Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): unify unread state and read synchronization

Generd86c18e043e5
diff --git a/assets/app-store/duo-2007x2853/01-share-agents.jpg b/assets/app-store/duo-2007x2853/01-share-agents.jpg
index a64d06578..9ae32a3ee 100644
Binary files a/assets/app-store/duo-2007x2853/01-share-agents.jpg and b/assets/app-store/duo-2007x2853/01-share-agents.jpg differ
diff --git a/assets/app-store/duo-2007x2853/02-teamwork.jpg b/assets/app-store/duo-2007x2853/02-teamwork.jpg
index 65208a8f7..29e37644d 100644
Binary files a/assets/app-store/duo-2007x2853/02-teamwork.jpg and b/assets/app-store/duo-2007x2853/02-teamwork.jpg differ
diff --git a/assets/app-store/duo-2007x2853/03-companion.jpg b/assets/app-store/duo-2007x2853/03-companion.jpg
index 6fbed5253..6d17f93f1 100644
Binary files a/assets/app-store/duo-2007x2853/03-companion.jpg and b/assets/app-store/duo-2007x2853/03-companion.jpg differ
diff --git a/assets/app-store/duo-2007x2853/04-context.jpg b/assets/app-store/duo-2007x2853/04-context.jpg
index f4fc649a8..017f7b143 100644
Binary files a/assets/app-store/duo-2007x2853/04-context.jpg and b/assets/app-store/duo-2007x2853/04-context.jpg differ
diff --git a/assets/app-store/duo-2007x2853/05-phone.jpg b/assets/app-store/duo-2007x2853/05-phone.jpg
index 2dc51cdf3..2433ca312 100644
Binary files a/assets/app-store/duo-2007x2853/05-phone.jpg and b/assets/app-store/duo-2007x2853/05-phone.jpg differ
diff --git a/assets/app-store/duo-2007x2853/06-existing-setup.jpg b/assets/app-store/duo-2007x2853/06-existing-setup.jpg
index 300ed05ae..8e11785c1 100644
Binary files a/assets/app-store/duo-2007x2853/06-existing-setup.jpg and b/assets/app-store/duo-2007x2853/06-existing-setup.jpg differ
diff --git a/assets/app-store/manifest.json b/assets/app-store/manifest.json
index 244bcf260..9caed768d 100644
--- a/assets/app-store/manifest.json
+++ b/assets/app-store/manifest.json
@@ -1,10 +1,10 @@
{
- "renderer": "155.0.8059.85",
+ "renderer": "156.0.8078.48",
"encoding": "RGB JPEG quality 80",
"clock": "2026-10-25T00:00:00Z",
"locale": "en-US",
"timezone": "UTC",
- "repositoryHead": "bf829d93a220f3797d1a395712bdde8a7abe73c4",
+ "repositoryHead": "58d73359f9714278c37453c6146c9d1c75521e19",
"inputs": {
"scripts/ci/pnpm-lock.mjs": "c6ad91cbd38cc08234e2da4122079d76bfef5eb61560862018cbab9d3e29f4cc",
"src/shared/src/billing.ts": "53d36e6bbab90d72ae86b9748d97bef4116a7f567d8587067f469d294c562b4a",
@@ -237,7 +237,7 @@
"src/web/src/components/community/messages/caret-text-insertion.ts": "7f3e0a70a1cbc76470d524a1eeceff77c14dd102b8593d2fa540a35f0f106660",
"src/web/src/components/community/messages/channel-ref-pill.tsx": "ed5f6ef481877ee63b9635f9a62624311060ecbffbb25a2338f22993a26f63ba",
"src/web/src/components/community/messages/composer-accessory-rail-layout.ts": "50ef57a41de96183fe956a85e360d5b9f5bfbc483fe0940cbfd6d14e7f49a645",
- "src/web/src/components/community/messages/composer-accessory-rail.tsx": "ba53382043ad165df75c9327184459f2c1018c68d2d9994a64ffb58bdd280e07",
+ "src/web/src/components/community/messages/composer-accessory-rail.tsx": "ede856478b4ef4ce636e1dbf15bdae8f34f0db6f0ac16678462f7f4f7ddcdebe",
"src/web/src/components/community/messages/composer-file-utils.ts": "1df082cd48b29632365fc33e61338439fecd7b750804fb3449859a121f7f82c1",
"src/web/src/components/community/messages/composer-keydown.ts": "42c4e454c7b0049632dcc4147de40090df6fc6f9614ba537755924d40249713d",
"src/web/src/components/community/messages/composer-ordered-list.ts": "5d6f44700df6c4e0116502210c68be8b6da363e6b54e0fcb1332385c4f110e63",
@@ -256,7 +256,7 @@
"src/web/src/components/community/messages/message-body-view.tsx": "4b5579de425640960a680b45043aada435a03b16afeaa59fe6aeebc19fb63905",
"src/web/src/components/community/messages/message-body.tsx": "0f43cb0c2c8eb3b507efc1f93e926d0cc9226f25173cc9e2fa8f2d8815c46ffd",
"src/web/src/components/community/messages/message-external-link.tsx": "ba22b8bfd1210f9645aa10c46a95c3d409cf87e68e0585709007f9bba1ad9d82",
- "src/web/src/components/community/messages/message-list-controller.ts": "d71b68e94985e23a2cbee050e0d7a318132e7441ece4ee3fc02ea6c8f776ce44",
+ "src/web/src/components/community/messages/message-list-controller.ts": "2f6d71a0905578f69fd0bf9c00227869d2c0a7007cafee36503abd93078f2070",
"src/web/src/components/community/messages/message-list-row.tsx": "e9b1e1d66b176821d96aca65e9a277aafdc96012f984a7758bff844a4b395a41",
"src/web/src/components/community/messages/message-list-view.tsx": "3fd669f94dd5cb655b91b103264d85de119589950c36c49454926421a078291e",
"src/web/src/components/community/messages/message-list.tsx": "6f4ddce666fc31c4e755e1f7608ebc433c4b1bde5a0177ed2d61759140ba0dd8",
@@ -392,28 +392,27 @@
"src/web/src/contexts/community/current-user.tsx": "9f87a44b03447614fe3bbaabc4c8956a0476e7386915808f9c2d767d776adeac",
"src/web/src/contexts/community/module-route.tsx": "94f36201313f5b5d87c3aadb465166817a731730181608642cec5a1e51e69164",
"src/web/src/contexts/community/route-frame.tsx": "a9a9b872b53c15d9f642a169649f99bb6414629bf7a03af3d3c5293d1df15f68",
- "src/web/src/hooks/community/account-unread-projection.ts": "118173e475c519db06a05e92d08c7f57396235beb689865bdd2f991e56e865e3",
"src/web/src/hooks/community/channel-metadata.ts": "151aeb7e24cfce79e00ccd73e1e479249ba0f6651aa869417ec8f1af28a7ab59",
"src/web/src/hooks/community/community-origin.ts": "aee72eac1133efddaa04d1f5622fd98704c13e751514cc1b0d4b0d1ab9e52cae",
"src/web/src/hooks/community/community-ws/cache.ts": "e063b7a235e0cf8ad453bc389ea60597a5a45d907b3602ce1ecc9f24d434b065",
"src/web/src/hooks/community/community-ws/channel-scope-projection.ts": "8f966b6ddce266450fabaa8ea6cd36dfc1ee8e22113cc650012d1313acb3e403",
"src/web/src/hooks/community/community-ws/connection-status.ts": "8c56a26869bb0e9c993c34ea0c1a3e0b128f1a8124644a8601629e30a56b02b7",
"src/web/src/hooks/community/community-ws/identity-events.ts": "7c01589fe61b138bbe7081a8aa0993ce99e4a23539143002c6d3613d1b3fe480",
- "src/web/src/hooks/community/community-ws/invalidation-projections.ts": "d948ce7a9c65ae3ce9980cf02aae469c2593e3f01d65efcd15e6ff9e0ad077dc",
- "src/web/src/hooks/community/community-ws/membership-events.ts": "c71bc9416b13d69690a4f4e153d51d7ffd3199a1c344fc953e909a0b6c537ce1",
+ "src/web/src/hooks/community/community-ws/invalidation-projections.ts": "b088cd2c03ffd88e1e236f8aacd22ac8530800ecd6a455ce2156cfadc8d7e7fb",
+ "src/web/src/hooks/community/community-ws/membership-events.ts": "3a1e3a7ec42e7802c4736685e8f65981d13748605b61087d30fcc79572921345",
"src/web/src/hooks/community/community-ws/message-events.ts": "780ce7915c80bd678f90e2659e003c5d4fcece85fb7bd9df6bd3e4a9c46fd790",
"src/web/src/hooks/community/community-ws/pii-events.ts": "ea7a0f73facfa489c4910646c2fd3cc7e60fc36e9e98daebda4786792c6d6ae6",
"src/web/src/hooks/community/community-ws/presence-machine-events.ts": "d4b9c5cf790aec8677a6ae7e71386d695dc83aee4da623658f797404ed5b7426",
"src/web/src/hooks/community/community-ws/projection-transaction.ts": "5f4b848c4d039fc845b34ea19ae54db73486f0a84e9181ebecb95a57b4a3275e",
"src/web/src/hooks/community/community-ws/reaction-details-invalidation.ts": "33553bfddf9f3e7b35cf6127cce2bb132f8b7c40e519d93cc7c5c74ea7f967c0",
- "src/web/src/hooks/community/community-ws/read-state-reconciliation.ts": "0012ff8b076604c722586e579b6af15311f8455b4a849e562c384b4da87e1073",
+ "src/web/src/hooks/community/community-ws/read-state-reconciliation.ts": "da3e7b7cde19dbdc845b5a207de2c3a01bd055a30d12c7c10877e40f17fc73ef",
"src/web/src/hooks/community/community-ws/reconnect-messages.ts": "c2bba29c116268bf043a0c9b01582504f6aadea9f29a1c688c9ab4e64fd51135",
- "src/web/src/hooks/community/community-ws/reconnect.ts": "f5337b74e93d3ba396c985adcb822dbc8fc30ce94c1b9c30d45d6940d1a415e2",
+ "src/web/src/hooks/community/community-ws/reconnect.ts": "990f4d323bf519e605293715866a122975dd83e45de86eca9be17eaa1aecbafa",
"src/web/src/hooks/community/community-ws/registry.ts": "68020314e8efa987c4885070d80a567ae33f4683db11ae8d0752b860e47a6ed1",
"src/web/src/hooks/community/community-ws/scope-eviction.ts": "fc96e1b312860f2e8025c6476a0cc9eecc0c52147897908e406642fde9ab3d4c",
"src/web/src/hooks/community/community-ws/server-rail-reconciliation.ts": "0d8e3fff2b64bb4af50b9781a4d47d85f8b74e1c31dbe41a8c8f20c37dcbabf1",
- "src/web/src/hooks/community/community-ws/social-events.ts": "7ef9faf5365cbe6a8f09ace818ce33d367574c9085625324c9eb1f23820c3250",
- "src/web/src/hooks/community/community-ws/structure-tree-events.ts": "38e3afc10b63bbc6083469305c5631adc4cb99748cd81b742d913fd60444cedf",
+ "src/web/src/hooks/community/community-ws/social-events.ts": "4d1802b9857a15734091ae271002d1cd90694925574ecd7ccdf9084e33c41db4",
+ "src/web/src/hooks/community/community-ws/structure-tree-events.ts": "e821b9bd9f2161d225452671c367dbba32c73b2103e1e339fdd696d9454aa49e",
"src/web/src/hooks/community/community-ws/typing-events.ts": "fca7e85e4fdd257bbf40b3593b154def5a4b82aaa35df84bdb7ec82efaf11921",
"src/web/src/hooks/community/community-ws/typing.ts": "1a353079e44e137eaef58f54223d40c1e07b4730c5a523048b923fed3ee0f888",
"src/web/src/hooks/community/fetch-all-server-members.ts": "6dcc38800c59590e09cde5bce56852bebfa98f1ba20fef23e16946f4e007a08e",
@@ -421,25 +420,24 @@
"src/web/src/hooks/community/forum-opener-title-reconciliation.ts": "94882e7861f95e7fa3ab7531795e773b0136a7140c6d93b4edeb9e836c491a27",
"src/web/src/hooks/community/inbox-read-reservation.ts": "59a5ba15d907884db551ed225233d6cdd159f77606165a106d1e5f190d33a7d0",
"src/web/src/hooks/community/mutations/bot-creation.ts": "1cd74b5b86dabe76fccebfaf1532557933c076f5459545e71f0118ad02121a11",
- "src/web/src/hooks/community/mutations/channels.ts": "14d008fdc4f8bf8c5d2770c0ce07f80ff192d51217920ce77c8912c8236fa873",
+ "src/web/src/hooks/community/mutations/channels.ts": "e36c6b7917284841dd8c746381b20d4eb0d5c3a43bc11d5573c586e64fe5bfc5",
"src/web/src/hooks/community/mutations/dm.ts": "3b0df4df34ddf42f2e81b0b4090a7781dfafa2fa95507c4e5cc71243c076fa70",
- "src/web/src/hooks/community/mutations/forum.ts": "f6b3ebbdd0ce6d0c7f2694dadd58ea2951052158aff8944a00601fc311181ec5",
+ "src/web/src/hooks/community/mutations/forum.ts": "3a70a6364faec466a03a97e7ff96939932d64006e955b119cf066743b3a2627e",
"src/web/src/hooks/community/mutations/friends.ts": "9ae43ab3aa399ce24fec970b7f1cdc189c847ec5b9ddaf060616e0f919f45eb0",
"src/web/src/hooks/community/mutations/index.ts": "7787dca5a073c2367c1196bb6e39d54bc8cfbec7b2b3cdaf2abf56b5e8090e1e",
"src/web/src/hooks/community/mutations/invites.ts": "8aaf81690176230c7cbf65e4c4e63f488c99fc4ae6961ab91a29a86a1cc7b935",
"src/web/src/hooks/community/mutations/members.ts": "e36736a85e706b4c37286d9f45f34f6641f7ee3e997171f2eff2e274379c6cbe",
"src/web/src/hooks/community/mutations/message-memberships.ts": "3a77e3b7b5323f5457a1f7fe7ca1fce5f5bbab513318476b1ff6fb7474138b6e",
"src/web/src/hooks/community/mutations/message-reactions.ts": "1f2a32eaf8853a4f4bbb9c7b1c845f4d416de5a8617cd866790aa70a3088dba4",
- "src/web/src/hooks/community/mutations/messages.ts": "051845429ee21fb0a97a8456d27b44ec630024d1334f1eb6474ef0424edfc8ec",
- "src/web/src/hooks/community/mutations/notifications.ts": "db51bd876de9dd22ca51ce7c0e13d443704c16e58a66767030acd642e49c0cdd",
+ "src/web/src/hooks/community/mutations/messages.ts": "3cf045a1a918263c550ed5bab16dfcd5bd638d77ffd04214eec617801c2fc1f5",
+ "src/web/src/hooks/community/mutations/notifications.ts": "8795f50ac099568b1017652c11c78e8c66288cbfd66caeb1b24a411ac77cff69",
"src/web/src/hooks/community/mutations/profile.ts": "8f6a04c35ccfe7b9277be15892d44afd89220e1b3c06cebbc8291a7ca1654a26",
"src/web/src/hooks/community/mutations/server-rail.ts": "df160394f6077f51f226d0de934b373fadb349f5ec4e0affb376a3a95c20c06e",
- "src/web/src/hooks/community/mutations/servers.ts": "ba9b5fec4ce4856d5e38b16227b15d1ba00b79e5c58a6fd99f77d53106b434e3",
+ "src/web/src/hooks/community/mutations/servers.ts": "09a17c19bd93b80ce6218f10f0b9a7441ea10db8184ae8a864cb6002c7457f72",
"src/web/src/hooks/community/mutations/uploads.ts": "e5c1dd10997f62dc12be31fe9f198fa23ac7774033df3b2aa017f21962493c36",
"src/web/src/hooks/community/read-coordinator-snapshot-projection.ts": "cb910681f3832b99bdc080c7263e4cb1b93d08068b615e0b5b65c9c51673a325",
- "src/web/src/hooks/community/read-coordinator.ts": "69056d826b210c3d244b6b702c78551f77e1ed9e4a765736daec55eb078943e8",
"src/web/src/hooks/community/unread-presentation.ts": "34545682942b75202315747f48a8b2f1b8aa3a4a173da80b74f2c8d21b71145f",
- "src/web/src/hooks/community/use-account-attention.ts": "34bafae5b02e94e74ee935a51fbb71223d823cd90ab3ff9d6520a858d550f19f",
+ "src/web/src/hooks/community/use-account-attention.ts": "3a4e61944de697441383be2c2f098b6faee48502415d47f33f7d8012e0562972",
"src/web/src/hooks/community/use-bot-audit-log.ts": "0dd56e81e5331f764bfc7e54f423fc0018c67dc315755a8eb78ce5e4c8950e67",
"src/web/src/hooks/community/use-bot-audit-preview.ts": "7d35c8b27517a90b5876b4e7fa9471567ae06aa62071708ae2422c11ce1a41bc",
"src/web/src/hooks/community/use-bot-bug-report.ts": "1e773d546d425cd65c93d8b0f7a20bb51e34273ec3803992f9029b404413a14c",
@@ -450,23 +448,23 @@
"src/web/src/hooks/community/use-channel-ref-directory.ts": "fd9c6444388e758ca27e47d149669bad6760ca06dbc033519d7ec0f3366b74de",
"src/web/src/hooks/community/use-community-command-mutation.ts": "a07e121e349a2f49db001686c68ff6073f47050806ae84002ee7292715955c65",
"src/web/src/hooks/community/use-community-view-source.ts": "052e7e0228ca7629d56568895e848f0647febbb1dbad3f1a0435afb9dcdaadbf",
- "src/web/src/hooks/community/use-community-ws.ts": "dc60473c5f60a5d7706c352fcb9e71861f253d4082ebc4bfc7d4e01142a57324",
+ "src/web/src/hooks/community/use-community-ws.ts": "aa53529cf2f3e107786bdce6982a277c08a07948a625d2bfd2295292e5267b2d",
"src/web/src/hooks/community/use-dm-message-sender.ts": "0dbd65cfe19914a8114ed13673f831ec7860f847b0bda8decbc74f82efc9a61d",
- "src/web/src/hooks/community/use-forum-sidebar-threads.ts": "0bb24651bc2baf628e2bed3be0ab16838ba30e11aa365c4faa79b59d6c857a83",
+ "src/web/src/hooks/community/use-forum-sidebar-threads.ts": "d406e93a277b4950bfd74b30e8583bf83055c0e11341ddc4e041512153b50352",
"src/web/src/hooks/community/use-friend-request-action-state.ts": "557902714b48aea69149571d9555b95f7c0e20abdbc0d69acd5baf83fef2e5ae",
"src/web/src/hooks/community/use-friends.ts": "ac3dc8c659c697784765b03b1610701b34b08497433ed4aae1ec6982aaec3204",
- "src/web/src/hooks/community/use-inbox.ts": "35ccc21841eca5855e018d2b2fc4b0869c678e03616bc351e7c01e6d53b95070",
+ "src/web/src/hooks/community/use-inbox.ts": "cb21c25c6c25edb7a493a4cddde9b0d6635480f8b6d7d981c5aa5e1eae57c142",
"src/web/src/hooks/community/use-invitable-friends.ts": "b3af46bcf7f917c87ea018589f2b96b3cf7ae7dec1ac060c3f290687931b858d",
"src/web/src/hooks/community/use-machines.ts": "5f8e8101ea623ca0266686ad2733906ed9e3d3e77cc4baeae8be0ced8bbb721c",
- "src/web/src/hooks/community/use-message.ts": "8a664702fe814a40133a64320caff007e5dc71514363a19cf51ccbc68b3d76f1",
- "src/web/src/hooks/community/use-notification-settings.ts": "0db37850b00de871726be46e40fdc38943328363fb51496ad6b8fe7bc6f08c7c",
+ "src/web/src/hooks/community/use-message.ts": "a3872c582ca42bb05320ca333cf71d26205dfe6fd281bbb7e070e735034f5e27",
+ "src/web/src/hooks/community/use-notification-settings.ts": "0896bc7b00d6463db0e8e4f934f73d7d7237de1a961ecd2c23dc35c0c3096365",
"src/web/src/hooks/community/use-reaction-details.ts": "20775d1e585c2b4be3d356114ff3dc611b9639375c4cc5648d45daa41d7ae847",
"src/web/src/hooks/community/use-running-owned-bots.ts": "db751eb7c096c0280a8c36d5a8a8039904331e8762c10b6957b61c898cee8f99",
"src/web/src/hooks/community/use-runtime-models.ts": "96c78069340df4a23b6b10ab2571b5c06754bfa7f989444c69152680c1933efb",
"src/web/src/hooks/community/use-scroll-anchor.ts": "d06f16ed85ecf2bc1a14cd2143a6c57e16846ff72b4c2dcb932e8fc30b1f1e88",
"src/web/src/hooks/community/use-server-members.ts": "1033e6e20ff4ec321902839c44ab744cd93ada7113c9f1d92484a1a661931ad2",
"src/web/src/hooks/community/use-server-panels.ts": "2c56d8a051f11b167845fe584827d6e648d2cd8740636f001f51ec1f1a9cbf6d",
- "src/web/src/hooks/community/use-servers.ts": "af9f458cc99d4b18ff15212fbee395a3abcd84fc92780d4907fa10dd9302ec0a",
+ "src/web/src/hooks/community/use-servers.ts": "191cad47a31cf12a0f1bd5546f3c6cd6afbfe877a2029c5b83cc957a80099c56",
"src/web/src/hooks/community/use-user-profile.ts": "4cf36a19dc34349eaf6e71060390cdc3e5e84c8e5e8a19fc5cb5435dff25dc13",
"src/web/src/hooks/community/use-virtual-cursor-pagination.ts": "173fedcd81119130906467fc01e7236aa51cbc36cacc5bcc84baf369ccc235a2",
"src/web/src/hooks/community/virtualizer-react-options.ts": "a5e918108000070d2d4de84ff58b9a5430e62ad99e1d1f892e3c8349cd5cabe1",
@@ -493,12 +491,12 @@
"src/web/src/lib/avatar/theme.ts": "b1b2dd1df0c509b090b1fdb3b57e714bb4e97d5da78c1cc3d5c5331ac3e39692",
"src/web/src/lib/community-db/collections.ts": "5969d9864b1518e2c6cdb782bdd0118e41b37610b06b88dd34dde88ca40d6081",
"src/web/src/lib/community-db/live-query.ts": "a43a9c28951cc952fadc6816a1cd119a0af9aea78525d44255bd378f6d409629",
- "src/web/src/lib/community-db/message-access-scope.ts": "dc071f7af87cb9a05f9784427ce1580b4bfa27f3daf684cb8f6bacdef36498bf",
- "src/web/src/lib/community-db/projections.ts": "679a68175edc16a29204a8b6cfd37cebb1de33c8a143a31b6fcaf7a1c1e55f20",
+ "src/web/src/lib/community-db/message-access-scope.ts": "c4d11a1000db036e3b6a237b53191fc5b6aed1f0766d64e81f8ac4a2e62a4f95",
+ "src/web/src/lib/community-db/projections.ts": "07588cd5d5ba0465852ee6299463b26283b001463bcf09511ab86b5e5df00692",
"src/web/src/lib/community-db/queries.ts": "2c33d376ee69510d2367a832f1887da00ede94e2a424bc4ee2c478809dccd16a",
- "src/web/src/lib/community-db/schema.ts": "a863c9929c03fd670e7700c997e7e27722943fbdf11fc6a48e027a1b3ca9600b",
+ "src/web/src/lib/community-db/schema.ts": "b705e6de4f1707737d406b33c63396fd10447ae98da9fb28069c40c71a8151f4",
"src/web/src/lib/community-db/server-rail.ts": "fee03f44f6aa6fbc1a801a5f2ac143dec2c1c6a7bec2aac3f03e7fe3760c1855",
- "src/web/src/lib/community-db/sync.ts": "af2b69f0627d8638d618730556bf95e89045a25d2f8a7599234df0e316d373d7",
+ "src/web/src/lib/community-db/sync.ts": "5e27b37bf910773ee4c56274a9d128a2660326f1bb12a414f47695ebc309ea46",
"src/web/src/lib/community-db/write.ts": "d2741760ebe6b5cbe5d2e730cfc85172f21400b51b466a2f560dec18ffdccf3b",
"src/web/src/lib/community-onboarding.ts": "235c16a80688f783e2785fe5538b954fc30607f87b51c17bb73a06a80c87c04f",
"src/web/src/lib/community/account-cache-lifecycle.ts": "03ff89ee6dbe39c8f0766e91a9df9ef54967923fabe06bf7a339b59818f537e0",
@@ -529,7 +527,7 @@
"src/web/src/lib/community/eject-server.ts": "d4048569cec8b2abcfa84c31df82699df8dbe2bd25b918130d66349f55e43e9d",
"src/web/src/lib/community/format-time.ts": "b5ab2ddf6552b4db1f217b32eb8bead713bdaf3ec015399352688e513d24b5a2",
"src/web/src/lib/community/forum-sidebar-window.ts": "5262fdc26d684baf0a3e815db3e7e1b14ff173a825b0ec93d78f6108653a17e8",
- "src/web/src/lib/community/forum-sidebar.ts": "74447916ababee3bcf49f286c4224f25be359008b864cc4f2950413241bb8182",
+ "src/web/src/lib/community/forum-sidebar.ts": "bd6fb6ce307aca6eb259f09cd9b52b9a0165df21d1ac1961d2ada6fc12955c8e",
"src/web/src/lib/community/friend-requests.ts": "0ee58fd3b2576d8fcb8f3b27bbb3d6982bb5061a7240a73b9964ea3034dbd4bd",
"src/web/src/lib/community/funnel-analytics.ts": "fba0236dcd932395405ea3fc11edb07e3ed028c673c02a960554fc9d72406347",
"src/web/src/lib/community/highlight-range.ts": "469677da44acca865954e53696144f53897b160668016659eddb85e82b43e4b6",
@@ -602,7 +600,7 @@
"src/web/src/lib/product-analytics.ts": "72c3410a8c79b37311200d0ef9c6375deefae038aedc736c414bb8779adf563e",
"src/web/src/lib/query-client.ts": "2fa0ba02e04bd287ff9c1d058a7a685499aa2ab40fb1d41b28872d3c24a9bc17",
"src/web/src/lib/query-keys.ts": "2668f3d6524d3139866cd2dc375c8d8905c3024d0d398769dba4c7b138850d2e",
- "src/web/src/lib/query-persister.ts": "bbe0207b054d66993ea5d741436732eae24a8a9af7fb7335b095ac947ad247bc",
+ "src/web/src/lib/query-persister.ts": "1b66a36d867dc1eb9ad76c4c870292e0dbf704f47cfe6a76373eedbe57153a6f",
"src/web/src/lib/service-worker/cache-identity.ts": "398f6799d7768f50ed6cc5ac9cd80a60be3383fe292890b1135c4e508e96bdb1",
"src/web/src/lib/service-worker/public-cache-storage.ts": "8857e70e77421e64ae9912fcf285548382c418f5d8d17e46e6280aee80e8a733",
"src/web/src/lib/streamdown-plugins.ts": "20295ea3fc6d583a301db5f9f766fdedf03584053843bc879836900c07f77a7d",
@@ -615,10 +613,10 @@
"src/web/src/stores/community/index.ts": "cb7ae7859fec81d48bbe8ec0d93272d356be44fa62c2a997167cb7e25b06ae5f",
"src/web/src/stores/community/message-stream-store.ts": "34a0e533c91a3f297832beaa090637a48f948a7b87dddd7fc7b5b5a0f61cc4ef",
"src/web/src/stores/community/profile-preview.tsx": "61a2e3c366fcfb0b4de78889e1f4ba9bb408a20b726cff7c4cfacb98ac0a9d9b",
- "src/web/src/stores/community/runtime-owner.ts": "24e2db673c72d590acbc91c3ca36ca24c7319dc3a9abd9e2aaf79ff628f38ee4",
- "src/web/src/stores/community/runtime.tsx": "96d7710bf5d7b0dc9127e3956f8bef844ddc5b7883fce03669434f28a8adfa39",
+ "src/web/src/stores/community/runtime-owner.ts": "578248ebba1c9de30400a886ccb3b6a739527231d66e39768c8cda5a0c556c67",
+ "src/web/src/stores/community/runtime.tsx": "7dfe06973fd76fb7578fa97bac4c929407acc4b74ed7a66a539fe54352ba0307",
"src/web/src/stores/community/ui-store.ts": "2ab58777ac468b11ba08db367aab27ff19ab379f263243e3d5aad75bfe4aa5ea",
- "src/web/src/stores/community/ws-store.ts": "dae006a2047a7edfd4eb1d9ef9a3d5eabaa7c12b8dbf89e13755a0768d370706",
+ "src/web/src/stores/community/ws-store.ts": "06abdb9dc85fa41b6b4afd97a052dc4e8f4c599e1101ad05c7875589078297ca",
"src/web/src/stores/community/ws.ts": "b834d01ab5ca62ecc846d5025b15793b73d84ddbff67d27cbef7b1d762449961",
"renderer:pnpm-dependencies": "2a2f4aade85e54767f09e17368084f17ca87080008b892a74eb6eb27d2ec2134",
"patches/@[email protected]": "51d33f6e4f128a90fe02d40ba5c0f2cd5614eabbab780845f28186dc473cab0a"
@@ -628,7 +626,7 @@
"path": "phone-1206x2622/01-share-agents.jpg",
"width": 1206,
"height": 2622,
- "sha256": "67c08bcbe2abaf278d95807ee67f0bde4194e1db2a38dffd370a21c3f02a138f",
+ "sha256": "8ea52c42d5e609ec3356a3c6d14dd6e029019f1760b9e75c4213795590010e43",
"surfaces": [
{
"scene": "workspace",
@@ -654,7 +652,7 @@
"path": "phone-1206x2622/02-teamwork.jpg",
"width": 1206,
"height": 2622,
- "sha256": "449e517899bf6dca21feb6ba9bb4e396fe2dad45309af91a76dc3daf5288dcb3",
+ "sha256": "add088d8ee0e7025b12319633bfbe64531ab660841faa0f8fa2de06c65b245cb",
"surfaces": [
{
"scene": "workspace",
@@ -680,7 +678,7 @@
"path": "phone-1206x2622/03-companion.jpg",
"width": 1206,
"height": 2622,
- "sha256": "41992422965debf02f29d3ef5b6f3bb9c1e6a06edb93e2f0ca3872c1ef4cead7",
+ "sha256": "052587efc5557f46915e6d673f7af1f7527b6b50614e82590caaad94e6b33a49",
"surfaces": [
{
"scene": "identity",
@@ -706,7 +704,7 @@
"path": "phone-1206x2622/04-context.jpg",
"width": 1206,
"height": 2622,
- "sha256": "2662ad08618ef2a62efa93697b10b3f497990dbade7b93b847b99f1f94f199c3",
+ "sha256": "7aff1b04edb171c5379077c092d212cad2e190339394724ce75db3d42ed430ff",
"surfaces": [
{
"scene": "continuity",
@@ -741,7 +739,7 @@
"path": "phone-1206x2622/05-phone.jpg",
"width": 1206,
"height": 2622,
- "sha256": "9ea0770d0a086284493ecd59430f9568cc646156c77b4806d5e6a70b1403edcb",
+ "sha256": "48b911e0b0fd0abf337b6f66cbe85a3cbc83e10b8733a2f95d2030f4ef697f99",
"surfaces": [
{
"scene": "workspace",
@@ -767,7 +765,7 @@
"path": "phone-1206x2622/06-existing-setup.jpg",
"width": 1206,
"height": 2622,
- "sha256": "14c73e1c6f5fea3c6d02a2b5850077e137531ea1bc5e8260d0bc99466b788a21",
+ "sha256": "ef7716e477d72e694ae3f9e27ba359507109034474f8bfc20871eef3835b5e6d",
"surfaces": [
{
"scene": "workspace",
@@ -793,7 +791,7 @@
"path": "phone-1320x2868/01-share-agents.jpg",
"width": 1320,
"height": 2868,
- "sha256": "310b2e3df2ace678b5649543c301add45555f5057bcd9364c823c87c8ac1b6ba",
+ "sha256": "52d8cf32d86474a3ffd6950e9a5b736989f2f306bf9a4fb2326c087450c93787",
"surfaces": [
{
"scene": "workspace",
@@ -819,7 +817,7 @@
"path": "phone-1320x2868/02-teamwork.jpg",
"width": 1320,
"height": 2868,
- "sha256": "8e3dd3072d5b7828723b47b002c62bdf8fbf7c4e809e0197774e0adfd1750ec5",
+ "sha256": "346908178928b218416f52fef18c0f61d0f5d4e7e5a1228332cf004593032dde",
"surfaces": [
{
"scene": "workspace",
@@ -845,7 +843,7 @@
"path": "phone-1320x2868/03-companion.jpg",
"width": 1320,
"height": 2868,
- "sha256": "42794e949a7997c6d9c4a6fdca9e24396cd41bc310b3b0128dde24d5c0907d0c",
+ "sha256": "93dbabe22c7e77bc0fb1c9e3b24a42c859d1700c067b3c39a811907102ed09f9",
"surfaces": [
{
"scene": "identity",
@@ -871,7 +869,7 @@
"path": "phone-1320x2868/04-context.jpg",
"width": 1320,
"height": 2868,
- "sha256": "bd2d061c2f5f443dd6c34760a8b78708bde301a1a653f82a51bd5ae9e605caca",
+ "sha256": "58bc2850948f57ba04f74a12ec90654de400b4c327ac4c5b5a3f24b142a89a0b",
"surfaces": [
{
"scene": "continuity",
@@ -906,7 +904,7 @@
"path": "phone-1320x2868/05-phone.jpg",
"width": 1320,
"height": 2868,
- "sha256": "48c0436b8a9eb3ba5ba7799183866c698b3e7a87aac8dfaecd280360031465d8",
+ "sha256": "270e04dedb164cbf854c5596fcb20461cfb927d616fdc0c67578a0c5af627a2d",
"surfaces": [
{
"scene": "workspace",
@@ -932,7 +930,7 @@
"path": "phone-1320x2868/06-existing-setup.jpg",
"width": 1320,
"height": 2868,
- "sha256": "5deac2a6bdb05807993fe721fa194e0bfb5351bdefd4f9683e2b6c680ff9c378",
+ "sha256": "2233e52d9f379900773604602ed8425796438bf00db0371702dedb88db3578e0",
"surfaces": [
{
"scene": "workspace",
@@ -958,7 +956,7 @@
"path": "tablet-2752x2064/01-share-agents.jpg",
"width": 2752,
"height": 2064,
- "sha256": "90579226e073bf7dda3f07671d4c032a215c222de7acb2af4e90cfd6dc211e97",
+ "sha256": "fd4725e892edfa23221a34ee95644b1601510c1876406e28f17c4b6b8229cbd4",
"surfaces": [
{
"scene": "workspace",
@@ -984,7 +982,7 @@
"path": "tablet-2752x2064/02-teamwork.jpg",
"width": 2752,
"height": 2064,
- "sha256": "b103d966cff5c5595b5cea5f777196e280479b42725b5e9bc7e68fd3378cd88c",
+ "sha256": "6deb347b840adc93c2f638c7e5eec7a685c14682c5a1840ff1f608ed539a78af",
"surfaces": [
{
"scene": "workspace",
@@ -1010,7 +1008,7 @@
"path": "tablet-2752x2064/03-companion.jpg",
"width": 2752,
"height": 2064,
- "sha256": "78c9ad75a900f3853b322267545e64ebfe1958ecae42527cf490fed3842ae8f3",
+ "sha256": "f01345b44dda10df81300616a9e3176a947ab0fa2fbb7a7ef2bdf3270a3204d9",
"surfaces": [
{
"scene": "identity",
@@ -1036,7 +1034,7 @@
"path": "tablet-2752x2064/04-context.jpg",
"width": 2752,
"height": 2064,
- "sha256": "e2883c7d31f89234810cd9f77b6ad90100691f9e45ffe12a63dd7285403c07c5",
+ "sha256": "d3accee044a1710c7cda914673d229e6c2064e23741b4a133a34ec2eedffe202",
"surfaces": [
{
"scene": "continuity",
@@ -1071,7 +1069,7 @@
"path": "tablet-2752x2064/05-phone.jpg",
"width": 2752,
"height": 2064,
- "sha256": "93673a8d5eeb349eae8c5a7dc447767f1088262b0f275f45e49c11c621ace59a",
+ "sha256": "f5f1998a4efdbae47d10b766e60214e4729f180aa7521e76b14acc1bcb552f96",
"surfaces": [
{
"scene": "workspace",
@@ -1097,7 +1095,7 @@
"path": "tablet-2752x2064/06-existing-setup.jpg",
"width": 2752,
"height": 2064,
- "sha256": "71edd998847b991c77a7568183937f44cc4c1ce524dfd66c98d7684e0f5214d9",
+ "sha256": "471ee8c0f3bf0ec38c3c174b271ba95df3e8a39cbd218870206569b675394690",
"surfaces": [
{
"scene": "workspace",
@@ -1123,7 +1121,7 @@
"path": "duo-2007x2853/01-share-agents.jpg",
"width": 2007,
"height": 2853,
- "sha256": "41ba4dcb99285c74b855f1e824ac0a56413c101e5832e22dcbc0b4e3e4c70910",
+ "sha256": "9f026ce5bc0e0508f7d2faa6b742d7121e517dad09770bf3dd32f8c81d365c5c",
"surfaces": [
{
"scene": "workspace",
@@ -1149,7 +1147,7 @@
"path": "duo-2007x2853/02-teamwork.jpg",
"width": 2007,
"height": 2853,
- "sha256": "913c19fe269aac05993ddfd9c049ba281e1b9a827c7fdf508c72e2934722701f",
+ "sha256": "c0ad7bcd8dfcefbfa0fd560eecc165b3c6ce7dc273a1630a71453a736b8245fe",
"surfaces": [
{
"scene": "workspace",
@@ -1175,7 +1173,7 @@
"path": "duo-2007x2853/03-companion.jpg",
"width": 2007,
"height": 2853,
- "sha256": "627afc8590c0a790cd16e983d1e4f63125c975beff61a94b6bd9e8e0d5c15256",
+ "sha256": "16fb5c0b82b4acc8bb97697c498ad5e4dab0ceb6f9e3536eabed7672a22a3525",
"surfaces": [
{
"scene": "identity",
@@ -1201,7 +1199,7 @@
"path": "duo-2007x2853/04-context.jpg",
"width": 2007,
"height": 2853,
- "sha256": "e07f2aa40054fb36b53298e65028df5ffd14bf622495acf28dbe1dab1b615e02",
+ "sha256": "e95476c8129a50eb5a39167dfd17b44bb1587b84b39405e039872c5058c27bcf",
"surfaces": [
{
"scene": "continuity",
@@ -1236,7 +1234,7 @@
"path": "duo-2007x2853/05-phone.jpg",
"width": 2007,
"height": 2853,
- "sha256": "611a8268b8ed0cbde480d10cf428406a45f6d04ea129d5d627582d0be4df69b5",
+ "sha256": "d10a3ee6c826a6fd416b5c8d54667c1c53cbab8861a35c77a68c85e70a8b6f8d",
"surfaces": [
{
"scene": "workspace",
@@ -1262,7 +1260,7 @@
"path": "duo-2007x2853/06-existing-setup.jpg",
"width": 2007,
"height": 2853,
- "sha256": "610f42c74b1cfcbdaa8a11f011c84ffdccbbb03166c4e39ff758529a98769f49",
+ "sha256": "48d4b518796420c7f79a7b1fa99bbb742c293f43d257bf618a0d1aae5c795e57",
"surfaces": [
{
"scene": "workspace",
diff --git a/assets/app-store/phone-1206x2622/01-share-agents.jpg b/assets/app-store/phone-1206x2622/01-share-agents.jpg
index 583dc69cd..f919d92a7 100644
Binary files a/assets/app-store/phone-1206x2622/01-share-agents.jpg and b/assets/app-store/phone-1206x2622/01-share-agents.jpg differ
diff --git a/assets/app-store/phone-1206x2622/02-teamwork.jpg b/assets/app-store/phone-1206x2622/02-teamwork.jpg
index 3228858c4..2cf01610a 100644
Binary files a/assets/app-store/phone-1206x2622/02-teamwork.jpg and b/assets/app-store/phone-1206x2622/02-teamwork.jpg differ
diff --git a/assets/app-store/phone-1206x2622/03-companion.jpg b/assets/app-store/phone-1206x2622/03-companion.jpg
index 9a5df2a01..2acf61dde 100644
Binary files a/assets/app-store/phone-1206x2622/03-companion.jpg and b/assets/app-store/phone-1206x2622/03-companion.jpg differ
diff --git a/assets/app-store/phone-1206x2622/04-context.jpg b/assets/app-store/phone-1206x2622/04-context.jpg
index 30c4f4f5e..33d8fd47b 100644
Binary files a/assets/app-store/phone-1206x2622/04-context.jpg and b/assets/app-store/phone-1206x2622/04-context.jpg differ
diff --git a/assets/app-store/phone-1206x2622/05-phone.jpg b/assets/app-store/phone-1206x2622/05-phone.jpg
index 7ccbf89e4..4370a3589 100644
Binary files a/assets/app-store/phone-1206x2622/05-phone.jpg and b/assets/app-store/phone-1206x2622/05-phone.jpg differ
diff --git a/assets/app-store/phone-1206x2622/06-existing-setup.jpg b/assets/app-store/phone-1206x2622/06-existing-setup.jpg
index 7db7cd1b1..ff8201b1c 100644
Binary files a/assets/app-store/phone-1206x2622/06-existing-setup.jpg and b/assets/app-store/phone-1206x2622/06-existing-setup.jpg differ
diff --git a/assets/app-store/phone-1320x2868/01-share-agents.jpg b/assets/app-store/phone-1320x2868/01-share-agents.jpg
index 821306e5d..0b557dbf8 100644
Binary files a/assets/app-store/phone-1320x2868/01-share-agents.jpg and b/assets/app-store/phone-1320x2868/01-share-agents.jpg differ
diff --git a/assets/app-store/phone-1320x2868/02-teamwork.jpg b/assets/app-store/phone-1320x2868/02-teamwork.jpg
index 6a5af944b..587a9ef76 100644
Binary files a/assets/app-store/phone-1320x2868/02-teamwork.jpg and b/assets/app-store/phone-1320x2868/02-teamwork.jpg differ
diff --git a/assets/app-store/phone-1320x2868/03-companion.jpg b/assets/app-store/phone-1320x2868/03-companion.jpg
index 7c8320abb..c1ed3bca9 100644
Binary files a/assets/app-store/phone-1320x2868/03-companion.jpg and b/assets/app-store/phone-1320x2868/03-companion.jpg differ
diff --git a/assets/app-store/phone-1320x2868/04-context.jpg b/assets/app-store/phone-1320x2868/04-context.jpg
index da30d6a9d..04983d0c2 100644
Binary files a/assets/app-store/phone-1320x2868/04-context.jpg and b/assets/app-store/phone-1320x2868/04-context.jpg differ
diff --git a/assets/app-store/phone-1320x2868/05-phone.jpg b/assets/app-store/phone-1320x2868/05-phone.jpg
index e963dcec8..8c5bc4311 100644
Binary files a/assets/app-store/phone-1320x2868/05-phone.jpg and b/assets/app-store/phone-1320x2868/05-phone.jpg differ
diff --git a/assets/app-store/phone-1320x2868/06-existing-setup.jpg b/assets/app-store/phone-1320x2868/06-existing-setup.jpg
index 6e1e256b9..447a63bf2 100644
Binary files a/assets/app-store/phone-1320x2868/06-existing-setup.jpg and b/assets/app-store/phone-1320x2868/06-existing-setup.jpg differ
diff --git a/assets/app-store/tablet-2752x2064/01-share-agents.jpg b/assets/app-store/tablet-2752x2064/01-share-agents.jpg
index e857de6ec..69e1be68f 100644
Binary files a/assets/app-store/tablet-2752x2064/01-share-agents.jpg and b/assets/app-store/tablet-2752x2064/01-share-agents.jpg differ
diff --git a/assets/app-store/tablet-2752x2064/02-teamwork.jpg b/assets/app-store/tablet-2752x2064/02-teamwork.jpg
index 1b49ca210..a5a424908 100644
Binary files a/assets/app-store/tablet-2752x2064/02-teamwork.jpg and b/assets/app-store/tablet-2752x2064/02-teamwork.jpg differ
diff --git a/assets/app-store/tablet-2752x2064/03-companion.jpg b/assets/app-store/tablet-2752x2064/03-companion.jpg
index 7cc4be57a..0e39750c8 100644
Binary files a/assets/app-store/tablet-2752x2064/03-companion.jpg and b/assets/app-store/tablet-2752x2064/03-companion.jpg differ
diff --git a/assets/app-store/tablet-2752x2064/04-context.jpg b/assets/app-store/tablet-2752x2064/04-context.jpg
index 34c59e3e3..8e2e42d3c 100644
Binary files a/assets/app-store/tablet-2752x2064/04-context.jpg and b/assets/app-store/tablet-2752x2064/04-context.jpg differ
diff --git a/assets/app-store/tablet-2752x2064/05-phone.jpg b/assets/app-store/tablet-2752x2064/05-phone.jpg
index 915657df6..77b0998eb 100644
Binary files a/assets/app-store/tablet-2752x2064/05-phone.jpg and b/assets/app-store/tablet-2752x2064/05-phone.jpg differ
diff --git a/assets/app-store/tablet-2752x2064/06-existing-setup.jpg b/assets/app-store/tablet-2752x2064/06-existing-setup.jpg
index 801f53306..43bdb99f2 100644
Binary files a/assets/app-store/tablet-2752x2064/06-existing-setup.jpg and b/assets/app-store/tablet-2752x2064/06-existing-setup.jpg differ
diff --git a/src/web/src/app/c/QueryProvider.dom.test.ts b/src/web/src/app/c/QueryProvider.dom.test.ts
index ad71c9fd5..57dc3abbf 100644
--- a/src/web/src/app/c/QueryProvider.dom.test.ts
+++ b/src/web/src/app/c/QueryProvider.dom.test.ts
@@ -9,9 +9,6 @@ import { communityKeys } from "@/lib/query-keys"
let queryClient: QueryClient
const createQueryClient = vi.hoisted(() => vi.fn())
-const setReconcileScheduler = vi.hoisted(() => vi.fn())
-const getAccountUnreadProjection = vi.hoisted(() => vi.fn(() => ({ setReconcileScheduler })))
-const disposeAccountUnreadProjection = vi.hoisted(() => vi.fn())
const restoreResult = vi.hoisted(() => ({ current: "success" as "success" | "error" }))
vi.mock("next/navigation", () => ({ useRouter: () => ({ refresh: vi.fn(), replace: vi.fn() }) }))
vi.mock("@/lib/auth-client", () => ({ useSession: () => ({ isPending: true, data: null, error: null }), currentSessionViewer: () => undefined }))
@@ -36,13 +33,11 @@ vi.mock("@/lib/query-persister", async (importOriginal) => ({ ...await importOri
createIdbPersister: () => ({ persistClient: vi.fn(), restoreClient: vi.fn(), removeClient: vi.fn(), retireAccount: vi.fn(), isCurrent: async () => true }),
}))
vi.mock("@/lib/community-db/sync", async (importOriginal) => ({ ...await importOriginal<typeof import("@/lib/community-db/sync")>(), installCommunityDbSync: () => () => undefined }))
-vi.mock("@/hooks/community/account-unread-projection", async (importOriginal) => ({ ...await importOriginal<typeof import("@/hooks/community/account-unread-projection")>(), getAccountUnreadProjection, disposeAccountUnreadProjection }))
import { QueryProvider } from "./QueryProvider"
beforeEach(() => {
queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
createQueryClient.mockReset(); createQueryClient.mockReturnValue(queryClient)
- setReconcileScheduler.mockClear(); getAccountUnreadProjection.mockClear(); disposeAccountUnreadProjection.mockClear()
restoreResult.current = "success"
})
afterEach(async () => {
@@ -146,20 +141,6 @@ describe("QueryProvider profile account lifecycle", () => {
expect(invalidate).not.toHaveBeenCalled()
act(() => renderer.unmount())
})
- it("routes projection reconciliation through the canonical source prefixes", async () => {
- const invalidate = vi.spyOn(queryClient, "invalidateQueries"), renderer = mount("viewer-c")
- expect(getAccountUnreadProjection).toHaveBeenCalledWith(queryClient, "viewer-c")
- const reconcile = setReconcileScheduler.mock.calls.at(-1)?.[0]
- expect(reconcile).toBeTypeOf("function")
- invalidate.mockClear()
- await act(async () => reconcile())
- for (const key of [communityKeys.inboxUnreads(), communityKeys.inboxMentions(), communityKeys.dms(), communityKeys.servers()]) expect(invalidate).toHaveBeenCalledWith({ queryKey: key, exact: true })
- const predicate = invalidate.mock.calls.map(([filters]) => filters?.predicate).find((value) => typeof value === "function")!
- const query = (queryKey: readonly unknown[]) => ({ queryKey } as Parameters<typeof predicate>[0])
- expect(predicate(query(communityKeys.server("server-1")))).toBe(true)
- for (const key of [communityKeys.members("server-1"), communityKeys.channelRefDirectory(), communityKeys.server("__none__"), communityKeys.server("__pending__")]) expect(predicate(query(key))).toBe(false)
- act(() => renderer.unmount())
- })
it("releases collections after descendant subscriptions release on real retirement", async () => {
vi.useFakeTimers()
try {
diff --git a/src/web/src/app/c/QueryProvider.late-block-restore.dom.test.tsx b/src/web/src/app/c/QueryProvider.late-block-restore.dom.test.tsx
index 757f9c055..59dc227cc 100644
--- a/src/web/src/app/c/QueryProvider.late-block-restore.dom.test.tsx
+++ b/src/web/src/app/c/QueryProvider.late-block-restore.dom.test.tsx
@@ -61,7 +61,7 @@ it.each([null, false, true].flatMap(blockMode => (["accepted", "incoming"] as co
expect(ids).toContain("m2")
if (blocked) act(() => dispatchCommunityWsEvents([{ type: "community:friend.block", userId: "peer", ...(blockMode ? { blockedByViewer: true } : {}) }], {
deliveryMode: "batch", contract: 2, queryClient: registry!.queryClient, communityStore: registry!.runtime.ui, wsStore: registry!.runtime.ws,
- sub: { dmConversationId: "c1" }, viewerUserIdRef: { current: "viewer" }, matchesFocus: event => event.channelId === "c1", scheduleInboxInvalidate: () => {},
+ sub: { dmConversationId: "c1" }, viewerUserIdRef: { current: "viewer" }, matchesFocus: event => event.channelId === "c1",
}))
expect(registry!.runtime.ws.actions.isChannelAccessRevoked("c1", null)).toBe(blocked)
await act(async () => { release!(); await Promise.resolve() })
diff --git a/src/web/src/app/c/QueryProvider.tsx b/src/web/src/app/c/QueryProvider.tsx
index 7035650c1..b87535811 100644
--- a/src/web/src/app/c/QueryProvider.tsx
+++ b/src/web/src/app/c/QueryProvider.tsx
@@ -1,6 +1,6 @@
"use client"
-import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react"
+import { useCallback, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react"
import { useIsRestoring, type QueryClient } from "@tanstack/react-query"
import { ReactQueryDevtools } from "@tanstack/react-query-devtools"
import { PersistQueryClientProvider } from "@tanstack/react-query-persist-client"
@@ -16,13 +16,8 @@ import {
} from "@/lib/query-persister"
import { disposeAccountReadStateReconciliation } from "@/hooks/community/community-ws/read-state-reconciliation"
import { disposeReadCoordinator } from "@/hooks/community/read-coordinator"
-import {
- disposeAccountUnreadProjection,
- getAccountUnreadProjection,
-} from "@/hooks/community/account-unread-projection"
import {
communityKeys,
- isCommunityServerDetailQueryKey,
} from "@/lib/query-keys"
import {
createCommunityDbRegistry,
@@ -77,7 +72,6 @@ function CommunityDbRuntime({
})
disposeReadCoordinator(queryClient)
disposeAccountReadStateReconciliation(queryClient)
- disposeAccountUnreadProjection(queryClient)
void registry.cleanup().finally(() => queryClient.clear()).catch((error: unknown) => {
if (!isAbortError(error)) console.error("Community collection cleanup failed", error)
})
@@ -140,29 +134,6 @@ function ScopedQueryProvider({
})
const [restoreGate] = useState(createRestoreGate)
const [communityDb] = useState(() => createCommunityDbRegistry(queryClient, userId, { waitForRestore: restoreGate.ready }))
- const unreadProjection = useMemo(
- () => userId ? getAccountUnreadProjection(queryClient, userId) : null,
- [queryClient, userId],
- )
- useEffect(() => {
- if (!unreadProjection) return
- unreadProjection.setReconcileScheduler(() => {
- void queryClient.invalidateQueries({
- queryKey: communityKeys.inboxUnreads(),
- exact: true,
- })
- void queryClient.invalidateQueries({
- queryKey: communityKeys.inboxMentions(),
- exact: true,
- })
- void queryClient.invalidateQueries({ queryKey: communityKeys.dms(), exact: true })
- void queryClient.invalidateQueries({ queryKey: communityKeys.servers(), exact: true })
- void queryClient.invalidateQueries({
- predicate: ({ queryKey }) => isCommunityServerDetailQueryKey(queryKey),
- })
- })
- return () => unreadProjection.setReconcileScheduler(null)
- }, [queryClient, unreadProjection])
// Persister is bound to the userId at construction; on account switch the
// whole community subtree unmounts and the shell re-renders with the new
// id, so we don't need to reactively rebuild the persister mid-session.
diff --git a/src/web/src/app/c/community-shell.identity.dom.test.ts b/src/web/src/app/c/community-shell.identity.dom.test.ts
index 0b0e12555..fc9b46987 100644
--- a/src/web/src/app/c/community-shell.identity.dom.test.ts
+++ b/src/web/src/app/c/community-shell.identity.dom.test.ts
@@ -32,6 +32,7 @@ import { CommunityShell } from "./community-shell"
const registries = new Map<string, CommunityDbRegistry>()
const seen: Array<{ viewer: string | null; presence: string[] }> = []
+const selfProfileCalls = () => fixtures.fetch.mock.calls.filter(([path]) => path === "/api/community/users/me/profile")
const self = (id: string) => ({ id, name: "Jane Roe", discriminator: "4242", aboutMe: "hello", avatar: "new-avatar", avatarVersion: 3, statusEmoji: null, statusText: "" })
function Probe() {
const client = useQueryClient()
@@ -61,7 +62,11 @@ beforeEach(async () => {
}))
await clearAllPersistedCaches()
fixtures.user = { id: "user-a", name: "A", email: "[email protected]", avatar: "A" }
- fixtures.fetch.mockReset().mockImplementation(() => Promise.resolve(self(fixtures.user.id)))
+ fixtures.fetch.mockReset().mockImplementation((path: string) => {
+ if (path === "/api/community/users/me/profile") return Promise.resolve(self(fixtures.user.id))
+ if (path === "/api/community/users/me/read-state") return Promise.resolve({ revision: 0, readStates: [] })
+ throw new Error(`Unexpected bootstrap endpoint: ${path}`)
+ })
fixtures.notifications.mockClear()
registries.clear(); seen.length = 0
})
@@ -94,7 +99,7 @@ describe("CommunityShell actual identity and bootstrap boundary", () => {
const report = vi.spyOn(console, "error").mockImplementation(() => undefined)
try {
render(React.createElement(React.StrictMode, null, tree()))
- await waitFor(() => expect(fixtures.fetch).toHaveBeenCalledOnce())
+ await waitFor(() => expect(selfProfileCalls()).toHaveLength(1))
await waitFor(() => expect(registries.get("user-a")!.collections.profiles.get("user-a")?.aboutMe).toBe("hello"))
expect(report.mock.calls.flat().join("\n")).not.toMatch(/Cannot update a component|while rendering a different component/)
} finally { report.mockRestore() }
@@ -117,11 +122,13 @@ describe("CommunityShell actual identity and bootstrap boundary", () => {
it("physically cancels A's held self-profile and rejects its late payload after B mounts", async () => {
let finish!: (data: ReturnType<typeof self>) => void
- fixtures.fetch.mockImplementationOnce(() => new Promise((resolve) => { finish = resolve }))
+ const normal = fixtures.fetch.getMockImplementation()!
+ fixtures.fetch.mockImplementation((path: string, options: { authenticationAccount?: string }) => path === "/api/community/users/me/profile" && options.authenticationAccount === "user-a"
+ ? new Promise((resolve) => { finish = resolve }) : normal(path, options))
const view = render(tree())
- await waitFor(() => expect(fixtures.fetch).toHaveBeenCalledOnce())
+ await waitFor(() => expect(selfProfileCalls()).toHaveLength(1))
const original = registries.get("user-a")!
- const signal = fixtures.fetch.mock.calls[0][1].signal as AbortSignal
+ const signal = selfProfileCalls()[0][1].signal as AbortSignal
fixtures.user = { id: "user-b", name: "B", email: "[email protected]", avatar: "B" }
view.rerender(tree())
await waitFor(() => expect(signal.aborted).toBe(true))
diff --git a/src/web/src/app/c/community-shell.tsx b/src/web/src/app/c/community-shell.tsx
index fb6b2d20b..3ecff49d4 100644
--- a/src/web/src/app/c/community-shell.tsx
+++ b/src/web/src/app/c/community-shell.tsx
@@ -17,6 +17,7 @@ import {
} from "@/contexts/community/current-user"
import { useCommunityWs } from "@/hooks/community/use-community-ws"
import { useNotificationSettings } from "@/hooks/community/use-notification-settings"
+import { useAccountReadState } from "@/hooks/community/community-ws/read-state-reconciliation"
import { useAccountAttention } from "@/hooks/community/use-account-attention"
import { PerfTraceBootstrap } from "@/components/perf/perf-trace-bootstrap"
import { CommunityOnboardingForm } from "@/components/community/onboarding/community-onboarding-form"
@@ -80,6 +81,7 @@ function CommunityBootstrap({ children }: { children: ReactNode }) {
useNotificationSettings()
useAccountAttention()
+ useAccountReadState()
// Wire the WS handler once for the whole community subtree. `viewerUserId`
// powers the `me` flag on incoming reactions — passing null would leave that
// flag stuck at false for the viewer's own reactions.
diff --git a/src/web/src/components/community/bots/bot-pii-panel.dom.test.tsx b/src/web/src/components/community/bots/bot-pii-panel.dom.test.tsx
index b0405a9d8..a6249015a 100644
--- a/src/web/src/components/community/bots/bot-pii-panel.dom.test.tsx
+++ b/src/web/src/components/community/bots/bot-pii-panel.dom.test.tsx
@@ -1,5 +1,5 @@
import { expect, it, vi } from "vitest"
-import { render, screen, within, setupUser } from "@/test/react-dom-harness"
+import { act, render, screen, within, setupUser } from "@/test/react-dom-harness"
import { BotPiiPanel } from "./bot-pii-panel"
vi.mock("@/components/avatar", () => ({ AgentAvatar: ({ seed, avatarUrl }: { seed: string; avatarUrl?: string }) => <span data-testid="bot-avatar" data-seed={seed} data-image={avatarUrl} /> }))
@@ -21,6 +21,39 @@ it("scopes the bot selector and its change action to the PII Filters tab", async
expect(view.container.querySelector("header")).not.toContainElement(selector)
expect(within(panel).getByText("Pipeline content")).toBeVisible()
await user.click(selector)
- await user.click(screen.getByRole("option", { name: "Second" }))
+ await user.click(await screen.findByRole("option", { name: "Second" }))
expect(onSelect).toHaveBeenCalledWith("b")
})
+
+it("keeps pointer selection valid when opening waits for the browser animation frame", async () => {
+ const frames = new Map<number, FrameRequestCallback>()
+ let frameId = 0
+ const request = vi.spyOn(window, "requestAnimationFrame").mockImplementation(callback => { frames.set(++frameId, callback); return frameId })
+ const cancel = vi.spyOn(window, "cancelAnimationFrame").mockImplementation(id => { frames.delete(id) })
+ const user = setupUser()
+ const onSelect = vi.fn()
+ const view = render(<BotPiiPanel bots={[{ id: "a", name: "First" }, { id: "b", name: "Second" }]} selectedId="a" onSelect={onSelect}><p>Pipeline content</p></BotPiiPanel>)
+ try {
+ const panel = screen.getByRole("tabpanel", { name: "PII Filters" })
+ const selector = within(panel).getByRole("combobox", { name: "Bot" })
+ await user.click(selector)
+ expect(frames.size).toBeGreaterThan(0)
+ expect(selector).toHaveAttribute("aria-expanded", "false")
+ expect(() => screen.getByRole("option", { name: "Second" })).toThrow()
+ expect(onSelect).not.toHaveBeenCalled()
+ await act(async () => {
+ const pending = [...frames.values()]
+ frames.clear()
+ for (const callback of pending) callback(performance.now())
+ })
+ const second = await screen.findByRole("option", { name: "Second" })
+ expect(selector).toHaveAttribute("aria-expanded", "true")
+ await user.click(second)
+ expect(onSelect).toHaveBeenCalledExactlyOnceWith("b")
+ } finally {
+ view.unmount()
+ frames.clear()
+ cancel.mockRestore()
+ request.mockRestore()
+ }
+})
diff --git a/src/web/src/components/community/channels/dm-view.tsx b/src/web/src/components/community/channels/dm-view.tsx
index 47f684224..0a8cb299a 100644
--- a/src/web/src/components/community/channels/dm-view.tsx
+++ b/src/web/src/components/community/channels/dm-view.tsx
@@ -31,6 +31,7 @@ import { useDms } from "@/hooks/community/use-dms"
import { useFriends } from "@/hooks/community/use-friends"
import { useDmMessages } from "@/hooks/community/use-messages"
import { resolveMessageReadProjection } from "@/lib/community/message-read-projection"
+import { useMessageUnreadCount } from "@/hooks/community/use-message-unread-count"
import { useDmWatermark } from "@/hooks/community/use-dm-watermark"
import { useChannelRefDirectory } from "@/hooks/community/use-channel-ref-directory"
import { toChannelRefCandidate } from "@/lib/community/channel-ref-extension"
@@ -235,16 +236,10 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeCom
catchUp: () => refetchMessages(),
})
- // `↓ N` unread count. Same math as channel: server truth is
- // `latestSeq - viewerLastReadSeq`. Clamp to 0 in case the read pointer
- // overshoots (e.g. a race between the read-state snapshot and a fresh
- // `latestSeq` fetch).
- const unreadCount = useMemo(() => {
- const seenSeq = readSnapshot?.lastReadSeq ?? 0
- const diff = latestSeq - seenSeq
- return diff > 0 ? diff : 0
- }, [latestSeq, readSnapshot])
-
+ const unreadCount = useMessageUnreadCount({ channelId: dmId, viewerUserId: currentUser.id, messages,
+ entryReadSeq: readSnapshot?.lastReadSeq, latestSeq, historyStartKnown,
+ hasMoreNewer: hasMoreNewerMessages, ready: historyAllowed && !!readSnapshot && !readSnapshotFetching && !messagesPending && !messagesError,
+ })
const typingUsers = useTypingUsersForScope(`dm:${dmId}`)
const typingNames = useTypingNamesForScope(`dm:${dmId}`)
diff --git a/src/web/src/components/community/messages/composer-accessory-rail.dom.test.ts b/src/web/src/components/community/messages/composer-accessory-rail.dom.test.ts
index d93f44a86..a119f193a 100644
--- a/src/web/src/components/community/messages/composer-accessory-rail.dom.test.ts
+++ b/src/web/src/components/community/messages/composer-accessory-rail.dom.test.ts
@@ -24,8 +24,8 @@ vi.mock("@/components/ui/tooltip", () => ({
const baseProps = {
typingNames: [] as string[],
- scrollCount: 4,
- scrollMode: "jump" as const,
+ scrollCount: 4 as number | undefined,
+ scrollMode: "jump" as "jump" | "scroll",
onScroll: vi.fn(),
}
@@ -56,6 +56,7 @@ describe("ComposerAccessoryRail", () => {
const renderer = renderRail({
typingNames: typing ? ["Alice"] : [],
scrollCount: center ? 2 : 0,
+ scrollMode: "scroll",
})
const rails = renderer.queryAllByTestId(tid.composerAccessoryRail)
expect(rails).toHaveLength(layout === "empty" ? 0 : 1)
@@ -81,6 +82,17 @@ describe("ComposerAccessoryRail", () => {
expect(baseProps.onScroll).toHaveBeenCalledOnce()
})
+ it.each([undefined, 0])("keeps jump available without inventing a positive unread count: %s", (scrollCount) => {
+ const renderer = renderRail({ scrollCount })
+ const jump = renderer.getByRole("button", { name: "Jump to present", exact: true })
+ expect(jump).toHaveAttribute("data-testid", tid.scrollToPresent)
+ expect(renderer.getByTestId(tid.composerAccessoryRail)).toHaveAttribute("data-layout", "centered")
+ expect(jump.querySelector("mock-ticker")).toBeNull()
+ expect(jump).not.toHaveTextContent("0")
+ fireEvent.click(jump)
+ expect(baseProps.onScroll).toHaveBeenCalledOnce()
+ })
+
it("does not reintroduce WS or viewport-derived width ownership", () => {
const source = readFileSync(resolve(
process.cwd(),
diff --git a/src/web/src/components/community/messages/composer-accessory-rail.tsx b/src/web/src/components/community/messages/composer-accessory-rail.tsx
index f50882930..5470da9bf 100644
--- a/src/web/src/components/community/messages/composer-accessory-rail.tsx
+++ b/src/web/src/components/community/messages/composer-accessory-rail.tsx
@@ -17,12 +17,12 @@ export function ComposerAccessoryRail({
onScroll,
}: {
typingNames: string[]
- scrollCount: number
+ scrollCount: number | undefined
scrollMode: "scroll" | "jump"
onScroll: () => void
}) {
const hasTyping = typingNames.length > 0
- const hasScroll = scrollCount > 0
+ const hasScroll = scrollMode === "jump" || (scrollCount ?? 0) > 0
const layout = allocateComposerAccessoryRail({
mode: "normal",
left: hasTyping,
@@ -132,13 +132,13 @@ function ScrollControl({
mode,
onClick,
}: {
- count: number
+ count: number | undefined
mode: "scroll" | "jump"
onClick: () => void
}) {
- if (count <= 0) return null
+ const knownCount = count !== undefined && count > 0
const aria = mode === "jump"
- ? `Jump to present, ${count} unread below`
+ ? knownCount ? `Jump to present, ${count} unread below` : "Jump to present"
: `Scroll to bottom, ${count} more below`
return (
<button
@@ -149,7 +149,7 @@ function ScrollControl({
className="pointer-events-auto flex h-full items-center gap-1.5 justify-self-center rounded-full border border-border bg-background/90 pl-2 pr-3 text-xs font-medium text-foreground shadow-(--e1) backdrop-blur-sm transition-colors hover:bg-accent focus-visible:outline-none focus-visible:ring-3 focus-visible:ring-ring/50"
>
<ArrowDown className="size-3.5 text-muted-foreground" />
- <NumberTicker value={count} />
+ {knownCount ? <NumberTicker value={count} /> : <span>Jump to present</span>}
</button>
)
}
diff --git a/src/web/src/components/community/messages/message-list-controller.dom.test.ts b/src/web/src/components/community/messages/message-list-controller.dom.test.ts
index 9126ae051..8c2e5d193 100644
--- a/src/web/src/components/community/messages/message-list-controller.dom.test.ts
+++ b/src/web/src/components/community/messages/message-list-controller.dom.test.ts
@@ -347,6 +347,12 @@ describe("useMessageListController", () => {
expect(latest.initialPosition).toMatchObject({ phase: "revealed", showSkeleton: false })
})
+ it("keeps an incomplete jump-to-present count unknown instead of using visible rows", () => {
+ act(() => { rtlRender(React.createElement(Probe, { value: props({ hasMoreNewer: true, unreadCount: undefined }) })) })
+ expect(latest.pillMode).toBe("jump")
+ expect(latest.pillCount).toBeUndefined()
+ })
+
it("passes every pagination/anchor input through and gives jump mode server-count precedence", () => {
const loadOlder = vi.fn()
const loadNewer = vi.fn()
diff --git a/src/web/src/components/community/messages/message-list-controller.ts b/src/web/src/components/community/messages/message-list-controller.ts
index 3d2f6988f..f06233632 100644
--- a/src/web/src/components/community/messages/message-list-controller.ts
+++ b/src/web/src/components/community/messages/message-list-controller.ts
@@ -219,7 +219,7 @@ export function useMessageListController({
}, [jumped, jumpRevision, scrollRef, setJumped])
const jumpMode = !!hasMoreNewer
- const pillCount = jumpMode ? ((unreadCount ?? belowCount) || 0) : belowCount
+ const pillCount = jumpMode ? unreadCount : belowCount
const jumpToPresent = useCallback(() => {
requestPresentPosition(onJumpToPresent?.())
}, [onJumpToPresent, requestPresentPosition])
diff --git a/src/web/src/components/community/shell/community-list-errors.dom.test.tsx b/src/web/src/components/community/shell/community-list-errors.dom.test.tsx
index ce563dc16..7f83edaf9 100644
--- a/src/web/src/components/community/shell/community-list-errors.dom.test.tsx
+++ b/src/web/src/components/community/shell/community-list-errors.dom.test.tsx
@@ -9,7 +9,6 @@ import { normalizeCommunityHref } from "@/lib/community/community-route"
import { communityKeys } from "@/lib/query-keys"
import { friendsQueryFn } from "@/hooks/community/use-friends"
import { dmsProjectedQueryFn } from "@/hooks/community/use-dms"
-import { getActiveAccountUnreadProjection } from "@/hooks/community/account-unread-projection"
import FriendsRoute from "../social/friends-route"
import { DmSidebarSlot } from "./dm-sidebar-slot"
@@ -84,7 +83,7 @@ it.each([
const owner = await createCommunityQueryOwner()
load.mockImplementation(async (path: string) => response(path, populated))
const queryKey = key(kind)
- await owner.client.query({ queryKey, queryFn: kind === "friends" ? friendsQueryFn : dmsProjectedQueryFn(getActiveAccountUnreadProjection(owner.client), owner.client) })
+ await owner.client.query({ queryKey, queryFn: kind === "friends" ? friendsQueryFn : dmsProjectedQueryFn(owner.client) })
let reject!: (error: Error) => void
const held = new Promise<never>((_, fail) => { reject = fail })
load.mockImplementation((path: string) => path === primaryPath(kind) ? held : Promise.resolve(response(path, populated)))
diff --git a/src/web/src/components/community/shell/server-landing-route.intent.dom.test.tsx b/src/web/src/components/community/shell/server-landing-route.intent.dom.test.tsx
index 61dc2c23a..a2d494af1 100644
--- a/src/web/src/components/community/shell/server-landing-route.intent.dom.test.tsx
+++ b/src/web/src/components/community/shell/server-landing-route.intent.dom.test.tsx
@@ -10,7 +10,6 @@ import { normalizeCommunityHref } from "@/lib/community/community-route"
import { communityKeys } from "@/lib/query-keys"
import { captureCommunityLiveSnapshotToken, publishCommunityLiveSnapshot } from "@/lib/community-db/sync"
import { serversProjectedQueryFn, useServer } from "@/hooks/community/use-servers"
-import { getActiveAccountUnreadProjection } from "@/hooks/community/account-unread-projection"
import { beginOwnerServerDelete, commitOwnerServerDelete, createOwnerServerDeleteRouteToken, observeOwnerServerDeleteRouteCommit } from "@/lib/community/eject-server"
import { flushOwnerServerDeleteRouteCommit } from "@/hooks/community/community-ws/scope-eviction"
import { useCommunityNavigationController } from "./use-community-navigation-controller"
@@ -33,7 +32,7 @@ async function setup(method: "push" | "pushImmediate", { cold = false, empty = f
const server = { id: "target", name: "Target", discriminator: "0001", description: "", icon: null, ownerId: "viewer" }
mocks.breakpoint = mobile ? "mobile" : "desktop"
mocks.load.mockResolvedValueOnce({ servers: [{ ...server, role: "owner", memberId: "membership" }] })
- await client.query({ queryKey: communityKeys.servers(), queryFn: serversProjectedQueryFn(getActiveAccountUnreadProjection(client), client) })
+ await client.query({ queryKey: communityKeys.servers(), queryFn: serversProjectedQueryFn(client) })
const channels = empty ? [] : [{ id: "channel", name: "Channel", active: false, unread: false, muted: false, type: "text" as const }]
if (!cold) {
publishCommunityLiveSnapshot(client, {
diff --git a/src/web/src/components/community/shell/server-sidebar-slot.identity.dom.test.tsx b/src/web/src/components/community/shell/server-sidebar-slot.identity.dom.test.tsx
index e549ea263..c9df27c26 100644
--- a/src/web/src/components/community/shell/server-sidebar-slot.identity.dom.test.tsx
+++ b/src/web/src/components/community/shell/server-sidebar-slot.identity.dom.test.tsx
@@ -9,10 +9,9 @@ import { CommunityRouteContext } from "@/contexts/community/route-frame"
import { normalizeCommunityHref, type CommunityCommittedFrame } from "@/lib/community/community-route"
import { communityKeys } from "@/lib/query-keys"
import { tid } from "@/lib/community/testids"
-import { captureCommunityLiveSnapshotToken, publishCommunityLiveSnapshot } from "@/lib/community-db/sync"
+import { captureCommunityLiveSnapshotToken, publishCommunityLiveSnapshot, publishAccountAttentionSnapshot, clearAttentionScopeOptimistically, restoreAttentionScopeOptimisticSnapshot } from "@/lib/community-db/sync"
import { createOwnerServerDeleteRouteToken } from "@/lib/community/eject-server"
import { serversProjectedQueryFn } from "@/hooks/community/use-servers"
-import { getActiveAccountUnreadProjection } from "@/hooks/community/account-unread-projection"
import { useCommunityRuntime } from "@/stores/community/runtime"
import { ServerSidebarSlot } from "./server-sidebar-slot"
import { useCommunityNavigationController } from "./use-community-navigation-controller"
@@ -32,9 +31,9 @@ it.each([false, true])("keeps real same-server list, row and category nodes thro
const server = { id: "target", name: "Target server", discriminator: "0001", description: "", icon: null, ownerId: "viewer" }
const proof = { kind: "structural" as const, token: captureCommunityLiveSnapshotToken(client), signal: undefined }
mocks.load.mockResolvedValueOnce({ servers: [{ ...server, role: "owner", memberId: "membership" }] })
- await client.query({ queryKey: communityKeys.servers(), queryFn: serversProjectedQueryFn(getActiveAccountUnreadProjection(client), client) })
+ await client.query({ queryKey: communityKeys.servers(), queryFn: serversProjectedQueryFn(client) })
mocks.load.mockClear()
- publishCommunityLiveSnapshot(client, { snapshot: { kind: "server-detail", data: { ...server, categories: [{ id: "category", name: grouped ? "Group" : "", private: 0, channels: [{ id: "channel", name: "Target channel", active: false, unread: false, muted: false, type: "text" }] }] } }, proof })
+ publishCommunityLiveSnapshot(client, { snapshot: { kind: "server-detail", data: { ...server, categories: [{ id: "category", name: grouped ? "Group" : "", private: 0, channels: [{ id: "channel", name: "Target channel", active: false, unread: true, muted: false, type: "text" }] }] } }, proof })
client.setQueryData(communityKeys.server(server.id), server.id)
client.setQueryData(communityKeys.forumSidebarThreads(server.id), { threads: [], verifiedEpoch: 0, serverNow: new Date().toISOString(), serverClockOffsetMs: 0 })
const token = createOwnerServerDeleteRouteToken(client)
@@ -59,6 +58,27 @@ it.each([false, true])("keeps real same-server list, row and category nodes thro
const view = render(node("/c/channels/target", 0))
const scroll = await view.findByTestId(tid.channelSidebarScroll)
const row = view.getByTestId(tid.channelRow("channel"))
+ const indicator = () => row.querySelector('[data-slot="community-channel-unread-indicator"]')
+ expect(indicator()).toHaveClass("h-0")
+ const attention = (seq: number) => publishAccountAttentionSnapshot(client, {
+ snapshot: { scopes: [{ scopeId: "channel", channelId: "channel", serverId: server.id, parentChannelId: null, ordinaryUnread: true, lastUnreadSeq: seq, attentionCount: 0, lastAttentionSeq: null }], items: [], limit: 100, truncated: false, included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } },
+ proof: { token: captureCommunityLiveSnapshotToken(client), signal: undefined },
+ })
+ await act(async () => { attention(4) })
+ await waitFor(() => expect(indicator()).toHaveClass("h-2.5"))
+ let optimistic!: ReturnType<typeof clearAttentionScopeOptimistically>
+ await act(async () => { optimistic = clearAttentionScopeOptimistically(registry, "channel", 4) })
+ await waitFor(() => expect(indicator()).toHaveClass("h-0"))
+ expect(registry.collections.channels.get("channel")).not.toHaveProperty("unread")
+ await act(async () => { attention(4) })
+ expect(indicator()).toHaveClass("h-0")
+ await act(async () => { attention(5) })
+ await waitFor(() => expect(indicator()).toHaveClass("h-2.5"))
+ await act(async () => {
+ restoreAttentionScopeOptimisticSnapshot(registry, optimistic)
+ publishAccountAttentionSnapshot(client, { snapshot: { scopes: [], items: [], limit: 100, truncated: false, included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } }, proof: { token: captureCommunityLiveSnapshotToken(client), signal: undefined } })
+ })
+ await waitFor(() => expect(indicator()).toHaveClass("h-0"))
const title = view.getByRole("button", { name: "Target server" })
const invite = view.getByRole("button", { name: "Invite to server" })
expect(row).toHaveAttribute("aria-roledescription", "draggable")
diff --git a/src/web/src/components/community/shell/server-sidebar-slot.target.dom.test.tsx b/src/web/src/components/community/shell/server-sidebar-slot.target.dom.test.tsx
index d8c2db920..19c0fb99d 100644
--- a/src/web/src/components/community/shell/server-sidebar-slot.target.dom.test.tsx
+++ b/src/web/src/components/community/shell/server-sidebar-slot.target.dom.test.tsx
@@ -10,7 +10,6 @@ import { communityKeys } from "@/lib/query-keys"
import { captureCommunityLiveSnapshotToken, publishCommunityLiveSnapshot } from "@/lib/community-db/sync"
import { createOwnerServerDeleteRouteToken } from "@/lib/community/eject-server"
import { serversProjectedQueryFn } from "@/hooks/community/use-servers"
-import { getActiveAccountUnreadProjection } from "@/hooks/community/account-unread-projection"
import { ServerSidebarSlot } from "./server-sidebar-slot"
const mocks = vi.hoisted(() => ({ pathname: "/c/channels/source/channel", search: "settings=1", breakpoint: "desktop", replace: vi.fn(), members: vi.fn(), presence: vi.fn(), props: vi.fn(), load: vi.fn() }))
@@ -130,7 +129,7 @@ it.each([
view.rerender(node())
const qualify = async () => {
mocks.load.mockResolvedValueOnce({ servers: [{ ...server, role, memberId: "membership" }] })
- await act(async () => { await client.query({ queryKey: communityKeys.servers(), queryFn: serversProjectedQueryFn(getActiveAccountUnreadProjection(client), client), staleTime: 0 }) })
+ await act(async () => { await client.query({ queryKey: communityKeys.servers(), queryFn: serversProjectedQueryFn(client), staleTime: 0 }) })
}
if (order === "owner-first") {
await qualify()
@@ -146,7 +145,7 @@ it.each([
if (role === "member") {
expect(view.queryByText("Server settings")).toBeNull()
mocks.load.mockResolvedValueOnce({ servers: [{ ...server, role: "owner", memberId: "membership" }] })
- await act(async () => { await client.query({ queryKey: communityKeys.servers(), queryFn: serversProjectedQueryFn(getActiveAccountUnreadProjection(client), client), staleTime: 0 }) })
+ await act(async () => { await client.query({ queryKey: communityKeys.servers(), queryFn: serversProjectedQueryFn(client), staleTime: 0 }) })
await waitFor(() => expect(mocks.props).toHaveBeenLastCalledWith(expect.objectContaining({ onOpenSettings: expect.any(Function) })))
expect(view.queryByText("Server settings")).toBeNull()
return
diff --git a/src/web/src/components/community/shell/server-sidebar-slot.tsx b/src/web/src/components/community/shell/server-sidebar-slot.tsx
index 3e36e015b..092d9252f 100644
--- a/src/web/src/components/community/shell/server-sidebar-slot.tsx
+++ b/src/web/src/components/community/shell/server-sidebar-slot.tsx
@@ -366,15 +366,7 @@ function ServerSidebar({ serverId, href, routeCommitted }: { serverId: string; h
routeCommitted,
])
- const displayCategories = forumSidebar.sidebar.server?.categories
- const categories = useMemo(() => (displayCategories ?? []).map((category) => ({
- ...category,
- channels: category.channels.map((channel) =>
- forumSidebar.parentUnread[channel.id] === undefined
- ? channel
- : { ...channel, unread: forumSidebar.parentUnread[channel.id] },
- ),
- })), [forumSidebar.parentUnread, displayCategories])
+ const categories = useMemo(() => forumSidebar.sidebar.server?.categories ?? [], [forumSidebar.sidebar.server?.categories])
const sidebarDataReady = Boolean(forumSidebar.sidebar.server)
const channelTreeScopeKey = `server:${serverId}`
diff --git a/src/web/src/hooks/community/account-unread-projection.test.ts b/src/web/src/hooks/community/account-unread-projection.test.ts
deleted file mode 100644
index f5740757d..000000000
--- a/src/web/src/hooks/community/account-unread-projection.test.ts
+++ /dev/null
@@ -1,1585 +0,0 @@
-import { QueryClient } from "@tanstack/react-query"
-import { describe, expect, it, vi } from "vitest"
-import {
- acceptAccountUnreadPrimarySnapshot,
- AccountUnreadProjection,
- disposeAccountUnreadProjection,
- getActiveAccountUnreadProjection,
- getAccountUnreadProjection,
- MAX_EXACT_ARRIVALS,
- MAX_EXACT_ARRIVALS_PER_CHANNEL,
- MAX_STICKY_SCOPES,
-} from "./account-unread-projection"
-
-describe("AccountUnreadProjection", () => {
- it("treats unknown access as allowed and only denies explicit retirement", () => {
- const projection = new AccountUnreadProjection("u1")
-
- expect(projection.allowsAccess({ channelId: "unknown", serverId: "server" })).toBe(true)
- projection.retireAccessScope({ kind: "server", serverId: "server" })
- expect(projection.allowsAccess({ channelId: "unknown", serverId: "server" })).toBe(false)
- projection.dispose()
- expect(projection.allowsAccess({ channelId: "other" })).toBe(false)
- })
-
- it("enumerates distinct pending conversations using the same read fences as the badge", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.recordArrival({ channelId: "dm", seq: 1 })
- projection.recordArrival({ channelId: "dm", seq: 2 })
- projection.recordArrival({ channelId: "other", seq: 1 })
- expect(projection.pendingChannelIds("inbox-unreads", "dms")).toEqual(["dm", "other"])
- projection.recordRead("dm", 2)
- expect(projection.pendingChannelIds("inbox-unreads", "dms")).toEqual(["other"])
- projection.recordRead("other", 1)
- expect(projection.pendingChannelIds("inbox-unreads", "dms")).toEqual([])
- expect(projection.hasPending("inbox-unreads", "dms")).toBe(false)
- })
-
- it("is a per-query-client and account singleton", () => {
- const client = new QueryClient()
- expect(getAccountUnreadProjection(client, "u1"))
- .toBe(getAccountUnreadProjection(client, "u1"))
- expect(getAccountUnreadProjection(client, "u1"))
- .not.toBe(getAccountUnreadProjection(client, "u2"))
- })
-
- it("publishes synchronous changes and stops after unsubscribe", () => {
- const projection = new AccountUnreadProjection("u1")
- const listener = vi.fn()
- const unsubscribe = projection.subscribe(listener)
-
- projection.recordArrival({ channelId: "dm", seq: 1 })
- expect(listener).toHaveBeenCalledOnce()
- expect(projection.getSnapshot()).toMatchObject({ ordinal: 1 })
-
- unsubscribe()
- projection.recordArrival({ channelId: "dm", seq: 2 })
- expect(listener).toHaveBeenCalledOnce()
- expect(projection.projectUnread("dms", "dm", false)).toBe(true)
- })
-
- it("ignores malformed arrivals and read cursors", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.recordArrival({ channelId: "", seq: 1 })
- projection.recordRead("c1", 0)
- projection.recordOptimisticRead("c1", Number.NaN, 1)
- expect(projection.getSnapshot()).toMatchObject({ ordinal: 0 })
- expect(projection.hasPending()).toBe(false)
- })
-
- it("records each rolling-deploy legacy snapshot once", () => {
- const projection = new AccountUnreadProjection("u1")
- const snapshot = {}
- projection.recordLegacySnapshot(snapshot, [{
- family: "servers",
- channelId: "legacy",
- serverId: "s1",
- }])
- const version = projection.getSnapshot()
- projection.recordLegacySnapshot(snapshot, [{
- family: "servers",
- channelId: "legacy",
- serverId: "s1",
- }])
- expect(projection.getSnapshot()).toBe(version)
- expect(projection.projectServerUnread("s1", [], false)).toBe(true)
- })
-
- it("rejects unordered legacy rows until fresh access authority clears the fence", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.retireAccessScope({ kind: "server", serverId: "s1" })
- projection.grantAccessScope({ kind: "server", serverId: "s1" })
-
- projection.recordLegacySnapshot({}, [{
- family: "inbox-unreads",
- channelId: "legacy",
- serverId: "s1",
- }])
- const authority = projection.beginSnapshot("servers", "channels")
- projection.absorbSnapshot(authority, [], {
- confirmedAccessScopes: [{ kind: "server", serverId: "s1" }],
- })
-
- expect(projection.projectUnread("inbox-unreads", "legacy", false)).toBe(false)
- expect(projection.inspectForTests().stickyCount).toBe(0)
-
- projection.recordLegacySnapshot({}, [{
- family: "inbox-unreads",
- channelId: "legacy",
- serverId: "s1",
- }])
- expect(projection.projectUnread("inbox-unreads", "legacy", false)).toBe(true)
- })
-
- it("merges duplicate exact evidence and ignores older read cursors", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.recordArrival({ channelId: "c1", serverId: "s1", messageId: "m1", seq: 2 })
- projection.recordArrival({
- channelId: "c1",
- railChannelId: "forum",
- messageId: "m1",
- attentionId: "mention-1",
- seq: 2,
- isMention: true,
- })
- projection.recordRead("c1", 1)
- projection.recordRead("c1", 1)
-
- expect(projection.projectUnread("servers", "c1", false)).toBe(true)
- expect(projection.projectUnread("dms", "c1", false)).toBe(true)
- expect(projection.projectUnread("inbox-mentions", "c1", false)).toBe(true)
- })
-
- it("does not retain an exact replay already covered by the primary cursor", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.acceptPrimarySnapshot({
- revision: 1,
- readStates: [{ channelId: "c1", lastReadSeq: 4 }],
- })
-
- projection.recordArrival({
- channelId: "c1",
- serverId: "s1",
- messageId: "m4",
- seq: 4,
- isMention: true,
- })
-
- expect(projection.hasPending()).toBe(false)
- expect(projection.projectUnread("servers", "c1", false)).toBe(false)
- expect(projection.projectUnread("inbox-mentions", "c1", false)).toBe(false)
- })
-
- it("keeps positive family evidence canonical until a later full snapshot omits it", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.setNotificationPolicy({})
- projection.recordArrival({ channelId: "c1", serverId: "s1", messageId: "m2", seq: 2 })
- expect(projection.projectUnread("servers", "c1", false)).toBe(true)
- const positive = projection.beginSnapshot("servers")
- projection.absorbSnapshot(positive, [{ channelId: "c1", serverId: "s1", lastUnreadSeq: 2 }])
- expect(projection.projectUnread("servers", "c1", false)).toBe(true)
- const empty = projection.beginSnapshot("servers")
- projection.absorbSnapshot(empty, [])
- expect(projection.projectUnread("servers", "c1", false)).toBe(false)
- })
-
- it("retires sticky unknowns only from a full current snapshot", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.setNotificationPolicy({})
- projection.recordArrival({ channelId: "c1", serverId: "s1" })
- const truncated = projection.beginSnapshot("inbox-unreads", "channels")
- projection.absorbSnapshot(truncated, [], { truncated: true })
- expect(projection.projectUnread("inbox-unreads", "c1", false)).toBe(true)
- const full = projection.beginSnapshot("inbox-unreads", "channels")
- projection.absorbSnapshot(full, [])
- expect(projection.projectUnread("inbox-unreads", "c1", false)).toBe(false)
- })
-
- it("retires a covered sticky family after newer full positive evidence", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.setNotificationPolicy({})
- projection.recordArrival({ channelId: "c1", serverId: "s1" })
- const token = projection.beginSnapshot("inbox-unreads", "channels")
- projection.absorbSnapshot(token, [{
- channelId: "c1",
- serverId: "s1",
- lastUnreadSeq: 7,
- }])
-
- expect(projection.inspectForTests()).toMatchObject({
- sourceCount: 2,
- exactCount: 1,
- stickyCount: 1,
- })
- expect(projection.hasPending("inbox-unreads", "channels")).toBe(true)
- expect(projection.projectUnread(
- "inbox-unreads",
- "c1",
- false,
- undefined,
- "channels",
- { channelId: "c1", throughSeq: 7 },
- )).toBe(false)
- })
-
- it("lets a visible read cover exact seq but never an unsequenced sticky bump", () => {
- const exact = new AccountUnreadProjection("u1")
- exact.recordArrival({ channelId: "c1", serverId: "s1", seq: 4 })
- exact.recordRead("c1", 4)
- expect(exact.projectUnread("servers", "c1", false)).toBe(false)
-
- const sticky = new AccountUnreadProjection("u1")
- sticky.recordArrival({ channelId: "c1", serverId: "s1" })
- sticky.recordRead("c1", 99)
- expect(sticky.projectUnread("servers", "c1", false)).toBe(true)
- })
-
- it("rolls back only the failed optimistic read generation", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 4 })
- projection.recordOptimisticRead("c1", 4, 1)
- expect(projection.projectUnread("servers", "c1", false)).toBe(false)
- projection.settleOptimisticRead(1, false)
- expect(projection.projectUnread("servers", "c1", false)).toBe(true)
- })
-
- it("commits an optimistic read at the greatest confirmed cursor", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 5 })
- projection.recordOptimisticRead("c1", 4, 2)
- projection.settleOptimisticRead(404, true, 5)
- expect(projection.projectUnread("servers", "c1", false)).toBe(true)
-
- projection.settleOptimisticRead(2, true, 5)
- expect(projection.projectUnread("servers", "c1", false)).toBe(false)
- })
-
- it("settles overlapping optimistic generations independently", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 4 })
- projection.recordOptimisticRead("c1", 4, 1)
- projection.recordOptimisticRead("c1", 5, 2)
- projection.settleOptimisticRead(2, false)
- expect(projection.projectUnread("servers", "c1", false)).toBe(false)
- projection.settleOptimisticRead(1, false)
- expect(projection.projectUnread("servers", "c1", false)).toBe(true)
-
- projection.recordOptimisticRead("c1", 4, 3)
- projection.settleOptimisticRead(3, true, 4)
- projection.recordOptimisticRead("c1", 5, 4)
- projection.settleOptimisticRead(4, false)
- expect(projection.projectUnread("servers", "c1", false)).toBe(false)
- })
-
- it("lets an accepted primary cursor settle matching optimistic generations", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 4 })
- projection.recordOptimisticRead("c1", 4, 1)
- projection.acceptPrimarySnapshot({
- revision: 1,
- readStates: [{ channelId: "c1", lastReadSeq: 4 }],
- })
- projection.settleOptimisticRead(1, false)
- expect(projection.projectUnread("servers", "c1", false)).toBe(false)
- })
-
- it("keeps post-mark-all arrivals while hiding only the captured prefix", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })
- const token = projection.beginMarkAll("channels")
- expect(projection.projectUnread("servers", "c1", true, 1)).toBe(false)
- projection.recordArrival({ channelId: "c2", serverId: "s1", seq: 2 })
- expect(projection.projectUnread("servers", "c2", false)).toBe(true)
- projection.rollbackMarkAll(token)
- expect(projection.projectUnread("servers", "c1", true, 1)).toBe(true)
- })
-
- it("keeps channel and DM mark-all domains independent inside Inbox", () => {
- const projection = new AccountUnreadProjection("u1")
- const channelToken = projection.beginMarkAll("channels")
- expect(projection.projectUnread("inbox-unreads", "channel", true, 2)).toBe(false)
- expect(projection.projectUnread("inbox-unreads", "dm", true, 2, "dms")).toBe(true)
- projection.rollbackMarkAll(channelToken)
-
- const dmToken = projection.beginMarkAll("dms")
- expect(projection.projectUnread("inbox-unreads", "channel", true, 2)).toBe(true)
- expect(projection.projectUnread("inbox-unreads", "dm", true, 2, "dms")).toBe(false)
- projection.rollbackMarkAll(dmToken)
- })
-
- it("retires only the accepted mark-all domain prefix and preserves later arrivals", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.recordArrival({
- channelId: "channel-before",
- serverId: "s1",
- isMention: true,
- })
- const channelToken = projection.beginMarkAll("channels")
- const mentionToken = projection.beginMarkAll("mentions")
- projection.recordArrival({ channelId: "channel-after", serverId: "s1" })
- projection.commitMarkAll(channelToken, 4)
- projection.commitMarkAll(mentionToken, 6)
-
- projection.acceptPrimarySnapshot({ revision: 4, readStates: [] })
- expect(projection.projectUnread("servers", "channel-before", false)).toBe(false)
- expect(projection.projectUnread("servers", "channel-after", false)).toBe(true)
- expect(projection.projectUnread("inbox-mentions", "channel-before", false)).toBe(false)
-
- projection.acceptPrimarySnapshot({ revision: 6, readStates: [] })
- expect(projection.projectUnread("inbox-mentions", "channel-before", false)).toBe(false)
- })
-
- it("retires exact family bits and overflow sentinels at an accepted fence", () => {
- const exact = new AccountUnreadProjection("u1")
- exact.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })
- const channel = exact.beginMarkAll("channels")
- exact.recordArrival({ channelId: "c2", serverId: "s1", seq: 2 })
- exact.commitMarkAll(channel, 2)
- exact.acceptPrimarySnapshot({ revision: 2, readStates: [] })
- expect(exact.projectUnread("servers", "c1", false)).toBe(false)
- expect(exact.projectUnread("servers", "c2", false)).toBe(true)
-
- const overflow = new AccountUnreadProjection("u1")
- for (let index = 0; index < MAX_STICKY_SCOPES; index += 1) {
- overflow.recordArrival({ channelId: `c${index}`, serverId: `s${index}` })
- }
- overflow.recordArrival({ channelId: "overflow", serverId: "s-overflow" })
- const token = overflow.beginMarkAll("channels")
- overflow.commitMarkAll(token, 3)
- overflow.acceptPrimarySnapshot({ revision: 3, readStates: [] })
- expect(overflow.projectUnread("servers", "unrelated", false)).toBe(false)
- })
-
- it("applies primary snapshots only to the active account", () => {
- const client = new QueryClient()
- const first = getAccountUnreadProjection(client, "u1")
- first.recordArrival({ channelId: "c1", serverId: "s1", seq: 2 })
- const second = getAccountUnreadProjection(client, "u2")
- second.recordArrival({ channelId: "c1", serverId: "s1", seq: 2 })
-
- acceptAccountUnreadPrimarySnapshot(client, {
- revision: 1,
- readStates: [{ channelId: "c1", lastReadSeq: 2 }],
- })
-
- expect(first.projectUnread("servers", "c1", false)).toBe(true)
- expect(second.projectUnread("servers", "c1", false)).toBe(false)
- })
-
- it("does not create or update a projection when no account is active", () => {
- const client = new QueryClient()
- acceptAccountUnreadPrimarySnapshot(client, {
- revision: 1,
- readStates: [{ channelId: "c1", lastReadSeq: 2 }],
- })
- const anonymous = getActiveAccountUnreadProjection(client)
- expect(anonymous.ownerUserId).toBe("__anonymous__")
- expect(anonymous.getSnapshot()).toMatchObject({ ordinal: 0 })
- })
-
- it("never derives a numeric server mention increment from isMention", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.recordArrival({
- channelId: "c1",
- serverId: "s1",
- seq: 2,
- isMention: true,
- })
- expect(projection.projectServerMentionCount("s1", [{
- channelId: "c1",
- count: 3,
- lastSeq: 1,
- }])).toBe(3)
- expect(projection.projectMentionCount("inbox-mentions", "c1", 0, 1)).toBe(1)
- })
-
- it("keeps positive mention evidence and retires it on a later full empty", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.setNotificationPolicy({})
- projection.recordMentionArrival({ channelId: "c1", seq: 4, isMention: true })
- const positive = projection.beginSnapshot("inbox-mentions")
- projection.absorbSnapshot(positive, [{
- channelId: "c1",
- lastUnreadSeq: 5,
- lastMentionSeq: 3,
- }])
- expect(projection.projectUnread("inbox-mentions", "c1", false)).toBe(true)
-
- const empty = projection.beginSnapshot("inbox-mentions")
- projection.absorbSnapshot(empty, [])
- expect(projection.projectUnread("inbox-mentions", "c1", false)).toBe(false)
- })
-
- it("retires a single-family sticky mention on authoritative absence", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.setNotificationPolicy({})
- projection.recordMentionArrival({ channelId: "c1", isMention: true })
- const token = projection.beginSnapshot("inbox-mentions")
- projection.absorbSnapshot(token, [])
- expect(projection.hasPending("inbox-mentions", "mentions")).toBe(false)
- })
-
- it("skips arrivals and sticky scopes owned by another family", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.recordArrival({ channelId: "exact", serverId: "s1", seq: 2 })
- projection.recordArrival({ channelId: "sticky", serverId: "s1" })
- projection.absorbFamily("dms", [{ channelId: "exact", lastUnreadSeq: 3 }])
- expect(projection.projectUnread("servers", "exact", false)).toBe(true)
- expect(projection.projectUnread("servers", "sticky", false)).toBe(true)
- })
-
- it("ignores stale family evidence", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 2 })
- projection.absorbFamily("servers", [{ channelId: "c1", lastUnreadSeq: 2 }], {
- stale: true,
- })
- expect(projection.projectUnread("servers", "c1", false)).toBe(true)
- })
-
- it("projects server and channel fallbacks, exact arrivals, and hidden forum children", () => {
- const projection = new AccountUnreadProjection("u1")
- expect(projection.projectServerUnread("s1", [], true)).toBe(false)
- expect(projection.projectServerChannelUnread("s1", "c1", [], true)).toBe(false)
-
- projection.recordArrival({
- channelId: "post",
- railChannelId: "forum",
- serverId: "s1",
- seq: 2,
- })
- expect(projection.projectServerUnread("s1", [], false)).toBe(true)
- expect(projection.projectServerChannelUnread("s1", "forum", [], false)).toBe(true)
- expect(projection.projectForumParentUnread(
- "s1",
- "forum",
- false,
- null,
- new Set(),
- )).toBe(true)
- expect(projection.projectForumParentUnread(
- "s1",
- "forum",
- false,
- null,
- new Set(["post"]),
- )).toBe(false)
- expect(projection.projectForumParentUnread(
- "s1",
- "forum",
- true,
- 3,
- new Set(["post"]),
- )).toBe(true)
- expect(projection.projectServerUnread("other", [], false)).toBe(false)
- })
-
- it("projects sticky server, channel, and hidden-forum unread state", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.recordArrival({
- channelId: "post",
- railChannelId: "forum",
- serverId: "s1",
- })
- expect(projection.projectServerUnread("s1", [], false)).toBe(true)
- expect(projection.projectServerChannelUnread("s1", "forum", [], false)).toBe(true)
- expect(projection.projectForumParentUnread(
- "s1",
- "forum",
- false,
- null,
- new Set(),
- )).toBe(true)
- })
-
- it("projects canonical server sources without aggregate-only fallbacks", () => {
- const projection = new AccountUnreadProjection("u1")
- expect(projection.projectServerUnread("s1", [{
- channelId: "c1",
- lastUnreadSeq: 2,
- }])).toBe(true)
- expect(projection.projectServerChannelUnread("s1", "c1", [{
- channelId: "c1",
- lastUnreadSeq: 2,
- }])).toBe(true)
- expect(projection.projectServerMentionCount("s1", [], 7)).toBe(0)
- expect(projection.projectServerMentionCount("s1", [{
- channelId: "c1",
- count: 3,
- lastSeq: 2,
- }])).toBe(3)
- })
-
- it("excludes only the reserved channel boundary and preserves later arrivals", () => {
- const projection = new AccountUnreadProjection("u1")
- const exclusion = { channelId: "c1", throughSeq: 2 }
- projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 2 })
-
- expect(projection.projectUnread(
- "servers",
- "c1",
- true,
- 2,
- "channels",
- exclusion,
- )).toBe(false)
- expect(projection.projectServerUnread("s1", [{
- channelId: "c1",
- lastUnreadSeq: 2,
- }], false, exclusion)).toBe(false)
- expect(projection.projectServerChannelUnread("s1", "c1", [{
- channelId: "c1",
- lastUnreadSeq: 2,
- }], false, exclusion)).toBe(false)
- expect(projection.hasPending("servers", "channels", exclusion)).toBe(false)
-
- projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 3 })
- expect(projection.projectUnread(
- "servers",
- "c1",
- true,
- 2,
- "channels",
- exclusion,
- )).toBe(true)
- expect(projection.projectServerUnread("s1", [{
- channelId: "c1",
- lastUnreadSeq: 2,
- }], false, exclusion)).toBe(true)
- expect(projection.hasPending("servers", "channels", exclusion)).toBe(true)
- })
-
- it("keeps unrelated aggregate sources visible during an exact reservation", () => {
- const projection = new AccountUnreadProjection("u1")
- const exclusion = { channelId: "post", throughSeq: 4 }
- projection.recordArrival({
- channelId: "post",
- railChannelId: "forum",
- serverId: "s1",
- seq: 4,
- })
- projection.recordArrival({ channelId: "sibling", serverId: "s1", seq: 1 })
-
- expect(projection.projectServerUnread("s1", [], false, exclusion)).toBe(true)
- expect(projection.projectServerChannelUnread(
- "s1",
- "forum",
- [],
- false,
- exclusion,
- )).toBe(false)
- expect(projection.projectForumParentUnread(
- "s1",
- "forum",
- false,
- null,
- new Set(),
- exclusion,
- )).toBe(false)
- })
-
- it("reports pending exact and sticky work by family and domain", () => {
- const exact = new AccountUnreadProjection("u1")
- exact.recordArrival({ channelId: "c1", serverId: "s1", seq: 1, isMention: true })
- expect(exact.hasPending("servers", "channels")).toBe(true)
- expect(exact.hasPending("inbox-mentions", "mentions")).toBe(true)
- expect(exact.hasPending("dms", "dms")).toBe(false)
- expect(exact.hasPending(undefined, "dms")).toBe(false)
-
- const sticky = new AccountUnreadProjection("u1")
- sticky.recordArrival({ channelId: "dm", isMention: true })
- expect(sticky.hasPending("dms")).toBe(true)
- expect(sticky.hasPending(undefined, "mentions")).toBe(true)
- expect(sticky.hasPending(undefined, "channels")).toBe(false)
- expect(sticky.hasPending("servers", "channels")).toBe(false)
- })
-
- it("degrades per-channel exact overflow to a sticky sentinel without losing unread", () => {
- const projection = new AccountUnreadProjection("u1")
- for (let seq = 1; seq <= MAX_EXACT_ARRIVALS_PER_CHANNEL + 1; seq += 1) {
- projection.recordArrival({ channelId: "c1", serverId: "s1", seq })
- }
- projection.recordRead("c1", MAX_EXACT_ARRIVALS_PER_CHANNEL + 1)
- expect(projection.projectUnread("servers", "c1", false)).toBe(true)
- })
-
- it("folds account-wide exact overflow into a sticky scope", () => {
- const projection = new AccountUnreadProjection("u1")
- for (let index = 0; index < MAX_EXACT_ARRIVALS; index += 1) {
- projection.recordArrival({
- channelId: `c${index}`,
- serverId: "s1",
- seq: 1,
- })
- }
- projection.recordArrival({ channelId: "overflow", serverId: "s1", seq: 1 })
- projection.recordRead("overflow", 99)
- expect(projection.projectUnread("servers", "overflow", false)).toBe(true)
- })
-
- it("keeps fixed family overflow conservative and generation-aware", () => {
- const projection = new AccountUnreadProjection("u1")
- for (let index = 0; index < MAX_STICKY_SCOPES; index += 1) {
- projection.recordArrival({ channelId: `c${index}`, serverId: `s${index}` })
- }
- projection.recordArrival({ channelId: "overflow-before", serverId: "s-overflow" })
- expect(projection.projectServerChannelUnread(
- "s-overflow",
- "overflow-before",
- [],
- )).toBe(true)
-
- const token = projection.beginMarkAll("channels")
- expect(projection.projectServerChannelUnread(
- "s-overflow",
- "overflow-before",
- [],
- )).toBe(false)
- projection.recordArrival({ channelId: "overflow-after", serverId: "s-after" })
- expect(projection.projectServerChannelUnread("s-after", "overflow-after", [])).toBe(true)
-
- projection.commitMarkAll(token, 3)
- projection.acceptPrimarySnapshot({ revision: 3, readStates: [] })
- expect(projection.projectServerChannelUnread("s-after", "overflow-after", [])).toBe(true)
- })
-
- it("evicts the oldest scoped sticky source without inventing an unrelated dot", () => {
- const projection = new AccountUnreadProjection("u1")
- const reconcile = vi.fn()
- projection.setReconcileScheduler(reconcile)
- for (let index = 0; index < MAX_STICKY_SCOPES; index += 1) {
- projection.recordArrival({ channelId: `c${index}`, serverId: `s${index}` })
- }
- projection.recordArrival({ channelId: "overflow", serverId: "s-overflow" })
- expect(projection.inspectForTests().stickyCount).toBe(MAX_STICKY_SCOPES)
- expect(projection.projectUnread("servers", "c0", false)).toBe(false)
- expect(projection.projectUnread("servers", "overflow", false)).toBe(true)
- expect(projection.hasPending("servers")).toBe(true)
- expect(projection.hasPending("servers", "channels")).toBe(true)
- expect(projection.projectUnread("servers", "unrelated", false)).toBe(false)
- expect(projection.projectServerUnread("unrelated", [], false)).toBe(false)
- expect(projection.projectForumParentUnread(
- "unrelated",
- "forum",
- false,
- null,
- new Set(),
- )).toBe(false)
- expect(reconcile).toHaveBeenCalledOnce()
- })
-
- it("coalesces reconciliation across repeated sticky overflow", () => {
- const projection = new AccountUnreadProjection("u1")
- const reconcile = vi.fn()
- projection.setReconcileScheduler(reconcile)
- for (let index = 0; index < MAX_STICKY_SCOPES; index += 1) {
- projection.recordArrival({ channelId: `c${index}`, serverId: `s${index}` })
- }
- projection.recordArrival({ channelId: "first", serverId: "s-first" })
- projection.recordArrival({ channelId: "second", serverId: "s-second" })
- expect(reconcile).toHaveBeenCalledOnce()
- })
-
- it("retires a compacted scoped source on a complete empty snapshot", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.setNotificationPolicy({})
- for (let seq = 1; seq <= MAX_EXACT_ARRIVALS_PER_CHANNEL + 1; seq += 1) {
- projection.recordArrival({ channelId: "shared", serverId: "s1", seq })
- }
- const token = projection.beginSnapshot("servers", "channels")
- projection.absorbSnapshot(token, [])
- expect(projection.projectUnread("servers", "shared", false)).toBe(false)
- })
-
- it("ignores superseded mark-all tokens", () => {
- const projection = new AccountUnreadProjection("u1")
- const first = projection.beginMarkAll("channels")
- const second = projection.beginMarkAll("channels")
- projection.commitMarkAll(first, 1)
- projection.rollbackMarkAll(first)
- expect(projection.projectUnread("servers", "c1", true, 1)).toBe(false)
- projection.rollbackMarkAll(second)
- expect(projection.projectUnread("servers", "c1", true, 1)).toBe(true)
- })
-
- it("refreshes a repeated sticky scope past a mark-all fence", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.recordArrival({ channelId: "c1", serverId: "s1" })
- const token = projection.beginMarkAll("channels")
- expect(projection.projectUnread("servers", "c1", false)).toBe(false)
- projection.recordArrival({ channelId: "c1", serverId: "s1" })
- expect(projection.projectUnread("servers", "c1", false)).toBe(true)
- projection.rollbackMarkAll(token)
- })
-
- it("keeps a post-mark-all mention as a new ordinary and attention source", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.recordArrival({ channelId: "c1", serverId: "s1" })
- const token = projection.beginMarkAll("channels")
- projection.recordMentionArrival({ channelId: "c1", isMention: true })
- projection.commitMarkAll(token, 2)
- projection.acceptPrimarySnapshot({ revision: 2, readStates: [] })
-
- expect(projection.projectUnread("servers", "c1", false)).toBe(true)
- expect(projection.projectUnread("inbox-mentions", "c1", false)).toBe(true)
- })
-
- it("stores one canonical source across unread and attention families", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.recordArrival({
- channelId: "c1",
- serverId: "s1",
- messageId: "m1",
- seq: 7,
- isMention: true,
- })
- expect(projection.inspectForTests().sourceCount).toBe(1)
- expect(projection.projectUnread("inbox-unreads", "c1", false)).toBe(true)
- expect(projection.projectUnread("inbox-mentions", "c1", false)).toBe(true)
- })
-
- it("coalesces bundled unread and mention events by channel sequence", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 7 })
- projection.recordMentionArrival({ channelId: "c1", messageId: "m1", seq: 7 })
-
- expect(projection.inspectForTests().sourceCount).toBe(1)
- expect(projection.projectUnread("inbox-unreads", "c1", false)).toBe(true)
- expect(projection.projectUnread("inbox-mentions", "c1", false)).toBe(true)
- })
-
- it("excludes the reserved mention from the server attention badge", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.recordArrival({
- channelId: "c1",
- serverId: "s1",
- messageId: "m1",
- seq: 7,
- isMention: true,
- })
-
- expect(projection.projectServerMentionCount("s1", [{
- channelId: "c1",
- count: 1,
- lastSeq: 7,
- }], 1, { channelId: "c1", throughSeq: 7 })).toBe(0)
- })
-
- it("upgrades a correlated unsequenced mention to the later exact unread source", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.recordMentionArrival({ channelId: "c1", messageId: "m1" })
- projection.recordArrival({
- channelId: "c1",
- serverId: "s1",
- messageId: "m1",
- seq: 7,
- })
-
- expect(projection.inspectForTests()).toMatchObject({
- sourceCount: 1,
- exactCount: 1,
- stickyCount: 0,
- })
- const exclusion = { channelId: "c1", throughSeq: 7 }
- expect(projection.projectUnread(
- "inbox-unreads",
- "c1",
- false,
- undefined,
- "channels",
- exclusion,
- )).toBe(false)
- expect(projection.projectUnread(
- "inbox-mentions",
- "c1",
- false,
- undefined,
- "mentions",
- exclusion,
- )).toBe(false)
- })
-
- it("enriches a bump-first sticky before a truncated exact mention snapshot", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.recordArrival({
- channelId: "post-1",
- serverId: "s1",
- railChannelId: "forum-1",
- isMention: true,
- })
- projection.recordMentionArrival({ channelId: "post-1", messageId: "m1" })
- const token = projection.beginSnapshot("inbox-mentions", "mentions")
- projection.absorbSnapshot(token, [{
- channelId: "post-1",
- serverId: "s1",
- railChannelId: "forum-1",
- messageId: "m1",
- attentionId: "attention-1",
- lastUnreadSeq: 7,
- lastMentionSeq: 7,
- }], { truncated: true })
-
- expect(projection.inspectForTests()).toMatchObject({
- sourceCount: 1,
- exactCount: 1,
- stickyCount: 0,
- })
- })
-
- it("keeps m1 to m2 to m1 sticky identities aggregated", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.recordMentionArrival({ channelId: "c1", messageId: "m1" })
- projection.recordMentionArrival({ channelId: "c1", messageId: "m2" })
- projection.recordMentionArrival({ channelId: "c1", messageId: "m1" })
- projection.recordArrival({ channelId: "c1", messageId: "m1", seq: 7 })
-
- expect(projection.inspectForTests()).toMatchObject({
- sourceCount: 2,
- exactCount: 1,
- stickyCount: 1,
- })
- })
-
- it("does not classify an unscoped mention frame as a DM", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.recordMentionArrival({ channelId: "unknown", seq: 7 })
-
- expect(projection.projectUnread("inbox-unreads", "unknown", false)).toBe(true)
- expect(projection.projectUnread("inbox-mentions", "unknown", false)).toBe(true)
- expect(projection.projectUnread("dms", "unknown", false)).toBe(false)
- })
-
- it("keeps live and snapshot mentions in a previously known DM family", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.setNotificationPolicy({})
- projection.recordArrival({ channelId: "dm", seq: 1 })
- projection.recordMentionArrival({ channelId: "dm", seq: 2 })
- projection.recordRead("dm", 1)
-
- expect(projection.projectUnread("dms", "dm", false)).toBe(true)
- expect(projection.projectUnread("inbox-mentions", "dm", false)).toBe(true)
-
- const token = projection.beginSnapshot("inbox-mentions", "mentions")
- projection.absorbSnapshot(token, [{
- channelId: "dm",
- lastUnreadSeq: 3,
- lastMentionSeq: 3,
- }], { truncated: true })
- projection.recordRead("dm", 2)
-
- expect(projection.projectUnread("dms", "dm", false)).toBe(true)
- expect(projection.projectUnread("inbox-mentions", "dm", false)).toBe(true)
- })
-
- it("projects an exact attention row without borrowing a newer channel source", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.recordMentionArrival({ channelId: "c1", seq: 4, isMention: true })
- projection.recordMentionArrival({ channelId: "c1", seq: 5, isMention: true })
- const exclusion = { channelId: "c1", throughSeq: 4 }
-
- expect(projection.projectUnread(
- "inbox-mentions",
- "c1",
- true,
- 4,
- "mentions",
- exclusion,
- true,
- )).toBe(false)
- expect(projection.projectUnread(
- "inbox-mentions",
- "c1",
- true,
- 5,
- "mentions",
- exclusion,
- true,
- )).toBe(true)
- })
-
- it("uses full absence as negative evidence but keeps post-request arrivals", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.setNotificationPolicy({})
- projection.recordArrival({ channelId: "before", serverId: "s1", seq: 1 })
- const token = projection.beginSnapshot("servers", "channels")
- projection.recordArrival({ channelId: "after", serverId: "s1", seq: 2 })
- projection.absorbSnapshot(token, [])
- expect(projection.projectUnread("servers", "before", false)).toBe(false)
- expect(projection.projectUnread("servers", "after", false)).toBe(true)
- })
-
- it("does not let a pre-mark-all snapshot refresh an old source past the fence", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.setNotificationPolicy({})
- projection.recordArrival({ channelId: "before", serverId: "s1", seq: 1 })
- const snapshot = projection.beginSnapshot("servers")
- const markAll = projection.beginMarkAll("channels")
-
- projection.absorbSnapshot(snapshot, [{
- channelId: "before",
- serverId: "s1",
- lastUnreadSeq: 1,
- }])
-
- expect(projection.projectUnread("servers", "before", false)).toBe(false)
- projection.rollbackMarkAll(markAll)
- expect(projection.projectUnread("servers", "before", false)).toBe(true)
- })
-
- it("keeps a source confirmed by a newer snapshot when an older empty arrives last", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.setNotificationPolicy({})
- projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })
- const older = projection.beginSnapshot("servers", "channels")
- const newer = projection.beginSnapshot("servers", "channels")
-
- projection.absorbSnapshot(newer, [{
- channelId: "c1",
- serverId: "s1",
- lastUnreadSeq: 1,
- }])
- projection.absorbSnapshot(older, [])
-
- expect(projection.projectUnread("servers", "c1", false)).toBe(true)
- })
-
- it("treats stale and truncated snapshots as positive-only", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })
- const stale = projection.beginSnapshot("servers", "channels")
- projection.absorbSnapshot(stale, [], { stale: true })
- const truncated = projection.beginSnapshot("servers", "channels")
- projection.absorbSnapshot(truncated, [], { truncated: true })
- expect(projection.projectUnread("servers", "c1", false)).toBe(true)
-
- const positive = projection.beginSnapshot("servers", "channels")
- projection.absorbSnapshot(positive, [{
- channelId: "c2",
- serverId: "s1",
- lastUnreadSeq: 2,
- }], { stale: true })
- expect(projection.projectUnread("servers", "c2", false)).toBe(true)
- })
-
- it("merges a positive family snapshot with its default domain", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.setNotificationPolicy({})
- const beginSnapshot = vi.spyOn(projection, "beginSnapshot")
-
- projection.mergeSources("dms", [{ channelId: "dm", lastUnreadSeq: 2 }])
-
- expect(beginSnapshot).toHaveBeenCalledWith("dms", "dms")
- expect(projection.projectUnread("dms", "dm", false)).toBe(true)
- })
-
- it("treats snapshots started before policy hydration as positive-only", () => {
- const projection = new AccountUnreadProjection("u1")
- const reconcile = vi.fn()
- projection.setReconcileScheduler(reconcile)
- projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })
- const token = projection.beginSnapshot("servers", "channels")
- projection.absorbSnapshot(token, [])
- projection.setNotificationPolicy({ server: { s1: "all" } })
- expect(projection.projectUnread("servers", "c1", false)).toBe(true)
- expect(reconcile).toHaveBeenCalledOnce()
- })
-
- it("reconciles pre-policy snapshots that would retire exact or sticky attention", () => {
- const exact = new AccountUnreadProjection("u1")
- const exactReconcile = vi.fn()
- exact.setReconcileScheduler(exactReconcile)
- exact.recordArrival({ channelId: "channel", serverId: "s1", seq: 1, isMention: true })
- const exactToken = exact.beginSnapshot("servers", "channels")
- exact.absorbSnapshot(exactToken, [{
- channelId: "channel",
- serverId: "s1",
- lastUnreadSeq: 1,
- }])
- exact.setNotificationPolicy({})
-
- expect(exact.projectUnread("servers", "channel", false)).toBe(true)
- expect(exactReconcile).toHaveBeenCalledOnce()
-
- const sticky = new AccountUnreadProjection("u1")
- const stickyReconcile = vi.fn()
- sticky.setReconcileScheduler(stickyReconcile)
- sticky.recordArrival({ channelId: "dm", isMention: true })
- const stickyToken = sticky.beginSnapshot("dms", "dms")
- sticky.absorbSnapshot(stickyToken, [{ channelId: "dm", lastUnreadSeq: 1 }])
- sticky.setNotificationPolicy({})
-
- expect(sticky.projectUnread("dms", "dm", false)).toBe(true)
- expect(stickyReconcile).toHaveBeenCalledOnce()
- })
-
- it("does not refetch a pre-policy snapshot that had no negative work", () => {
- const projection = new AccountUnreadProjection("u1")
- const reconcile = vi.fn()
- projection.setReconcileScheduler(reconcile)
- const token = projection.beginSnapshot("dms", "dms")
- projection.absorbSnapshot(token, [])
-
- projection.setNotificationPolicy({})
-
- expect(reconcile).not.toHaveBeenCalled()
- })
-
- it("makes an old-policy full empty positive-only and coalesces reconciliation", () => {
- const projection = new AccountUnreadProjection("u1")
- const reconcile = vi.fn()
- projection.setReconcileScheduler(reconcile)
- projection.setNotificationPolicy({ server: { s1: "all" } })
- reconcile.mockClear()
- projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })
- const token = projection.beginSnapshot("servers", "channels")
- projection.setNotificationPolicy({ server: { s1: "nothing" } })
- projection.absorbSnapshot(token, [])
- projection.absorbSnapshot(token, [])
- expect(reconcile).toHaveBeenCalledOnce()
- projection.setNotificationPolicy({ server: { s1: "all" } })
- expect(projection.projectUnread("servers", "c1", false)).toBe(true)
- })
-
- it("runs a reconciliation requested before its scheduler attaches", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.setNotificationPolicy({})
- const token = projection.beginSnapshot("servers")
- projection.setNotificationPolicy({ server: { s1: "nothing" } })
- projection.absorbSnapshot(token, [])
-
- const reconcile = vi.fn()
- projection.setReconcileScheduler(reconcile)
- expect(reconcile).toHaveBeenCalledOnce()
- })
-
- it("absorbs each issued snapshot token at most once", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.setNotificationPolicy({})
- const token = projection.beginSnapshot("servers", "channels")
- projection.absorbSnapshot(token, [{
- channelId: "c1",
- serverId: "s1",
- lastUnreadSeq: 1,
- }])
- projection.absorbSnapshot(token, [{
- channelId: "c2",
- serverId: "s1",
- lastUnreadSeq: 2,
- }])
-
- expect(projection.projectUnread("servers", "c1", false)).toBe(true)
- expect(projection.projectUnread("servers", "c2", false)).toBe(false)
- })
-
- it("applies exact channel over parent over server policy without consuming sources", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.recordArrival({
- channelId: "child",
- railChannelId: "parent",
- serverId: "s1",
- seq: 1,
- isMention: true,
- })
- const before = projection.inspectForTests()
- projection.setNotificationPolicy({
- server: { s1: "nothing" },
- channel: { parent: "mentions", child: "all" },
- })
- expect(projection.projectUnread("servers", "child", false)).toBe(true)
- projection.setNotificationPolicy({
- server: { s1: "nothing" },
- channel: { parent: "mentions" },
- })
- expect(projection.projectUnread("servers", "child", false)).toBe(true)
- projection.setNotificationPolicy({ server: { s1: "nothing" } })
- expect(projection.projectUnread("servers", "child", false)).toBe(false)
- projection.setNotificationPolicy({ server: { s1: "all" } })
- expect(projection.projectUnread("servers", "child", false)).toBe(true)
- expect(projection.inspectForTests().sourceCount).toBe(before.sourceCount)
- expect(projection.inspectForTests().readState).toEqual(before.readState)
- })
-
- it("shows only attention-bearing unread under mentions policy", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.recordArrival({ channelId: "plain", serverId: "s1", seq: 1 })
- projection.recordArrival({
- channelId: "attention",
- serverId: "s1",
- seq: 1,
- isMention: true,
- })
- projection.setNotificationPolicy({ server: { s1: "mentions" } })
- expect(projection.projectUnread("servers", "plain", false)).toBe(false)
- expect(projection.projectUnread("servers", "attention", false)).toBe(true)
- expect(projection.projectUnread("inbox-mentions", "attention", false)).toBe(true)
- })
-
- it("does not let a retired mention identity qualify a later plain raw row", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.setNotificationPolicy({ server: { s1: "mentions" } })
- projection.recordArrival({
- channelId: "c1",
- serverId: "s1",
- seq: 1,
- isMention: true,
- })
- projection.recordRead("c1", 1)
-
- expect(projection.inspectForTests().sourceCount).toBe(0)
- expect(projection.projectUnread("inbox-unreads", "c1", true, 2)).toBe(false)
-
- projection.recordArrival({
- channelId: "c1",
- serverId: "s1",
- seq: 2,
- isMention: true,
- })
- expect(projection.projectUnread("inbox-unreads", "c1", true, 2)).toBe(true)
- })
-
- it("rolls back one policy overlay without overwriting a newer committed overlay", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.setNotificationPolicy({ server: { s1: "all" } })
- projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })
- const older = projection.beginNotificationPolicyOverlay({
- kind: "server",
- id: "s1",
- level: "nothing",
- })
- const newer = projection.beginNotificationPolicyOverlay({
- kind: "channel",
- id: "c1",
- level: "all",
- })
-
- projection.commitNotificationPolicyOverlay(newer)
- expect(projection.projectUnread("servers", "c1", false)).toBe(true)
- projection.rollbackNotificationPolicyOverlay(older)
- expect(projection.projectUnread("servers", "c1", false)).toBe(true)
- })
-
- it("rolls a channel-default overlay back to the exact override", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.setNotificationPolicy({
- server: { s1: "nothing" },
- channel: { c1: "all" },
- })
- projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })
- const token = projection.beginNotificationPolicyOverlay({
- kind: "channel",
- id: "c1",
- level: null,
- })
-
- expect(projection.projectUnread("servers", "c1", false)).toBe(false)
- projection.rollbackNotificationPolicyOverlay(token)
- expect(projection.projectUnread("servers", "c1", false)).toBe(true)
- })
-
- it("dismisses only the matching attention facet and rolls it back", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.setNotificationPolicy({})
- projection.recordArrival({
- channelId: "c1",
- serverId: "s1",
- messageId: "m1",
- seq: 4,
- isMention: true,
- })
- const token = projection.beginDismissMention({
- mentionId: "mention-1",
- channelId: "c1",
- seq: 4,
- })
- expect(projection.projectUnread("servers", "c1", false)).toBe(true)
- expect(projection.projectUnread("inbox-mentions", "c1", false)).toBe(false)
- expect(projection.projectServerMentionCount("s1", [{
- channelId: "c1",
- count: 2,
- lastSeq: 4,
- }])).toBe(1)
- projection.rollbackDismissMention(token)
- expect(projection.projectUnread("inbox-mentions", "c1", false)).toBe(true)
- expect(projection.projectServerMentionCount("s1", [{
- channelId: "c1",
- count: 2,
- lastSeq: 4,
- }])).toBe(2)
-
- const staleSnapshot = projection.beginSnapshot("inbox-mentions", "mentions")
- const committed = projection.beginDismissMention({
- mentionId: "mention-1",
- channelId: "c1",
- seq: 4,
- })
- projection.commitDismissMention(committed, 3)
- projection.absorbSnapshot(staleSnapshot, [], { truncated: false })
- expect(projection.projectUnread(
- "inbox-mentions",
- "c1",
- true,
- 4,
- "mentions",
- null,
- true,
- "mention-1",
- )).toBe(false)
- projection.absorbFamily("servers", [{
- channelId: "c1",
- serverId: "s1",
- lastUnreadSeq: 4,
- lastMentionSeq: 4,
- isMention: true,
- }])
- expect(projection.projectServerMentionCount("s1", [{
- channelId: "c1",
- count: 2,
- lastSeq: 4,
- }])).toBe(1)
-
- const confirmingSnapshot = projection.beginSnapshot("inbox-mentions", "mentions")
- projection.absorbSnapshot(confirmingSnapshot, [], { truncated: false })
- expect(projection.projectServerMentionCount("s1", [{
- channelId: "c1",
- count: 2,
- lastSeq: 4,
- }])).toBe(2)
- })
-
- it("keeps same-seq sibling attention identities and counts only direct mentions", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.setNotificationPolicy({})
- for (const attentionId of ["reply-1", "mention-1"]) {
- projection.recordArrival({
- channelId: "c1",
- serverId: "s1",
- messageId: "m1",
- attentionId,
- seq: 4,
- isMention: true,
- })
- }
-
- const reply = projection.beginDismissMention({
- mentionId: "reply-1",
- channelId: "c1",
- seq: 4,
- countsServerMention: false,
- })
- expect(projection.projectUnread(
- "inbox-mentions", "c1", true, 4, "mentions", null, true, "reply-1",
- )).toBe(false)
- expect(projection.projectUnread(
- "inbox-mentions", "c1", true, 4, "mentions", null, true, "mention-1",
- )).toBe(true)
- expect(projection.projectServerMentionCount("s1", [{
- channelId: "c1", count: 1, lastSeq: 4,
- }])).toBe(1)
-
- projection.rollbackDismissMention(reply)
- projection.beginDismissMention({
- mentionId: "mention-1",
- channelId: "c1",
- seq: 4,
- countsServerMention: true,
- })
- expect(projection.projectUnread(
- "inbox-mentions", "c1", true, 4, "mentions", null, true, "mention-1",
- )).toBe(false)
- expect(projection.projectUnread(
- "inbox-mentions", "c1", true, 4, "mentions", null, true, "reply-1",
- )).toBe(true)
- expect(projection.projectServerMentionCount("s1", [{
- channelId: "c1", count: 1, lastSeq: 4,
- }])).toBe(0)
- })
-
- it("does not let a revision hint alone retire a committed mark-all fence", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.recordArrival({ channelId: "sticky", serverId: "s1" })
- const token = projection.beginMarkAll("channels")
- projection.commitMarkAll(token, 5)
- projection.acceptPrimarySnapshot({ revision: 5, readStates: [] })
- projection.rollbackMarkAll(token)
- expect(projection.projectUnread("servers", "sticky", false)).toBe(true)
- })
-
- it("retires access scope atomically and restores it on rollback", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })
- const token = projection.beginScopeRetirement({ kind: "server", serverId: "s1" })
- expect(projection.projectUnread("servers", "c1", false)).toBe(false)
- projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 2 })
- projection.rollbackScopeRetirement(token)
- expect(projection.projectUnread("servers", "c1", false)).toBe(true)
- projection.retireAccessScope({ kind: "server", serverId: "s1" })
- expect(projection.projectUnread("servers", "c1", false)).toBe(false)
- expect(projection.projectUnread("servers", "c1", true, 1)).toBe(false)
- projection.grantAccessScope({ kind: "server", serverId: "s1" })
- expect(projection.projectUnread("servers", "c1", true, 1)).toBe(false)
- projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 2 })
- expect(projection.projectUnread("servers", "c1", false)).toBe(false)
- const confirmation = projection.beginAccessConfirmation()
- projection.confirmAccessScopes(
- [{ kind: "server", serverId: "s1" }],
- confirmation,
- )
- expect(projection.projectUnread("servers", "c1", false)).toBe(true)
- })
-
- it("lets a post-retirement authority recover a committed access tombstone", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })
- projection.retireAccessScope({ kind: "server", serverId: "s1" })
-
- const serverSnapshot = projection.beginSnapshot("servers", "channels")
- projection.absorbSnapshot(serverSnapshot, [{
- channelId: "c1",
- serverId: "s1",
- lastUnreadSeq: 2,
- }], {
- confirmedAccessScopes: [{ kind: "server", serverId: "s1" }],
- })
-
- expect(projection.projectUnread("servers", "c1", false)).toBe(true)
- expect(projection.inspectForTests().sourceCount).toBe(1)
-
- projection.retireAccessScope({ kind: "channel", channelId: "c1" })
- const channelSnapshot = projection.beginSnapshot("server-detail:s1", "channels")
- projection.absorbSnapshot(channelSnapshot, [{
- channelId: "c1",
- serverId: "s1",
- lastUnreadSeq: 3,
- }], {
- confirmedAccessScopes: [{ kind: "channel", channelId: "c1" }],
- })
-
- expect(projection.projectUnread("server-detail:s1", "c1", false)).toBe(true)
- })
-
- it("rejects a pre-retirement snapshot after a later access grant", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })
- const staleSnapshot = projection.beginSnapshot("servers", "channels")
-
- projection.retireAccessScope({ kind: "server", serverId: "s1" })
- projection.grantAccessScope({ kind: "server", serverId: "s1" })
- projection.absorbSnapshot(staleSnapshot, [{
- channelId: "c1",
- serverId: "s1",
- lastUnreadSeq: 2,
- }], {
- confirmedAccessScopes: [{ kind: "server", serverId: "s1" }],
- })
-
- expect(projection.projectUnread("servers", "c1", false)).toBe(false)
- expect(projection.projectUnread("servers", "c1", true, 2)).toBe(false)
- expect(projection.inspectForTests().sourceCount).toBe(0)
- })
-
- it("inherits a server retirement floor for channels learned behind its tombstone", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.recordArrival({ channelId: "known", serverId: "s1", seq: 1 })
- projection.retireAccessScope({ kind: "server", serverId: "s1" })
-
- projection.recordArrival({ channelId: "late", serverId: "s1", seq: 2 })
- projection.grantAccessScope({ kind: "server", serverId: "s1" })
- const empty = projection.beginSnapshot("servers", "channels")
- projection.absorbSnapshot(empty, [], {
- confirmedAccessScopes: [{ kind: "server", serverId: "s1" }],
- })
-
- expect(projection.projectUnread("inbox-unreads", "late", true, 2)).toBe(false)
- expect(projection.inspectForTests().sourceCount).toBe(0)
- })
-
- it("keeps a retired channel raw row fenced until a fresh snapshot confirms access", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.recordArrival({ channelId: "private", serverId: "s1", seq: 1 })
- projection.retireAccessScope({ kind: "channel", channelId: "private" })
-
- expect(projection.projectUnread("inbox-unreads", "private", true, 1)).toBe(false)
- projection.grantAccessScope({ kind: "channel", channelId: "private" })
- expect(projection.projectUnread("inbox-unreads", "private", true, 1)).toBe(false)
-
- const empty = projection.beginSnapshot("server-detail:s1", "channels")
- projection.absorbSnapshot(empty, [], {
- confirmedAccessScopes: [{ kind: "channel", channelId: "private" }],
- })
- expect(projection.projectUnread("inbox-unreads", "private", true, 1)).toBe(false)
- expect(projection.projectUnread("server-detail:s1", "private", true, 1)).toBe(false)
-
- const positive = projection.beginSnapshot("server-detail:s1", "channels")
- projection.absorbSnapshot(positive, [{
- channelId: "private",
- serverId: "s1",
- lastUnreadSeq: 2,
- }])
- expect(projection.projectUnread("server-detail:s1", "private", true, 2)).toBe(true)
- })
-
- it("releases abandoned snapshot tokens without accepting late evidence", () => {
- const projection = new AccountUnreadProjection("u1")
- const token = projection.beginSnapshot("servers")
- expect(projection.inspectForTests().pendingSnapshots).toBe(1)
- projection.cancelSnapshot(token)
- projection.absorbSnapshot(token, [{ channelId: "late", lastUnreadSeq: 2 }])
- expect(projection.inspectForTests()).toMatchObject({
- pendingSnapshots: 0,
- sourceCount: 0,
- })
- })
-
- it("enriches duplicate exact rows from arrivals and canonical snapshot evidence", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.setNotificationPolicy({})
- projection.recordArrival({ channelId: "arrival", seq: 2 })
- projection.recordArrival({
- channelId: "arrival",
- serverId: "s1",
- railChannelId: "forum-1",
- seq: 2,
- })
- expect(projection.hasPending(undefined, "channels")).toBe(true)
- expect(projection.projectServerChannelUnread("s1", "forum-1", [], false)).toBe(true)
-
- projection.recordArrival({ channelId: "snapshot", seq: 3 })
- const token = projection.beginSnapshot("inbox-mentions", "mentions")
- projection.absorbSnapshot(token, [{
- channelId: "snapshot",
- serverId: "s1",
- railChannelId: "forum-1",
- lastUnreadSeq: 3,
- lastMentionSeq: 3,
- isMention: true,
- attentionId: "attention-1",
- }], { truncated: true })
-
- expect(projection.projectUnread(
- "inbox-mentions", "snapshot", false, 3, "mentions", null, true, "attention-1",
- )).toBe(true)
- expect(projection.projectServerChannelUnread("s1", "forum-1", [], false)).toBe(true)
- })
-
- it("preserves authoritative server and channel bases beneath pending policy overlays", () => {
- const serverProjection = new AccountUnreadProjection("u1")
- serverProjection.setNotificationPolicy({ server: { s1: "mentions" } })
- const serverToken = serverProjection.beginNotificationPolicyOverlay({
- kind: "server",
- id: "s1",
- level: "nothing",
- })
- serverProjection.setNotificationPolicy({ server: { s1: "all" } })
- serverProjection.rollbackNotificationPolicyOverlay(serverToken)
- serverProjection.recordArrival({
- channelId: "c1", serverId: "s1", seq: 1, isMention: true,
- })
- expect(serverProjection.projectUnread("servers", "c1", false)).toBe(true)
-
- const channelProjection = new AccountUnreadProjection("u1")
- channelProjection.setNotificationPolicy({ channel: { c1: "mentions" } })
- const channelToken = channelProjection.beginNotificationPolicyOverlay({
- kind: "channel",
- id: "c1",
- level: "nothing",
- })
- channelProjection.setNotificationPolicy({ channel: { c1: "all" } })
- channelProjection.rollbackNotificationPolicyOverlay(channelToken)
- channelProjection.recordArrival({
- channelId: "c1", serverId: "s1", seq: 1, isMention: true,
- })
- expect(channelProjection.projectUnread("servers", "c1", false)).toBe(true)
-
- const absentChannelProjection = new AccountUnreadProjection("u1")
- absentChannelProjection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })
- const absentToken = absentChannelProjection.beginNotificationPolicyOverlay({
- kind: "channel",
- id: "c1",
- level: "nothing",
- })
- expect(absentChannelProjection.projectUnread("servers", "c1", false)).toBe(false)
- absentChannelProjection.setNotificationPolicy({})
- expect(absentChannelProjection.projectUnread("servers", "c1", false)).toBe(false)
- absentChannelProjection.rollbackNotificationPolicyOverlay(absentToken)
- expect(absentChannelProjection.projectUnread("servers", "c1", false)).toBe(true)
- })
-
- it("matches identity-free attention dismissals by seq and ignores newer dismissals in counts", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.setNotificationPolicy({})
- projection.beginDismissMention({
- mentionId: "same-seq", channelId: "c1", seq: 4, countsServerMention: false,
- })
- expect(projection.projectUnread(
- "inbox-mentions", "c1", true, 4, "mentions", null, true,
- )).toBe(false)
-
- projection.beginDismissMention({
- mentionId: "future",
- channelId: "c1",
- seq: 5,
- countsServerMention: true,
- })
- expect(projection.projectMentionCount("servers", "c1", 1, 4)).toBe(1)
- })
-
- it("settles a confirmed mark-all fence after its captured source is read", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.setNotificationPolicy({})
- projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })
- const markAll = projection.beginMarkAll("channels")
- projection.commitMarkAll(markAll, 1)
- projection.acceptPrimarySnapshot({ revision: 1, readStates: [] })
- projection.recordRead("c1", 1)
-
- const snapshot = projection.beginSnapshot("servers", "channels")
- projection.absorbSnapshot(snapshot, [])
-
- expect(projection.projectUnread("servers", "fresh", true, 2)).toBe(true)
- })
-
- it("keeps every public operation inert after disposal", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.dispose()
- const listener = vi.fn()
- projection.subscribe(listener)()
- projection.setReconcileScheduler(listener)
- projection.settleOptimisticRead(1, true, 1)
- projection.acceptPrimarySnapshot({ revision: 1, readStates: [] })
- projection.absorbFamily("servers", [{ channelId: "c1", lastUnreadSeq: 1 }])
- expect(projection.projectUnread("servers", "c1", true, 1)).toBe(false)
- expect(projection.projectMentionCount("servers", "c1", 1, 1)).toBe(0)
-
- const policy = projection.beginNotificationPolicyOverlay({
- kind: "server",
- id: "s1",
- level: "nothing",
- })
- projection.commitNotificationPolicyOverlay(policy)
- projection.rollbackNotificationPolicyOverlay(policy)
- const dismissal = projection.beginDismissMention({ mentionId: "m1", channelId: "c1" })
- projection.commitDismissMention(dismissal)
- projection.rollbackDismissMention(dismissal)
- const retirement = projection.beginScopeRetirement({ kind: "server", serverId: "s1" })
- projection.commitScopeRetirement(retirement)
- projection.rollbackScopeRetirement(retirement)
- projection.retireAccessScope({ kind: "server", serverId: "s1" })
- projection.grantAccessScope({ kind: "server", serverId: "s1" })
- projection.confirmAccessScopes(
- [{ kind: "server", serverId: "s1" }],
- projection.beginAccessConfirmation(),
- )
- const markAll = projection.beginMarkAll("channels")
- projection.commitMarkAll(markAll, 1)
- projection.rollbackMarkAll(markAll)
- projection.dispose()
-
- expect(listener).not.toHaveBeenCalled()
- })
-
- it("fences late snapshots and mutations after disposal", () => {
- const projection = new AccountUnreadProjection("u1")
- projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })
- const snapshot = projection.beginSnapshot("servers")
- const scope = projection.beginScopeRetirement({ kind: "server", serverId: "s1" })
- projection.dispose()
- projection.absorbSnapshot(snapshot, [{ channelId: "late", lastUnreadSeq: 2 }])
- projection.rollbackScopeRetirement(scope)
- projection.recordArrival({ channelId: "late", seq: 2 })
- expect(projection.inspectForTests()).toMatchObject({ sourceCount: 0, disposed: true })
- })
-
- it("disposes one account or an entire query-client ledger", () => {
- const client = new QueryClient()
- const first = getAccountUnreadProjection(client, "u1")
- getAccountUnreadProjection(client, "u2")
-
- disposeAccountUnreadProjection(client, "u1")
- expect(getAccountUnreadProjection(client, "u1")).not.toBe(first)
-
- disposeAccountUnreadProjection(client)
- const anonymous = getActiveAccountUnreadProjection(client)
- expect(anonymous.ownerUserId).toBe("__anonymous__")
- disposeAccountUnreadProjection(new QueryClient())
- })
-})
diff --git a/src/web/src/hooks/community/account-unread-projection.ts b/src/web/src/hooks/community/account-unread-projection.ts
deleted file mode 100644
index fbfff13e3..000000000
--- a/src/web/src/hooks/community/account-unread-projection.ts
+++ /dev/null
@@ -1,2029 +0,0 @@
-import type { queries } from "@alook/shared"
-import type { ReadCoordinatorSnapshot } from "./read-coordinator-snapshot-projection"
-import { batch, createStore } from "@tanstack/store"
-import type { QueryClient } from "@tanstack/react-query"
-
-type AccountUnreadPrimarySnapshot = Pick<queries.communityReadState.AccountReadStateSnapshot, "revision"> & ReadCoordinatorSnapshot
-
-export type AccountUnreadFamily =
- | "servers"
- | `server-detail:${string}`
- | "inbox-unreads"
- | "inbox-mentions"
- | "dms"
-
-export type AccountUnreadDomain = "channels" | "dms" | "mentions"
-
-export type AccountUnreadArrival = {
- channelId: string
- railChannelId?: string
- serverId?: string
- messageId?: string | null
- attentionId?: string
- seq?: number
- isMention?: boolean
-}
-
-export type AccountUnreadSource = {
- channelId: string
- lastUnreadSeq: number
- mentionCount?: number
- lastMentionSeq?: number | null
- serverId?: string
- railChannelId?: string
- messageId?: string
- attentionId?: string
- isMention?: boolean
-}
-
-export type AccountUnreadPresentationExclusion = {
- channelId: string
- throughSeq?: number
-}
-
-export type AccountUnreadLegacySource = {
- family: AccountUnreadFamily
- channelId: string
- serverId?: string
- railChannelId?: string
- isMention?: boolean
-}
-
-type PendingArrival = {
- key: string
- channelId: string
- serverId?: string
- railChannelId?: string
- seq: number
- ordinal: number
- isMention: boolean
- attentionIds: Set<string>
- families: Map<AccountUnreadFamily, number>
-}
-
-type StickyUnknown = {
- channelId: string
- serverId?: string
- railChannelId?: string
- messageId?: string | null
- isMention: boolean
- attentionIds: Set<string>
- families: Map<AccountUnreadFamily, { boundary: number; ordinal: number }>
-}
-
-export type AccountUnreadFacet = "ordinary" | "attention"
-
-type AccountUnreadPolicyLevel = "all" | "mentions" | "nothing"
-
-export type AccountUnreadPolicySnapshot = {
- all?: AccountUnreadPolicyLevel | string
- server?: Readonly<Record<string, AccountUnreadPolicyLevel | string>>
- channel?: Readonly<Record<string, AccountUnreadPolicyLevel | string>>
- parentByChannel?: Readonly<Record<string, string>>
-}
-
-export type AccountUnreadPolicyPatch =
- | { kind: "server"; id: string; level: AccountUnreadPolicyLevel | string }
- | { kind: "channel"; id: string; level: AccountUnreadPolicyLevel | string | null }
-
-export type AccountUnreadPolicyToken = {
- nonce: symbol
- ownerEpoch: number
-}
-
-type FrozenPolicy = {
- all: AccountUnreadPolicyLevel
- server: ReadonlyMap<string, AccountUnreadPolicyLevel>
- channel: ReadonlyMap<string, AccountUnreadPolicyLevel>
- parentByChannel: ReadonlyMap<string, string>
-}
-
-type MutablePolicy = {
- all: AccountUnreadPolicyLevel
- server: Map<string, AccountUnreadPolicyLevel>
- channel: Map<string, AccountUnreadPolicyLevel>
- parentByChannel: Map<string, string>
-}
-
-export type AccountUnreadSnapshotToken = {
- family: AccountUnreadFamily
- domain: AccountUnreadDomain
- startOrdinal: number
- policyGeneration: number
- eligibleCoverage: ReadonlySet<AccountUnreadFacet>
- nonce: symbol
- ownerEpoch: number
- policy: FrozenPolicy
-}
-
-export type AccountUnreadScope =
- | { kind: "server"; serverId: string }
- | { kind: "channel"; channelId: string }
-
-export type AccountUnreadScopeToken = {
- scope: AccountUnreadScope
- ordinal: number
- nonce: symbol
- ownerEpoch: number
-}
-
-export type AccountUnreadAccessConfirmationToken = {
- ordinal: number
- ownerEpoch: number
-}
-
-type AccountUnreadScopeHint = Pick<
- PendingArrival,
- "channelId" | "serverId" | "railChannelId"
->
-
-export type AccountUnreadDismissToken = {
- mentionId: string
- channelId: string
- seq?: number
- countsServerMention: boolean
- ordinal: number
- nonce: symbol
- ownerEpoch: number
-}
-
-export type MarkAllToken = {
- domain: AccountUnreadDomain
- ordinal: number
- nonce: symbol
-}
-
-type MarkAllFence = MarkAllToken & {
- state: "pending" | "committed"
- revision: number | null
-}
-
-export const MAX_EXACT_ARRIVALS = 512
-export const MAX_EXACT_ARRIVALS_PER_CHANNEL = 64
-export const MAX_STICKY_SCOPES = 256
-
-const owners = new WeakMap<QueryClient, Map<string, AccountUnreadProjection>>()
-const activeOwners = new WeakMap<QueryClient, string>()
-
-function familiesFor(arrival: AccountUnreadArrival): AccountUnreadFamily[] {
- const families: AccountUnreadFamily[] = ["inbox-unreads"]
- if (arrival.serverId) {
- families.push("servers", `server-detail:${arrival.serverId}`)
- } else {
- families.push("dms")
- }
- if (arrival.isMention) families.push("inbox-mentions")
- return families
-}
-
-function familyDomain(family: AccountUnreadFamily): AccountUnreadDomain {
- if (family === "dms") return "dms"
- if (family === "inbox-mentions") return "mentions"
- return "channels"
-}
-
-function arrivalDomain(
- family: AccountUnreadFamily,
- serverId: string | undefined,
-): AccountUnreadDomain {
- if (family === "inbox-mentions") return "mentions"
- return serverId ? "channels" : "dms"
-}
-
-function excludesUnread(
- exclusion: AccountUnreadPresentationExclusion | null | undefined,
- channelId: string,
- seq?: number | null,
-) {
- if (!exclusion || exclusion.channelId !== channelId) return false
- if (exclusion.throughSeq === undefined) return true
- return seq !== undefined && seq !== null && seq <= exclusion.throughSeq
-}
-
-function normalizePolicyLevel(value?: string): AccountUnreadPolicyLevel {
- const normalized = value?.trim().toLowerCase()
- if (normalized === "nothing") return "nothing"
- if (normalized === "mentions" || normalized?.includes("mention")) return "mentions"
- return "all"
-}
-
-function freezePolicy(snapshot: AccountUnreadPolicySnapshot): MutablePolicy {
- return {
- all: normalizePolicyLevel(snapshot.all),
- server: new Map(Object.entries(snapshot.server ?? {}).map(([id, level]) => (
- [id, normalizePolicyLevel(level)]
- ))),
- channel: new Map(Object.entries(snapshot.channel ?? {}).map(([id, level]) => (
- [id, normalizePolicyLevel(level)]
- ))),
- parentByChannel: new Map(Object.entries(snapshot.parentByChannel ?? {})),
- }
-}
-
-function policySignature(policy: FrozenPolicy) {
- const sortEntries = <T,>(values: ReadonlyMap<string, T>) => (
- [...values.entries()].sort(([left], [right]) => left.localeCompare(right))
- )
- return JSON.stringify([
- policy.all,
- sortEntries(policy.server),
- sortEntries(policy.channel),
- sortEntries(policy.parentByChannel),
- ])
-}
-
-function scopeKey(scope: AccountUnreadScope) {
- return scope.kind === "server"
- ? `server:${scope.serverId}`
- : `channel:${scope.channelId}`
-}
-
-function copyArrival(source: PendingArrival): PendingArrival {
- return { ...source, attentionIds: new Set(source.attentionIds), families: new Map(source.families) }
-}
-
-function copySticky(source: StickyUnknown): StickyUnknown {
- return { ...source, attentionIds: new Set(source.attentionIds), families: new Map([...source.families].map(([family, value]) => [family, { ...value }])) }
-}
-
-export type AccountUnreadState = {
- ordinal: number
- ownerEpoch: number
- disposed: boolean
- highestRevision: number
- policyGeneration: number
- policyReady: boolean
- policy: FrozenPolicy
- policyBase: MutablePolicy
- policyOverlays: Map<symbol, {
- patch: AccountUnreadPolicyPatch
- state: "pending" | "committed"
- }>
- reconcileScheduled: boolean
- reconcilePendingDelivery: boolean
- lastPolicyReconcileGeneration: number
- prePolicySnapshotNeedsReconcile: boolean
- exact: Map<string, PendingArrival>
- exactByChannel: Map<string, Set<string>>
- sticky: Map<string, StickyUnknown>
- evidence: Map<string, number>
- readSeq: Map<string, number>
- optimisticReads: Map<number, { channelId: string; seq: number; committed: boolean }>
- markAll: Map<AccountUnreadDomain, MarkAllFence>
- scopeHints: Map<string, AccountUnreadScopeHint>
- rawRetirementFloors: Map<string, number>
- accessFences: Map<string, AccountUnreadScopeToken & { state: "pending" | "committed" | "grant-pending" }>
- dismissals: Map<symbol, AccountUnreadDismissToken & { state: "pending" | "committed" }>
- snapshots: Set<symbol>
-}
-
-export function accountUnreadAllowsAccess(state: AccountUnreadState, source: { channelId?: string; serverId?: string | null }) {
- return !state.disposed
- && (!source.channelId || !state.accessFences.has(`channel:${source.channelId}`))
- && (!source.serverId || !state.accessFences.has(`server:${source.serverId}`))
-}
-
-function initialUnreadState(): AccountUnreadState {
- return {
- ordinal: 0,
- ownerEpoch: 0,
- disposed: false,
- highestRevision: -1,
- policyGeneration: 0,
- policyReady: false,
- policy: {
- all: "all",
- server: new Map(),
- channel: new Map(),
- parentByChannel: new Map(),
- },
- policyBase: {
- all: "all",
- server: new Map(),
- channel: new Map(),
- parentByChannel: new Map(),
- },
- policyOverlays: new Map<symbol, {
- patch: AccountUnreadPolicyPatch
- state: "pending" | "committed"
- }>(),
- reconcileScheduled: false,
- reconcilePendingDelivery: false,
- lastPolicyReconcileGeneration: -1,
- prePolicySnapshotNeedsReconcile: false,
- exact: new Map<string, PendingArrival>(),
- exactByChannel: new Map<string, Set<string>>(),
- sticky: new Map<string, StickyUnknown>(),
- evidence: new Map<string, number>(),
- readSeq: new Map<string, number>(),
- optimisticReads: new Map<
- number,
- { channelId: string; seq: number; committed: boolean }
- >(),
- markAll: new Map<AccountUnreadDomain, MarkAllFence>(),
- scopeHints: new Map<string, AccountUnreadScopeHint>(),
- rawRetirementFloors: new Map<string, number>(),
- accessFences: new Map<
- string,
- AccountUnreadScopeToken & { state: "pending" | "committed" | "grant-pending" }
- >(),
- dismissals: new Map<
- symbol,
- AccountUnreadDismissToken & { state: "pending" | "committed" }
- >(),
- snapshots: new Set<symbol>(),
- }
-}
-
-export class AccountUnreadProjection {
- readonly state = createStore(initialUnreadState())
- private reconcile: (() => void) | null = null
- private readonly legacySnapshots = new WeakSet<object>()
-
- private get ordinal(): AccountUnreadState["ordinal"] { return this.state.get().ordinal }
- private set ordinal(value: AccountUnreadState["ordinal"]) { this.state.setState((state) => state.ordinal === value ? state : { ...state, ordinal: value }) }
- private get ownerEpoch(): AccountUnreadState["ownerEpoch"] { return this.state.get().ownerEpoch }
- private set ownerEpoch(value: AccountUnreadState["ownerEpoch"]) { this.state.setState((state) => state.ownerEpoch === value ? state : { ...state, ownerEpoch: value }) }
- private get disposed(): AccountUnreadState["disposed"] { return this.state.get().disposed }
- private set disposed(value: AccountUnreadState["disposed"]) { this.state.setState((state) => state.disposed === value ? state : { ...state, disposed: value }) }
- private get highestRevision(): AccountUnreadState["highestRevision"] { return this.state.get().highestRevision }
- private set highestRevision(value: AccountUnreadState["highestRevision"]) { this.state.setState((state) => state.highestRevision === value ? state : { ...state, highestRevision: value }) }
- private get policyGeneration(): AccountUnreadState["policyGeneration"] { return this.state.get().policyGeneration }
- private set policyGeneration(value: AccountUnreadState["policyGeneration"]) { this.state.setState((state) => state.policyGeneration === value ? state : { ...state, policyGeneration: value }) }
- private get policyReady(): AccountUnreadState["policyReady"] { return this.state.get().policyReady }
- private set policyReady(value: AccountUnreadState["policyReady"]) { this.state.setState((state) => state.policyReady === value ? state : { ...state, policyReady: value }) }
- private get policy(): AccountUnreadState["policy"] { return this.state.get().policy }
- private set policy(value: AccountUnreadState["policy"]) { this.state.setState((state) => state.policy === value ? state : { ...state, policy: value }) }
- private get policyBase(): AccountUnreadState["policyBase"] { return this.state.get().policyBase }
- private set policyBase(value: AccountUnreadState["policyBase"]) { this.state.setState((state) => state.policyBase === value ? state : { ...state, policyBase: value }) }
- private get policyOverlays(): AccountUnreadState["policyOverlays"] { return this.state.get().policyOverlays }
- private set policyOverlays(value: AccountUnreadState["policyOverlays"]) { this.state.setState((state) => state.policyOverlays === value ? state : { ...state, policyOverlays: value }) }
- private get reconcileScheduled(): AccountUnreadState["reconcileScheduled"] { return this.state.get().reconcileScheduled }
- private set reconcileScheduled(value: AccountUnreadState["reconcileScheduled"]) { this.state.setState((state) => state.reconcileScheduled === value ? state : { ...state, reconcileScheduled: value }) }
- private get reconcilePendingDelivery(): AccountUnreadState["reconcilePendingDelivery"] { return this.state.get().reconcilePendingDelivery }
- private set reconcilePendingDelivery(value: AccountUnreadState["reconcilePendingDelivery"]) { this.state.setState((state) => state.reconcilePendingDelivery === value ? state : { ...state, reconcilePendingDelivery: value }) }
- private get lastPolicyReconcileGeneration(): AccountUnreadState["lastPolicyReconcileGeneration"] { return this.state.get().lastPolicyReconcileGeneration }
- private set lastPolicyReconcileGeneration(value: AccountUnreadState["lastPolicyReconcileGeneration"]) { this.state.setState((state) => state.lastPolicyReconcileGeneration === value ? state : { ...state, lastPolicyReconcileGeneration: value }) }
- private get prePolicySnapshotNeedsReconcile(): AccountUnreadState["prePolicySnapshotNeedsReconcile"] { return this.state.get().prePolicySnapshotNeedsReconcile }
- private set prePolicySnapshotNeedsReconcile(value: AccountUnreadState["prePolicySnapshotNeedsReconcile"]) { this.state.setState((state) => state.prePolicySnapshotNeedsReconcile === value ? state : { ...state, prePolicySnapshotNeedsReconcile: value }) }
- private get exact(): AccountUnreadState["exact"] { return this.state.get().exact }
- private set exact(value: AccountUnreadState["exact"]) { this.state.setState((state) => state.exact === value ? state : { ...state, exact: value }) }
- private get exactByChannel(): AccountUnreadState["exactByChannel"] { return this.state.get().exactByChannel }
- private set exactByChannel(value: AccountUnreadState["exactByChannel"]) { this.state.setState((state) => state.exactByChannel === value ? state : { ...state, exactByChannel: value }) }
- private get sticky(): AccountUnreadState["sticky"] { return this.state.get().sticky }
- private set sticky(value: AccountUnreadState["sticky"]) { this.state.setState((state) => state.sticky === value ? state : { ...state, sticky: value }) }
- private get evidence(): AccountUnreadState["evidence"] { return this.state.get().evidence }
- private set evidence(value: AccountUnreadState["evidence"]) { this.state.setState((state) => state.evidence === value ? state : { ...state, evidence: value }) }
- private get readSeq(): AccountUnreadState["readSeq"] { return this.state.get().readSeq }
- private set readSeq(value: AccountUnreadState["readSeq"]) { this.state.setState((state) => state.readSeq === value ? state : { ...state, readSeq: value }) }
- private get optimisticReads(): AccountUnreadState["optimisticReads"] { return this.state.get().optimisticReads }
- private set optimisticReads(value: AccountUnreadState["optimisticReads"]) { this.state.setState((state) => state.optimisticReads === value ? state : { ...state, optimisticReads: value }) }
- private get markAll(): AccountUnreadState["markAll"] { return this.state.get().markAll }
- private set markAll(value: AccountUnreadState["markAll"]) { this.state.setState((state) => state.markAll === value ? state : { ...state, markAll: value }) }
- private get scopeHints(): AccountUnreadState["scopeHints"] { return this.state.get().scopeHints }
- private set scopeHints(value: AccountUnreadState["scopeHints"]) { this.state.setState((state) => state.scopeHints === value ? state : { ...state, scopeHints: value }) }
- private get rawRetirementFloors(): AccountUnreadState["rawRetirementFloors"] { return this.state.get().rawRetirementFloors }
- private set rawRetirementFloors(value: AccountUnreadState["rawRetirementFloors"]) { this.state.setState((state) => state.rawRetirementFloors === value ? state : { ...state, rawRetirementFloors: value }) }
- private get accessFences(): AccountUnreadState["accessFences"] { return this.state.get().accessFences }
- private set accessFences(value: AccountUnreadState["accessFences"]) { this.state.setState((state) => state.accessFences === value ? state : { ...state, accessFences: value }) }
- private get dismissals(): AccountUnreadState["dismissals"] { return this.state.get().dismissals }
- private set dismissals(value: AccountUnreadState["dismissals"]) { this.state.setState((state) => state.dismissals === value ? state : { ...state, dismissals: value }) }
- private get snapshots(): AccountUnreadState["snapshots"] { return this.state.get().snapshots }
- private set snapshots(value: AccountUnreadState["snapshots"]) { this.state.setState((state) => state.snapshots === value ? state : { ...state, snapshots: value }) }
-
- private changeMap<K extends "policyOverlays" | "exact" | "exactByChannel" | "sticky" | "evidence" | "readSeq" | "optimisticReads" | "markAll" | "scopeHints" | "rawRetirementFloors" | "accessFences" | "dismissals", R>(
- field: K, change: (map: AccountUnreadState[K]) => R,
- ): R {
- const next = new Map(this.state.get()[field] as Map<unknown, unknown>) as AccountUnreadState[K]
- const result = change(next)
- const previous = this.state.get()[field] as Map<unknown, unknown>
- if (next.size !== previous.size || [...(next as Map<unknown, unknown>)].some(([key, value]) => !previous.has(key) || previous.get(key) !== value)) {
- this.state.setState((state) => ({ ...state, [field]: next }))
- }
- return result
- }
-
- private changeSet<R>(change: (snapshots: Set<symbol>) => R): R {
- const next = new Set(this.snapshots)
- const result = change(next)
- if (next.size !== this.snapshots.size || [...next].some((nonce) => !this.snapshots.has(nonce))) this.snapshots = next
- return result
- }
-
- private transition<T>(operation: () => T): T {
- let result!: T
- batch(() => { result = operation() })
- return result
- }
-
- constructor(readonly ownerUserId: string) {}
-
- subscribe = (listener: () => void) => {
- if (this.disposed) return () => undefined
- const subscription = this.state.subscribe(listener)
- return () => subscription.unsubscribe()
- }
-
- getSnapshot = () => this.state.get()
-
- allowsAccess(source: { channelId?: string; serverId?: string | null }) {
- return accountUnreadAllowsAccess(this.state.get(), source)
- }
-
- setReconcileScheduler(reconcile: (() => void) | null) {
- return this.transition(() => {
- if (this.disposed) return
- this.reconcile = reconcile
- if (reconcile && this.reconcilePendingDelivery) {
- this.reconcilePendingDelivery = false
- reconcile()
- }
- })
- }
-
- recordArrival(arrival: AccountUnreadArrival) {
- return this.transition(() => {
- this.recordArrivalForFamilies(arrival, familiesFor(arrival))
- })
- }
-
- recordMentionArrival(arrival: AccountUnreadArrival) {
- return this.transition(() => {
- const knownSource = this.findSourceScope(arrival.channelId)
- const knownScope = knownSource ?? this.scopeHints.get(arrival.channelId)
- const enriched = {
- ...arrival,
- serverId: arrival.serverId ?? knownScope?.serverId,
- railChannelId: arrival.railChannelId ?? knownScope?.railChannelId,
- isMention: true,
- }
- const families: AccountUnreadFamily[] = enriched.serverId
- ? familiesFor(enriched)
- : knownSource?.families.has("dms")
- ? ["inbox-unreads", "inbox-mentions", "dms"]
- : ["inbox-unreads", "inbox-mentions"]
- this.recordArrivalForFamilies(enriched, families)
- })
- }
-
- recordLegacySnapshot(
- snapshot: object,
- sources: readonly AccountUnreadLegacySource[],
- ) {
- return this.transition(() => {
- if (this.disposed || this.legacySnapshots.has(snapshot)) return
- this.legacySnapshots.add(snapshot)
- for (const source of sources) {
- // Legacy rows carry no request-start token. While a committed/granting
- // access fence exists they cannot prove that their unread bit was read
- // after the retirement, so let fresh structural authority clear the
- // fence before admitting them.
- this.rememberScope(source)
- if (!this.scopeAllowsLegacySnapshot(source)) continue
- this.recordSticky(
- source.channelId,
- [source.family],
- source.isMention === true,
- source.serverId,
- source.railChannelId,
- )
- }
- })
- }
-
- absorbLegacyServerAggregate(
- serverId: string,
- sources: readonly AccountUnreadSource[],
- ) {
- return this.transition(() => {
- if (this.disposed || sources.length === 0) return
- const channelId = `\u0000legacy-server:${serverId}`
- const source = this.sticky.get(channelId)
- const unknown = source ? copySticky(source) : undefined
- if (!unknown?.families.delete("servers")) return
- if (unknown.families.size === 0) this.changeMap("sticky", (map) => map.delete(channelId))
- else this.changeMap("sticky", (map) => map.set(channelId, unknown))
- })
- }
-
- private recordArrivalForFamilies(
- arrival: AccountUnreadArrival,
- families: AccountUnreadFamily[],
- observedOrdinal?: number,
- ) {
- if (this.disposed || !arrival.channelId) return
- this.rememberScope(arrival)
- if (!this.scopeAllowsArrival(arrival, observedOrdinal)) return
- const seq = arrival.seq
- if (!Number.isSafeInteger(seq) || (seq ?? 0) <= 0) {
- this.recordSticky(
- arrival.channelId,
- families,
- arrival.isMention === true,
- arrival.serverId,
- arrival.railChannelId,
- observedOrdinal,
- arrival.messageId,
- arrival.attentionId,
- )
- return
- }
- if (seq! <= (this.readSeq.get(arrival.channelId) ?? 0)) return
- const key = arrival.messageId
- ? `${arrival.channelId}:${arrival.messageId}`
- : `${arrival.channelId}:seq:${seq}`
- const channelKeys = new Set(this.exactByChannel.get(arrival.channelId))
- const previousArrival = this.exact.get(key) ?? [...channelKeys]
- .map((candidate) => this.exact.get(candidate))
- .find((candidate) => candidate?.seq === seq)
- const existing = previousArrival ? copyArrival(previousArrival) : undefined
- if (existing) {
- let changed = false
- let membershipOrdinal = this.ordinal
- for (const family of families) {
- const previous = existing.families.get(family)
- // Snapshot evidence with an observed ordinal is merged by
- // recordSnapshotSource before this fallback. An existing row here is
- // therefore always a live-arrival merge and gets a fresh ordinal.
- if (previous === undefined) {
- if (!changed) membershipOrdinal = ++this.ordinal
- existing.families.set(family, membershipOrdinal)
- changed = true
- }
- }
- if (!existing.isMention && arrival.isMention === true) {
- existing.isMention = true
- changed = true
- }
- if (arrival.attentionId && !existing.attentionIds.has(arrival.attentionId)) {
- existing.attentionIds.add(arrival.attentionId)
- changed = true
- }
- if (!existing.serverId && arrival.serverId) {
- existing.serverId = arrival.serverId
- changed = true
- }
- if (!existing.railChannelId && arrival.railChannelId) {
- existing.railChannelId = arrival.railChannelId
- changed = true
- }
- if (changed) this.changeMap("exact", (map) => map.set(existing.key, existing))
- return
- }
- if (
- this.exact.size >= MAX_EXACT_ARRIVALS
- || channelKeys.size >= MAX_EXACT_ARRIVALS_PER_CHANNEL
- ) {
- const foldedFamilies = new Set(families)
- let isMention = arrival.isMention === true
- let serverId = arrival.serverId
- let railChannelId = arrival.railChannelId
- const attentionIds = new Set(arrival.attentionId ? [arrival.attentionId] : [])
- for (const exactKey of [...channelKeys]) {
- const folded = this.exact.get(exactKey)!
- for (const family of folded.families.keys()) foldedFamilies.add(family)
- isMention ||= folded.isMention
- serverId ??= folded.serverId
- railChannelId ??= folded.railChannelId
- for (const attentionId of folded.attentionIds) attentionIds.add(attentionId)
- this.removeExact(exactKey)
- }
- this.recordSticky(
- arrival.channelId,
- [...foldedFamilies],
- isMention,
- serverId,
- railChannelId,
- observedOrdinal,
- undefined,
- undefined,
- attentionIds,
- )
- return
- }
- const matchingSticky = this.sticky.get(arrival.channelId)
- const correlatedSticky = arrival.messageId
- && matchingSticky?.messageId === arrival.messageId
- ? matchingSticky
- : undefined
- const pendingOrdinal = observedOrdinal ?? ++this.ordinal
- const pending: PendingArrival = {
- key,
- channelId: arrival.channelId,
- serverId: arrival.serverId ?? correlatedSticky?.serverId,
- railChannelId: arrival.railChannelId ?? correlatedSticky?.railChannelId,
- seq: seq!,
- ordinal: Math.max(
- pendingOrdinal,
- ...[...(correlatedSticky?.families.values() ?? [])].map((membership) => (
- membership.ordinal
- )),
- ),
- isMention: arrival.isMention === true || correlatedSticky?.isMention === true,
- attentionIds: new Set([
- ...(correlatedSticky?.attentionIds ?? []),
- ...(arrival.attentionId ? [arrival.attentionId] : []),
- ]),
- families: new Map(),
- }
- for (const [family, membership] of correlatedSticky?.families ?? []) {
- pending.families.set(family, membership.ordinal)
- }
- for (const family of families) {
- pending.families.set(
- family,
- Math.max(pending.families.get(family) ?? -1, pendingOrdinal),
- )
- }
- if (correlatedSticky) this.changeMap("sticky", (map) => map.delete(arrival.channelId))
- this.changeMap("exact", (map) => map.set(key, pending))
- channelKeys.add(key)
- this.changeMap("exactByChannel", (map) => map.set(arrival.channelId, channelKeys))
-
- }
-
- getConfirmedReadSeq(channelId: string) {
- return this.disposed ? undefined : this.readSeq.get(channelId)
- }
-
- recordRead(channelId: string, seq: number) {
- return this.transition(() => {
- if (this.disposed || !Number.isSafeInteger(seq) || seq <= 0) return
- const previous = this.readSeq.get(channelId) ?? 0
- if (seq <= previous) return
- this.changeMap("readSeq", (map) => map.set(channelId, seq))
- for (const key of this.exactByChannel.get(channelId) ?? []) {
- const arrival = this.exact.get(key)
- if (arrival && arrival.seq <= seq) this.removeExact(key)
- }
-
- })
- }
-
- recordOptimisticRead(channelId: string, seq: number, generation: number) {
- return this.transition(() => {
- if (this.disposed || !Number.isSafeInteger(seq) || seq <= 0) return
- this.changeMap("optimisticReads", (map) => map.set(generation, { channelId, seq, committed: false }))
-
- })
- }
-
- settleOptimisticRead(
- generation: number,
- committed: boolean,
- confirmedSeq?: number,
- ) {
- return this.transition(() => {
- if (this.disposed) return
- const optimistic = this.optimisticReads.get(generation)
- if (!optimistic) return
- if (committed) {
- this.changeMap("optimisticReads", (map) => map.set(generation, { ...optimistic, seq: Math.max(optimistic.seq, confirmedSeq ?? 0), committed: true }))
- return
- }
- this.changeMap("optimisticReads", (map) => map.delete(generation))
-
- })
- }
-
- acceptPrimarySnapshot(snapshot: AccountUnreadPrimarySnapshot) {
- return this.transition(() => {
- if (this.disposed || snapshot.revision < this.highestRevision) return
- this.highestRevision = snapshot.revision
- for (const row of snapshot.readStates) {
- this.recordRead(row.channelId, row.lastReadSeq)
- for (const [generation, optimistic] of this.optimisticReads) {
- if (
- optimistic.channelId === row.channelId
- && optimistic.seq <= row.lastReadSeq
- ) this.changeMap("optimisticReads", (map) => map.delete(generation))
- }
- }
- for (const [domain, fence] of this.markAll) {
- if (
- fence.state === "committed"
- && fence.revision !== null
- && snapshot.revision >= fence.revision
- ) {
- if (!this.hasCapturedDomainSource(domain, fence.ordinal)) {
- this.changeMap("markAll", (map) => map.delete(domain))
- }
- }
- }
-
- })
- }
-
- beginSnapshot(
- family: AccountUnreadFamily,
- domain: AccountUnreadDomain = familyDomain(family),
- eligibleCoverage: Iterable<AccountUnreadFacet> = [
- family === "inbox-mentions" ? "attention" : "ordinary",
- ],
- ): AccountUnreadSnapshotToken {
- return this.transition(() => {
- this.reconcileScheduled = false
- const token = {
- family,
- domain,
- startOrdinal: this.disposed ? this.ordinal : ++this.ordinal,
- policyGeneration: this.policyGeneration,
- eligibleCoverage: new Set(this.policyReady ? eligibleCoverage : []),
- nonce: Symbol(family),
- ownerEpoch: this.ownerEpoch,
- policy: this.clonePolicy(),
- }
- if (!this.disposed) this.changeSet((snapshots) => snapshots.add(token.nonce))
- return token
- })
- }
-
- absorbSnapshot(
- token: AccountUnreadSnapshotToken,
- sources: readonly AccountUnreadSource[],
- options: {
- truncated?: boolean
- stale?: boolean
- confirmedAccessScopes?: readonly AccountUnreadScope[]
- } = {},
- ) {
- return this.transition(() => {
- if (
- this.disposed
- || token.ownerEpoch !== this.ownerEpoch
- || !this.changeSet((snapshots) => snapshots.delete(token.nonce))
- ) return
- const family = token.family
- const facet = family === "inbox-mentions" ? "attention" : "ordinary"
- if (!options.stale && !options.truncated && options.confirmedAccessScopes) {
- this.confirmAccessScopes(options.confirmedAccessScopes, {
- ordinal: token.startOrdinal,
- ownerEpoch: token.ownerEpoch,
- })
- }
- const positiveChannels = new Map<string, number>()
- const positiveAttentionChannels = new Map<string, number>()
- const positiveAttentionIds = new Set(
- sources.flatMap((source) => source.attentionId ? [source.attentionId] : []),
- )
- for (const source of sources) {
- const evidenceSeq = family === "inbox-mentions"
- ? source.lastMentionSeq ?? source.lastUnreadSeq
- : source.lastUnreadSeq
- if (!source.channelId || !Number.isSafeInteger(evidenceSeq) || evidenceSeq <= 0) continue
- positiveChannels.set(
- source.channelId,
- Math.max(positiveChannels.get(source.channelId) ?? 0, evidenceSeq),
- )
- if (family === "inbox-mentions" || source.isMention) {
- positiveAttentionChannels.set(
- source.channelId,
- Math.max(positiveAttentionChannels.get(source.channelId) ?? 0, evidenceSeq),
- )
- }
- this.recordSnapshotSource(family, source, evidenceSeq, token.startOrdinal)
- }
-
- if (token.policyGeneration !== this.policyGeneration) {
- this.requestPolicyReconcile()
- return
- }
- if (options.stale || options.truncated) return
- if (!token.eligibleCoverage.has(facet)) {
- if (
- !this.policyReady
- && this.snapshotWouldRetire(
- token,
- family,
- facet,
- positiveChannels,
- positiveAttentionChannels,
- )
- ) this.prePolicySnapshotNeedsReconcile = true
- return
- }
-
- if (family === "inbox-mentions") {
- for (const [nonce, dismissal] of this.dismissals) {
- if (
- dismissal.state === "committed"
- && dismissal.ordinal < token.startOrdinal
- && !positiveAttentionIds.has(dismissal.mentionId)
- ) {
- this.changeMap("dismissals", (map) => map.delete(nonce))
- }
- }
- }
- for (const [key, source] of [...this.exact]) {
- const arrival = copyArrival(source)
- const membershipOrdinal = arrival.families.get(family)
- if (
- membershipOrdinal === undefined
- || membershipOrdinal > token.startOrdinal
- || arrivalDomain(family, arrival.serverId) !== token.domain
- || !this.policyAllows(arrival, facet, token.policy)
- ) continue
- const positiveSeq = (
- family === "inbox-mentions" || arrival.isMention
- ? positiveAttentionChannels
- : positiveChannels
- ).get(arrival.channelId)
- if (positiveSeq !== undefined && positiveSeq >= arrival.seq) continue
- arrival.families.delete(family)
- if (arrival.families.size === 0) this.removeExact(key)
- else this.changeMap("exact", (map) => map.set(key, arrival))
- }
- for (const [channelId, source] of [...this.sticky]) {
- const unknown = copySticky(source)
- const membership = unknown.families.get(family)
- const positiveSeq = (
- family === "inbox-mentions" || unknown.isMention
- ? positiveAttentionChannels
- : positiveChannels
- ).get(channelId)
- if (
- !membership
- || membership.ordinal > token.startOrdinal
- || arrivalDomain(family, unknown.serverId) !== token.domain
- || !this.policyAllows(unknown, facet, token.policy)
- || (positiveSeq !== undefined && positiveSeq <= membership.boundary)
- ) continue
- // A complete response whose channel evidence advanced past the
- // sticky's previous boundary has materialized that unsequenced source
- // into the exact record added above. Retire only this family membership;
- // other families still need their own complete coverage.
- unknown.families.delete(family)
- if (unknown.families.size === 0) this.changeMap("sticky", (map) => map.delete(channelId))
- else this.changeMap("sticky", (map) => map.set(channelId, unknown))
- }
- this.settleConfirmedMarkAllFences()
-
- })
- }
-
- cancelSnapshot(token: AccountUnreadSnapshotToken) {
- return this.transition(() => {
- if (!this.validOwnerToken(token)) return
- this.changeSet((snapshots) => snapshots.delete(token.nonce))
- })
- }
-
- absorbFamily(
- family: AccountUnreadFamily,
- sources: readonly AccountUnreadSource[],
- options: {
- truncated?: boolean
- stale?: boolean
- domain?: AccountUnreadDomain
- } = {},
- ) {
- return this.transition(() => {
- if (this.disposed) return
- const token = this.beginSnapshot(
- family,
- options.domain ?? familyDomain(family),
- )
- this.absorbSnapshot(token, sources, options)
- })
- }
-
- mergeSources(
- family: AccountUnreadFamily,
- sources: readonly AccountUnreadSource[],
- domain: AccountUnreadDomain = familyDomain(family),
- ) {
- return this.transition(() => {
- const token = this.beginSnapshot(family, domain)
- this.absorbSnapshot(token, sources, { truncated: true })
- })
- }
-
- projectUnread(
- family: AccountUnreadFamily,
- channelId: string,
- rawUnread: boolean,
- sourceSeq?: number | null,
- domain: AccountUnreadDomain = familyDomain(family),
- exclusion?: AccountUnreadPresentationExclusion | null,
- exactSourceOnly = false,
- attentionId?: string,
- ) {
- if (this.disposed) return false
- const fence = this.markAll.get(domain)
- const read = this.effectiveReadSeq(channelId)
- const facet = family === "inbox-mentions" ? "attention" : "ordinary"
- const policySource = this.sourceScope(channelId, sourceSeq)
- if (!this.scopeAllowed(policySource)) return false
- const rawVisible = rawUnread
- && !(sourceSeq && read >= sourceSeq)
- && !fence
- && this.rawAccessAllowed(family, channelId)
- && !excludesUnread(exclusion, channelId, sourceSeq)
- && this.policyAllows(policySource, facet, this.policy)
- && (facet !== "attention" || !this.attentionIdentityDismissed(
- channelId,
- sourceSeq,
- attentionId,
- ))
- if (rawVisible) return true
- for (const key of this.exactByChannel.get(channelId) ?? []) {
- const arrival = this.exact.get(key)
- if (!arrival || !arrival.families.has(family) || arrival.seq <= read) continue
- if (exactSourceOnly && sourceSeq !== arrival.seq) continue
- if (excludesUnread(exclusion, channelId, arrival.seq)) continue
- const membershipOrdinal = arrival.families.get(family)!
- if (
- (!fence || membershipOrdinal > fence.ordinal)
- && this.policyAllows(arrival, facet, this.policy)
- && (facet !== "attention" || (
- attentionId
- ? !this.attentionIdentityDismissed(channelId, arrival.seq, attentionId)
- : !this.attentionDismissed(arrival)
- ))
- ) return true
- }
- if (exactSourceOnly) return false
- const sticky = this.sticky.get(channelId)
- const pending = sticky?.families.get(family)
- if (pending) {
- if (excludesUnread(exclusion, channelId)) return false
- if (
- (!fence || pending.ordinal > fence.ordinal)
- && this.policyAllows(sticky!, facet, this.policy)
- ) return true
- }
- return false
- }
-
- projectMentionCount(
- family: "servers" | "inbox-mentions",
- channelId: string,
- rawCount: number,
- sourceSeq?: number | null,
- exclusion?: AccountUnreadPresentationExclusion | null,
- ) {
- if (this.disposed) return 0
- const fence = this.markAll.get("mentions")
- const read = this.effectiveReadSeq(channelId)
- const policySource = this.sourceScope(channelId)
- if (!this.scopeAllowed(policySource)) return 0
- let count = !fence
- && !(sourceSeq && read >= sourceSeq)
- && this.rawAccessAllowed(family, channelId)
- && !excludesUnread(exclusion, channelId, sourceSeq)
- && this.policyAllows(policySource, "attention", this.policy)
- ? rawCount
- : 0
- count = Math.max(0, count - this.dismissedAttentionCount(channelId, sourceSeq))
- for (const key of this.exactByChannel.get(channelId) ?? []) {
- const arrival = this.exact.get(key)
- if (
- family === "inbox-mentions"
- && arrival?.isMention
- && arrival.families.has(family)
- && arrival.seq > read
- && !(sourceSeq && sourceSeq >= arrival.seq)
- && !excludesUnread(exclusion, channelId, arrival.seq)
- && (!fence || arrival.families.get(family)! > fence.ordinal)
- && this.policyAllows(arrival, "attention", this.policy)
- && !this.attentionDismissed(arrival)
- ) count += 1
- }
- return count
- }
-
- projectServerUnread(
- serverId: string,
- sources: readonly AccountUnreadSource[],
- rawUnread = false,
- exclusion?: AccountUnreadPresentationExclusion | null,
- ) {
- if (sources.some((source) => (
- this.projectUnread(
- "servers",
- source.channelId,
- true,
- source.lastUnreadSeq,
- "channels",
- exclusion,
- )
- ))) return true
- void rawUnread
- for (const arrival of this.exact.values()) {
- if (
- arrival.serverId === serverId
- && this.projectUnread(
- "servers",
- arrival.channelId,
- false,
- undefined,
- "channels",
- exclusion,
- )
- ) return true
- }
- for (const unknown of this.sticky.values()) {
- if (
- unknown.serverId === serverId
- && this.projectUnread(
- "servers",
- unknown.channelId,
- false,
- undefined,
- "channels",
- exclusion,
- )
- ) return true
- }
- return false
- }
-
- projectServerChannelUnread(
- serverId: string,
- channelId: string,
- sources: readonly AccountUnreadSource[],
- rawUnread = false,
- exclusion?: AccountUnreadPresentationExclusion | null,
- ) {
- const family = `server-detail:${serverId}` as const
- if (sources.some((source) => (
- this.projectUnread(
- family,
- source.channelId,
- true,
- source.lastUnreadSeq,
- "channels",
- exclusion,
- )
- ))) return true
- void rawUnread
- for (const arrival of this.exact.values()) {
- if (
- arrival.serverId === serverId
- && (arrival.channelId === channelId || arrival.railChannelId === channelId)
- && this.projectUnread(
- family,
- arrival.channelId,
- false,
- undefined,
- "channels",
- exclusion,
- )
- ) return true
- }
- for (const unknown of this.sticky.values()) {
- if (
- unknown.serverId === serverId
- && (unknown.channelId === channelId || unknown.railChannelId === channelId)
- && this.projectUnread(
- family,
- unknown.channelId,
- false,
- undefined,
- "channels",
- exclusion,
- )
- ) return true
- }
- return false
- }
-
- projectForumParentUnread(
- serverId: string,
- parentChannelId: string,
- rawBaseUnread: boolean,
- sourceSeq: number | null | undefined,
- renderedChildIds: ReadonlySet<string>,
- exclusion?: AccountUnreadPresentationExclusion | null,
- ) {
- const family = `server-detail:${serverId}` as const
- if (
- this.projectUnread(
- family,
- parentChannelId,
- rawBaseUnread,
- sourceSeq,
- "channels",
- exclusion,
- )
- ) return true
- for (const arrival of this.exact.values()) {
- if (
- arrival.serverId === serverId
- && arrival.railChannelId === parentChannelId
- && !renderedChildIds.has(arrival.channelId)
- && this.projectUnread(
- family,
- arrival.channelId,
- false,
- undefined,
- "channels",
- exclusion,
- )
- ) return true
- }
- for (const unknown of this.sticky.values()) {
- if (
- unknown.serverId === serverId
- && unknown.railChannelId === parentChannelId
- && !renderedChildIds.has(unknown.channelId)
- && this.projectUnread(
- family,
- unknown.channelId,
- false,
- undefined,
- "channels",
- exclusion,
- )
- ) return true
- }
- return false
- }
-
- projectServerMentionCount(
- _serverId: string,
- sources: ReadonlyArray<{ channelId: string; count: number; lastSeq: number }>,
- rawFallback = 0,
- exclusion?: AccountUnreadPresentationExclusion | null,
- ) {
- void rawFallback
- return sources.reduce((sum, source) => sum + this.projectMentionCount(
- "servers",
- source.channelId,
- source.count,
- source.lastSeq,
- exclusion,
- ), 0)
- }
-
- hasPending(...args: Parameters<AccountUnreadProjection["pendingChannels"]>) {
- return !this.pendingChannels(...args).next().done
- }
-
- pendingChannelIds(...args: Parameters<AccountUnreadProjection["pendingChannels"]>) {
- return [...new Set(this.pendingChannels(...args))]
- }
-
- private *pendingChannels(
- family?: AccountUnreadFamily,
- domain?: AccountUnreadDomain,
- exclusion?: AccountUnreadPresentationExclusion | null,
- ) {
- if (this.disposed) return
- for (const arrival of this.exact.values()) {
- if (family && !arrival.families.has(family)) continue
- if (!this.scopeAllowed(arrival)) continue
- if (excludesUnread(exclusion, arrival.channelId, arrival.seq)) continue
- const sourceDomain = family === "inbox-mentions" || arrival.isMention && domain === "mentions"
- ? "mentions"
- : arrival.serverId ? "channels" : "dms"
- if (domain && sourceDomain !== domain) continue
- const fence = this.markAll.get(domain ?? sourceDomain)
- const relevantFamily = family ?? [...arrival.families.keys()].find((candidate) => (
- arrivalDomain(candidate, arrival.serverId) === (domain ?? sourceDomain)
- ))
- if (!relevantFamily) continue
- const facet = relevantFamily === "inbox-mentions" ? "attention" : "ordinary"
- const membershipOrdinal = arrival.families.get(relevantFamily)!
- if (
- (!fence || membershipOrdinal > fence.ordinal)
- && this.policyAllows(arrival, facet, this.policy)
- && (facet !== "attention" || !this.attentionDismissed(arrival))
- ) yield arrival.channelId
- }
- for (const unknown of this.sticky.values()) {
- if (!this.scopeAllowed(unknown)) continue
- if (excludesUnread(exclusion, unknown.channelId)) continue
- for (const [pendingFamily, pending] of unknown.families) {
- if (family && pendingFamily !== family) continue
- const pendingDomain = arrivalDomain(pendingFamily, unknown.serverId)
- if (domain && pendingDomain !== domain) continue
- const fence = this.markAll.get(domain ?? pendingDomain)
- const facet = pendingFamily === "inbox-mentions" ? "attention" : "ordinary"
- if (
- (!fence || pending.ordinal > fence.ordinal)
- && this.policyAllows(unknown, facet, this.policy)
- ) yield unknown.channelId
- }
- }
- }
-
- setNotificationPolicy(snapshot: AccountUnreadPolicySnapshot) {
- return this.transition(() => {
- if (this.disposed) return
- const wasReady = this.policyReady
- const nextBase = freezePolicy(snapshot)
- // Query cache writes mirror optimistic controls for the settings UI. They
- // are not authoritative policy while the matching overlay is unresolved,
- // otherwise a failed request could hydrate its own optimistic value into
- // the base and make rollback ineffective.
- for (const overlay of this.policyOverlays.values()) {
- if (overlay.patch.kind === "server") {
- const prior = this.policyBase.server.get(overlay.patch.id)
- if (prior === undefined) nextBase.server.delete(overlay.patch.id)
- else nextBase.server.set(overlay.patch.id, prior)
- } else {
- const prior = this.policyBase.channel.get(overlay.patch.id)
- if (prior === undefined) nextBase.channel.delete(overlay.patch.id)
- else nextBase.channel.set(overlay.patch.id, prior)
- }
- }
- this.policyBase = nextBase
- const changed = this.refreshPolicy(true)
- if (
- changed
- && (wasReady || this.prePolicySnapshotNeedsReconcile)
- ) this.requestPolicyReconcile()
- this.prePolicySnapshotNeedsReconcile = false
- })
- }
-
- beginNotificationPolicyOverlay(
- patch: AccountUnreadPolicyPatch,
- ): AccountUnreadPolicyToken {
- return this.transition(() => {
- const token = { nonce: Symbol(patch.id), ownerEpoch: this.ownerEpoch }
- if (this.disposed) return token
- this.changeMap("policyOverlays", (map) => map.set(token.nonce, { patch: { ...patch }, state: "pending" }))
- this.refreshPolicy(false)
- return token
- })
- }
-
- commitNotificationPolicyOverlay(token: AccountUnreadPolicyToken) {
- return this.transition(() => {
- if (!this.validOwnerToken(token)) return
- const overlay = this.policyOverlays.get(token.nonce)
- if (!overlay) return
- this.changeMap("policyOverlays", (map) => map.set(token.nonce, { ...overlay, state: "committed" }))
- this.flushCommittedPolicyOverlays()
- this.refreshPolicy(false)
- this.requestPolicyReconcile()
- })
- }
-
- rollbackNotificationPolicyOverlay(token: AccountUnreadPolicyToken) {
- return this.transition(() => {
- if (!this.validOwnerToken(token) || !this.changeMap("policyOverlays", (map) => map.delete(token.nonce))) return
- this.flushCommittedPolicyOverlays()
- this.refreshPolicy(false)
- })
- }
-
- getPolicyGeneration() {
- return this.policyGeneration
- }
-
- beginDismissMention(input: {
- mentionId: string
- channelId: string
- seq?: number
- countsServerMention?: boolean
- }): AccountUnreadDismissToken {
- return this.transition(() => {
- const token: AccountUnreadDismissToken = {
- ...input,
- countsServerMention: input.countsServerMention ?? true,
- ordinal: this.disposed ? this.ordinal : ++this.ordinal,
- nonce: Symbol(input.mentionId),
- ownerEpoch: this.ownerEpoch,
- }
- if (!this.disposed) {
- this.changeMap("dismissals", (map) => map.set(token.nonce, { ...token, state: "pending" }))
-
- }
- return token
- })
- }
-
- commitDismissMention(token: AccountUnreadDismissToken, _revision?: number) {
- return this.transition(() => {
- if (!this.validOwnerToken(token)) return
- // The optimistic facet fence remains until the next complete Mentions
- // snapshot supplies matching negative evidence. A revision hint alone is
- // deliberately insufficient to settle a destructive transaction.
- const dismissal = this.dismissals.get(token.nonce)
- if (!dismissal) return
- this.changeMap("dismissals", (map) => map.set(token.nonce, { ...dismissal, state: "committed" }))
-
- })
- }
-
- rollbackDismissMention(token: AccountUnreadDismissToken) {
- return this.transition(() => {
- if (!this.validOwnerToken(token) || !this.changeMap("dismissals", (map) => map.delete(token.nonce))) return
-
- })
- }
-
- beginScopeRetirement(scope: AccountUnreadScope): AccountUnreadScopeToken {
- return this.transition(() => {
- const token: AccountUnreadScopeToken = {
- scope: { ...scope },
- ordinal: this.ordinal,
- nonce: Symbol(scope.kind),
- ownerEpoch: this.ownerEpoch,
- }
- if (!this.disposed) {
- this.changeMap("accessFences", (map) => map.set(scopeKey(scope), { ...token, state: "pending" }))
-
- }
- return token
- })
- }
-
- commitScopeRetirement(token: AccountUnreadScopeToken, _revision?: number) {
- return this.transition(() => {
- if (!this.validOwnerToken(token)) return
- const current = this.accessFences.get(scopeKey(token.scope))
- if (current?.nonce !== token.nonce) return
- this.changeMap("accessFences", (map) => map.set(scopeKey(token.scope), { ...current, state: "committed" }))
- this.recordRawRetirementFloor(token.scope, this.ordinal)
- this.pruneScope(token.scope, this.ordinal)
-
- })
- }
-
- rollbackScopeRetirement(token: AccountUnreadScopeToken) {
- return this.transition(() => {
- if (!this.validOwnerToken(token)) return
- const key = scopeKey(token.scope)
- if (this.accessFences.get(key)?.nonce !== token.nonce) return
- this.changeMap("accessFences", (map) => map.delete(key))
-
- })
- }
-
- retireNotificationScope(scope: AccountUnreadScope) {
- return this.transition(() => {
- if (this.disposed) return
- const ordinal = ++this.ordinal
- this.recordRawRetirementFloor(scope, ordinal)
- this.pruneScope(scope, ordinal)
-
- this.requestReconcile()
- })
- }
-
- retireAccessScope(scope: AccountUnreadScope) {
- return this.transition(() => {
- if (this.disposed) return
- const token = this.beginScopeRetirement(scope)
- this.commitScopeRetirement(token)
- })
- }
-
- grantAccessScope(scope: AccountUnreadScope) {
- return this.transition(() => {
- if (this.disposed) return
- const fence = this.accessFences.get(scopeKey(scope))
- if (!fence) return
- this.changeMap("accessFences", (map) => map.set(scopeKey(scope), { ...fence, state: "grant-pending" }))
- // A grant only permits fresh authoritative evidence to seed the scope; it
- // does not expose raw cache retained from before the retirement.
- this.requestReconcile()
- })
- }
-
- beginAccessConfirmation(): AccountUnreadAccessConfirmationToken {
- return this.transition(() => {
- return {
- ordinal: this.disposed ? this.ordinal : ++this.ordinal,
- ownerEpoch: this.ownerEpoch,
- }
- })
- }
-
- confirmAccessScopes(
- scopes: readonly AccountUnreadScope[],
- token: AccountUnreadAccessConfirmationToken,
- ) {
- return this.transition(() => {
- if (!this.validOwnerToken(token)) return
- for (const scope of scopes) {
- const key = scopeKey(scope)
- const fence = this.accessFences.get(key)
- if (
- !fence
- || fence.state === "pending"
- || fence.ordinal >= token.ordinal
- ) continue
- this.changeMap("accessFences", (map) => map.delete(key))
- }
-
- })
- }
-
- dispose() {
- return this.transition(() => {
- if (this.disposed) return
- this.disposed = true
- this.ownerEpoch += 1
- this.changeMap("exact", (map) => map.clear())
- this.changeMap("exactByChannel", (map) => map.clear())
- this.changeMap("sticky", (map) => map.clear())
- this.changeMap("evidence", (map) => map.clear())
- this.changeMap("readSeq", (map) => map.clear())
- this.changeMap("optimisticReads", (map) => map.clear())
- this.changeMap("markAll", (map) => map.clear())
- this.changeMap("scopeHints", (map) => map.clear())
- this.changeMap("rawRetirementFloors", (map) => map.clear())
- this.changeMap("accessFences", (map) => map.clear())
- this.changeMap("dismissals", (map) => map.clear())
- this.changeSet((snapshots) => snapshots.clear())
- this.changeMap("policyOverlays", (map) => map.clear())
- this.reconcile = null
- this.reconcileScheduled = false
- this.reconcilePendingDelivery = false
- })
- }
-
- inspectForTests() {
- return {
- sourceCount: this.exact.size + this.sticky.size,
- exactCount: this.exact.size,
- stickyCount: this.sticky.size,
- readState: [...this.readSeq.entries()].sort(),
- policyGeneration: this.policyGeneration,
- policyReady: this.policyReady,
- highestRevision: this.highestRevision,
- pendingSnapshots: this.snapshots.size,
- disposed: this.disposed,
- }
- }
-
- beginMarkAll(domain: AccountUnreadDomain): MarkAllToken {
- return this.transition(() => {
- if (this.disposed) {
- return { domain, ordinal: this.ordinal, nonce: Symbol(domain) }
- }
- const token: MarkAllToken = { domain, ordinal: this.ordinal, nonce: Symbol(domain) }
- this.changeMap("markAll", (map) => map.set(domain, { ...token, state: "pending", revision: null }))
-
- return token
- })
- }
-
- commitMarkAll(token: MarkAllToken, revision: number) {
- return this.transition(() => {
- if (this.disposed) return
- const fence = this.markAll.get(token.domain)
- if (!fence || fence.nonce !== token.nonce) return
- this.changeMap("markAll", (map) => map.set(token.domain, { ...fence, state: "committed", revision }))
-
- })
- }
-
- rollbackMarkAll(token: MarkAllToken) {
- return this.transition(() => {
- if (this.disposed) return
- const fence = this.markAll.get(token.domain)
- if (!fence || fence.nonce !== token.nonce) return
- this.changeMap("markAll", (map) => map.delete(token.domain))
-
- })
- }
-
- private recordSnapshotSource(
- family: AccountUnreadFamily,
- source: AccountUnreadSource,
- evidenceSeq: number,
- observedOrdinal: number,
- ) {
- const evidenceKey = this.evidenceKey(family, source.channelId)
- this.changeMap("evidence", (map) => map.set(evidenceKey, Math.max(this.evidence.get(evidenceKey) ?? 0, evidenceSeq)))
- const knownSource = this.findSourceScope(source.channelId)
- const knownScope = knownSource ?? this.scopeHints.get(source.channelId)
- const sourceArrival = {
- channelId: source.channelId,
- serverId: source.serverId ?? knownScope?.serverId,
- railChannelId: source.railChannelId ?? knownScope?.railChannelId,
- messageId: source.messageId,
- attentionId: source.attentionId,
- seq: evidenceSeq,
- isMention: source.isMention === true || family === "inbox-mentions",
- }
- const observedFamilies: AccountUnreadFamily[] = family === "inbox-mentions"
- ? sourceArrival.serverId
- ? familiesFor(sourceArrival)
- : knownSource?.families.has("dms")
- ? ["inbox-unreads", "inbox-mentions", "dms"]
- : ["inbox-unreads", "inbox-mentions"]
- : [family]
- for (const key of this.exactByChannel.get(source.channelId) ?? []) {
- const previous = this.exact.get(key)
- if (!previous || previous.seq !== evidenceSeq) continue
- const existing = copyArrival(previous)
- for (const observedFamily of observedFamilies) {
- existing.families.set(
- observedFamily,
- Math.max(existing.families.get(observedFamily) ?? -1, observedOrdinal),
- )
- }
- if (sourceArrival.isMention && !existing.isMention) {
- existing.isMention = true
- }
- if (source.attentionId) existing.attentionIds.add(source.attentionId)
- if (!existing.serverId && source.serverId) {
- existing.serverId = source.serverId
- }
- if (!existing.railChannelId && source.railChannelId) {
- existing.railChannelId = source.railChannelId
- }
- this.changeMap("exact", (map) => map.set(key, existing))
- return
- }
- this.recordArrivalForFamilies(sourceArrival, observedFamilies, observedOrdinal)
- }
-
- private clonePolicy(): FrozenPolicy {
- return {
- all: this.policy.all,
- server: new Map(this.policy.server),
- channel: new Map(this.policy.channel),
- parentByChannel: new Map(this.policy.parentByChannel),
- }
- }
-
- private applyPolicyPatch(policy: MutablePolicy, patch: AccountUnreadPolicyPatch) {
- if (patch.kind === "server") {
- policy.server.set(patch.id, normalizePolicyLevel(patch.level))
- return
- }
- if (patch.level === null) policy.channel.delete(patch.id)
- else policy.channel.set(patch.id, normalizePolicyLevel(patch.level))
- }
-
- private flushCommittedPolicyOverlays() {
- const nextBase: MutablePolicy = { ...this.policyBase, server: new Map(this.policyBase.server), channel: new Map(this.policyBase.channel), parentByChannel: new Map(this.policyBase.parentByChannel) }
- let changed = false
- for (const [nonce, overlay] of this.policyOverlays) {
- if (overlay.state !== "committed") break
- this.applyPolicyPatch(nextBase, overlay.patch)
- this.changeMap("policyOverlays", (map) => map.delete(nonce))
- changed = true
- }
- if (changed) this.policyBase = nextBase
- }
-
- private refreshPolicy(markReady: boolean) {
- const next: MutablePolicy = {
- all: this.policyBase.all,
- server: new Map(this.policyBase.server),
- channel: new Map(this.policyBase.channel),
- parentByChannel: new Map(this.policyBase.parentByChannel),
- }
- for (const overlay of this.policyOverlays.values()) {
- this.applyPolicyPatch(next, overlay.patch)
- }
- const becameReady = markReady && !this.policyReady
- if (!becameReady && policySignature(next) === policySignature(this.policy)) return false
- this.policy = next
- if (markReady) this.policyReady = true
- this.policyGeneration += 1
-
- return true
- }
-
- private policyLevelFor(
- source: Pick<PendingArrival, "channelId" | "serverId" | "railChannelId">,
- policy: FrozenPolicy,
- ) {
- const exact = policy.channel.get(source.channelId)
- if (exact) return exact
- const parentId = source.railChannelId ?? policy.parentByChannel.get(source.channelId)
- if (parentId) {
- const parent = policy.channel.get(parentId)
- if (parent) return parent
- }
- if (source.serverId) return policy.server.get(source.serverId) ?? policy.all
- return policy.all
- }
-
- private policyAllows(
- source: Pick<PendingArrival, "channelId" | "serverId" | "railChannelId" | "isMention">,
- facet: AccountUnreadFacet,
- policy: FrozenPolicy,
- ) {
- const level = this.policyLevelFor(source, policy)
- if (level === "nothing") return false
- if (facet === "attention") return true
- return level === "all" || source.isMention
- }
-
- private sourceScope(channelId: string, sourceSeq?: number | null): Pick<
- PendingArrival,
- "channelId" | "serverId" | "railChannelId" | "isMention"
- > {
- if (sourceSeq !== undefined && sourceSeq !== null) {
- for (const key of this.exactByChannel.get(channelId) ?? []) {
- const source = this.exact.get(key)
- if (source?.seq === sourceSeq) return source
- }
- }
- return this.findSourceScope(channelId) ?? {
- ...this.scopeHints.get(channelId),
- channelId,
- isMention: false,
- }
- }
-
- private findSourceScope(channelId: string): PendingArrival | StickyUnknown | undefined {
- for (const key of this.exactByChannel.get(channelId) ?? []) {
- const source = this.exact.get(key)
- if (source) return source
- }
- return this.sticky.get(channelId)
- }
-
- private attentionDismissed(
- source: Pick<
- PendingArrival,
- "channelId" | "seq" | "ordinal" | "isMention" | "attentionIds"
- >,
- ) {
- if (!source.isMention) return false
- if (source.attentionIds.size > 0) {
- return [...source.attentionIds].every((attentionId) => (
- this.attentionIdentityDismissed(source.channelId, source.seq, attentionId)
- ))
- }
- for (const dismissal of this.dismissals.values()) {
- if (dismissal.channelId !== source.channelId) continue
- if (dismissal.seq !== undefined && dismissal.seq !== source.seq) continue
- if (source.ordinal <= dismissal.ordinal) return true
- }
- return false
- }
-
- private attentionIdentityDismissed(
- channelId: string,
- seq?: number | null,
- attentionId?: string,
- ) {
- for (const dismissal of this.dismissals.values()) {
- if (dismissal.channelId !== channelId) continue
- if (attentionId) {
- if (dismissal.mentionId === attentionId) return true
- continue
- }
- if (
- seq !== undefined
- && seq !== null
- && dismissal.seq !== undefined
- && dismissal.seq === seq
- ) return true
- }
- return false
- }
-
- private dismissedAttentionCount(channelId: string, sourceSeq?: number | null) {
- const identities = new Set<string>()
- for (const dismissal of this.dismissals.values()) {
- if (dismissal.channelId !== channelId) continue
- if (!dismissal.countsServerMention) continue
- if (
- sourceSeq !== undefined
- && sourceSeq !== null
- && dismissal.seq !== undefined
- && dismissal.seq > sourceSeq
- ) continue
- identities.add(dismissal.mentionId)
- }
- return identities.size
- }
-
- private validOwnerToken(token: { ownerEpoch: number }) {
- return !this.disposed && token.ownerEpoch === this.ownerEpoch
- }
-
- private scopeAllowed(source: { channelId: string; serverId?: string }) {
- if (this.accessFences.has(`channel:${source.channelId}`)) return false
- return !source.serverId || !this.accessFences.has(`server:${source.serverId}`)
- }
-
- private scopeAllowsArrival(
- source: { channelId: string; serverId?: string },
- observedOrdinal?: number,
- ) {
- const allowsFence = (
- fence: (AccountUnreadScopeToken & {
- state: "pending" | "committed" | "grant-pending"
- }) | undefined,
- ) => {
- if (!fence || fence.state === "pending") return true
- if (fence.state === "committed") return false
- return observedOrdinal === undefined || observedOrdinal > fence.ordinal
- }
- return allowsFence(this.accessFences.get(`channel:${source.channelId}`))
- && (!source.serverId || allowsFence(this.accessFences.get(`server:${source.serverId}`)))
- }
-
- private scopeAllowsLegacySnapshot(source: { channelId: string; serverId?: string }) {
- const allowsFence = (
- fence: (AccountUnreadScopeToken & {
- state: "pending" | "committed" | "grant-pending"
- }) | undefined,
- ) => !fence || fence.state === "pending"
- return allowsFence(this.accessFences.get(`channel:${source.channelId}`))
- && (!source.serverId || allowsFence(this.accessFences.get(`server:${source.serverId}`)))
- }
-
- private rememberScope(source: AccountUnreadScopeHint) {
- const previous = this.scopeHints.get(source.channelId)
- const next = {
- channelId: source.channelId,
- serverId: source.serverId ?? previous?.serverId,
- railChannelId: source.railChannelId ?? previous?.railChannelId,
- }
- this.changeMap("scopeHints", (map) => map.set(source.channelId, next))
- if (!next.serverId) return
- const serverFence = this.accessFences.get(`server:${next.serverId}`)
- if (!serverFence || serverFence.state === "pending") return
- this.changeMap("rawRetirementFloors", (map) => map.set(source.channelId, Math.max(this.rawRetirementFloors.get(source.channelId) ?? -1, serverFence.ordinal)))
- }
-
- private recordRawRetirementFloor(scope: AccountUnreadScope, ordinal: number) {
- if (scope.kind === "channel") {
- this.changeMap("rawRetirementFloors", (map) => map.set(scope.channelId, ordinal))
- return
- }
- for (const [channelId, hint] of this.scopeHints) {
- if (hint.serverId === scope.serverId) {
- this.changeMap("rawRetirementFloors", (map) => map.set(channelId, ordinal))
- }
- }
- }
-
- private rawAccessAllowed(family: AccountUnreadFamily, channelId: string) {
- const floor = this.rawRetirementFloors.get(channelId)
- if (floor === undefined) return true
- for (const key of this.exactByChannel.get(channelId) ?? []) {
- const membership = this.exact.get(key)?.families.get(family)
- if (membership !== undefined && membership > floor) return true
- }
- return (this.sticky.get(channelId)?.families.get(family)?.ordinal ?? -1) > floor
- }
-
- private pruneScope(scope: AccountUnreadScope, throughOrdinal: number) {
- const matches = (source: { channelId: string; serverId?: string }) => (
- scope.kind === "server"
- ? source.serverId === scope.serverId
- : source.channelId === scope.channelId
- )
- for (const [key, previous] of [...this.exact]) {
- if (!matches(previous)) continue
- const source = copyArrival(previous)
- for (const [family, membershipOrdinal] of [...source.families]) {
- if (membershipOrdinal <= throughOrdinal) source.families.delete(family)
- }
- if (source.families.size === 0) this.removeExact(key)
- else this.changeMap("exact", (map) => map.set(key, source))
- }
- for (const [channelId, previous] of [...this.sticky]) {
- if (!matches(previous)) continue
- const source = copySticky(previous)
- for (const [family, membership] of [...source.families]) {
- if (membership.ordinal <= throughOrdinal) source.families.delete(family)
- }
- if (source.families.size === 0) this.changeMap("sticky", (map) => map.delete(channelId))
- else this.changeMap("sticky", (map) => map.set(channelId, source))
- }
- }
-
- private hasCapturedDomainSource(domain: AccountUnreadDomain, throughOrdinal: number) {
- for (const source of this.exact.values()) {
- for (const [family, membershipOrdinal] of source.families) {
- if (
- membershipOrdinal <= throughOrdinal
- && arrivalDomain(family, source.serverId) === domain
- ) return true
- }
- }
- for (const source of this.sticky.values()) {
- for (const [family, membership] of source.families) {
- if (
- membership.ordinal <= throughOrdinal
- && arrivalDomain(family, source.serverId) === domain
- ) return true
- }
- }
- return false
- }
-
- private settleConfirmedMarkAllFences() {
- let changed = false
- for (const [domain, fence] of [...this.markAll]) {
- if (
- fence.state === "committed"
- && fence.revision !== null
- && fence.revision <= this.highestRevision
- && !this.hasCapturedDomainSource(domain, fence.ordinal)
- ) {
- this.changeMap("markAll", (map) => map.delete(domain))
- changed = true
- }
- }
- return changed
- }
-
- private snapshotWouldRetire(
- token: AccountUnreadSnapshotToken,
- family: AccountUnreadFamily,
- facet: AccountUnreadFacet,
- positiveChannels: ReadonlyMap<string, number>,
- positiveAttentionChannels: ReadonlyMap<string, number>,
- ) {
- for (const arrival of this.exact.values()) {
- const membershipOrdinal = arrival.families.get(family)
- if (
- membershipOrdinal !== undefined
- && membershipOrdinal <= token.startOrdinal
- && arrivalDomain(family, arrival.serverId) === token.domain
- && this.policyAllows(arrival, facet, token.policy)
- && ((family === "inbox-mentions" || arrival.isMention
- ? positiveAttentionChannels
- : positiveChannels
- ).get(arrival.channelId) ?? -1) < arrival.seq
- ) return true
- }
- for (const [channelId, source] of this.sticky) {
- const membership = source.families.get(family)
- if (
- membership
- && membership.ordinal <= token.startOrdinal
- && arrivalDomain(family, source.serverId) === token.domain
- && this.policyAllows(source, facet, token.policy)
- && !(family === "inbox-mentions" || source.isMention
- ? positiveAttentionChannels
- : positiveChannels
- ).has(channelId)
- ) return true
- }
- return false
- }
-
- private requestPolicyReconcile() {
- if (this.lastPolicyReconcileGeneration === this.policyGeneration) return
- this.lastPolicyReconcileGeneration = this.policyGeneration
- this.requestReconcile()
- }
-
- private requestReconcile() {
- if (this.disposed || this.reconcileScheduled) return
- this.reconcileScheduled = true
- if (this.reconcile) this.reconcile()
- else this.reconcilePendingDelivery = true
- }
-
- private recordSticky(
- channelId: string,
- families: AccountUnreadFamily[],
- isMention: boolean,
- serverId?: string,
- railChannelId?: string,
- observedOrdinal?: number,
- messageId?: string | null,
- attentionId?: string,
- attentionIds: ReadonlySet<string> = new Set(),
- ) {
- if (this.disposed || !channelId) return
- this.rememberScope({ channelId, serverId, railChannelId })
- if (!this.scopeAllowsArrival({ channelId, serverId })) return
- const arrivalOrdinal = observedOrdinal ?? ++this.ordinal
- const previous = this.sticky.get(channelId)
- let unknown = previous ? copySticky(previous) : undefined
- if (!unknown) {
- if (this.sticky.size >= MAX_STICKY_SCOPES) {
- const oldest = [...this.sticky.entries()].reduce<
- [string, StickyUnknown] | null
- >((candidate, entry) => {
- if (!candidate) return entry
- const oldestOrdinal = Math.min(...[...candidate[1].families.values()].map((v) => v.ordinal))
- const entryOrdinal = Math.min(...[...entry[1].families.values()].map((v) => v.ordinal))
- return entryOrdinal < oldestOrdinal ? entry : candidate
- }, null)
- if (oldest) this.changeMap("sticky", (map) => map.delete(oldest[0]))
- this.requestReconcile()
- }
- unknown = {
- channelId,
- serverId,
- railChannelId,
- messageId,
- isMention,
- attentionIds: new Set([
- ...attentionIds,
- ...(attentionId ? [attentionId] : []),
- ]),
- families: new Map(),
- }
- } else if (unknown.messageId === undefined && messageId !== undefined) {
- unknown.messageId = messageId
- } else if (
- unknown.messageId !== null
- && messageId !== undefined
- && unknown.messageId !== messageId
- ) {
- // A channel-scoped sticky may summarize more than one unsequenced
- // arrival. Once identities disagree it is no longer safe to correlate
- // the aggregate with a later exact message.
- unknown.messageId = null
- }
- unknown.isMention ||= isMention
- if (attentionId) unknown.attentionIds.add(attentionId)
- for (const id of attentionIds) unknown.attentionIds.add(id)
- unknown.serverId ??= serverId
- unknown.railChannelId ??= railChannelId
- for (const family of families) {
- const pending = unknown.families.get(family)
- if (pending) {
- pending.ordinal = arrivalOrdinal
- } else {
- unknown.families.set(
- family,
- {
- boundary: this.evidence.get(this.evidenceKey(family, channelId)) ?? 0,
- ordinal: arrivalOrdinal,
- },
- )
- }
- }
- this.changeMap("sticky", (map) => map.set(channelId, unknown!))
- }
-
- private evidenceKey(family: AccountUnreadFamily, channelId: string) {
- return `${family}\u0000${channelId}`
- }
-
- private effectiveReadSeq(channelId: string) {
- let seq = this.readSeq.get(channelId) ?? 0
- for (const optimistic of this.optimisticReads.values()) {
- if (optimistic.channelId === channelId) seq = Math.max(seq, optimistic.seq)
- }
- return seq
- }
-
- private removeExact(key: string) {
- const arrival = this.exact.get(key)!
- this.changeMap("exact", (map) => map.delete(key))
- const channelKeys = new Set(this.exactByChannel.get(arrival.channelId))
- channelKeys.delete(key)
- this.changeMap("exactByChannel", (map) => channelKeys.size === 0 ? map.delete(arrival.channelId) : map.set(arrival.channelId, channelKeys))
- }
-
-
-}
-
-export function getAccountUnreadProjection(
- queryClient: QueryClient,
- ownerUserId: string,
-) {
- if (ownerUserId !== "__anonymous__") activeOwners.set(queryClient, ownerUserId)
- let byUser = owners.get(queryClient)
- if (!byUser) {
- byUser = new Map()
- owners.set(queryClient, byUser)
- }
- let projection = byUser.get(ownerUserId)
- if (!projection) {
- projection = new AccountUnreadProjection(ownerUserId)
- byUser.set(ownerUserId, projection)
- }
- return projection
-}
-
-export function getActiveAccountUnreadProjection(queryClient: QueryClient) {
- return getAccountUnreadProjection(
- queryClient,
- activeOwners.get(queryClient) ?? "__anonymous__",
- )
-}
-
-export function disposeAccountUnreadProjection(
- queryClient: QueryClient,
- ownerUserId?: string,
-) {
- const byUser = owners.get(queryClient)
- if (!byUser) return
- if (ownerUserId) {
- byUser.get(ownerUserId)?.dispose()
- byUser.delete(ownerUserId)
- } else {
- for (const projection of byUser.values()) projection.dispose()
- byUser.clear()
- }
- if (!ownerUserId || activeOwners.get(queryClient) === ownerUserId) {
- activeOwners.delete(queryClient)
- }
- if (byUser.size === 0) owners.delete(queryClient)
-}
-
-export function acceptAccountUnreadPrimarySnapshot(
- queryClient: QueryClient,
- snapshot: AccountUnreadPrimarySnapshot,
-) {
- const ownerUserId = activeOwners.get(queryClient)
- if (!ownerUserId) return
- owners.get(queryClient)?.get(ownerUserId)?.acceptPrimarySnapshot(snapshot)
-}
diff --git a/src/web/src/hooks/community/community-ws/bundle-events.dom.test.ts b/src/web/src/hooks/community/community-ws/bundle-events.dom.test.ts
index 7054a8d72..df2d3edb0 100644
--- a/src/web/src/hooks/community/community-ws/bundle-events.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/bundle-events.dom.test.ts
@@ -48,7 +48,6 @@ import {
releaseReadSurface,
submitReadIntent,
} from "@/hooks/community/read-coordinator"
-import { getActiveAccountUnreadProjection } from "@/hooks/community/account-unread-projection"
beforeEach(async () => {
reconcileCommunityWsReconnect.mockClear()
@@ -189,216 +188,6 @@ describe("useCommunityWs — operation bundles", () => {
expect(hasCanonicalChannelNotify("post_1", "u_me")).toBe(true)
})
- it("merges multiple requests into one queued successor generation", async () => {
- vi.useFakeTimers()
- try {
- getCapturedRuntime().ui.actions.subscribe({ channelId: "ch-1" })
- await mountHook({ viewerUserId: "viewer-1" })
- let releaseRead!: () => void
- const readGate = new Promise<void>((resolve) => {
- releaseRead = resolve
- })
- getCommunityApiFetchMock().mockImplementation(async (url: unknown) => {
- if (typeof url === "string" && url.endsWith("/read")) {
- await readGate
- return { changed: true, revision: 1, targetSeq: 1 }
- }
- if (url === "/api/community/users/me/read-state") {
- return {
- revision: 1,
- readStates: [{
- channelId: "ch-1",
- lastReadMessageId: "message-1",
- lastReadAt: "2026-08-27T00:00:00.000Z",
- lastReadSeq: 1,
- }],
- }
- }
- throw new Error(`unexpected API fetch: ${String(url)}`)
- })
- vi.spyOn(capturedQueryClient, "invalidateQueries")
- const lease = registerReadSurface(
- capturedQueryClient,
- "viewer-1",
- { kind: "timeline", channelId: "ch-1" },
- )
-
- capturedOnMessage!({
- type: "community:mention.create",
- userId: "viewer-1",
- messageId: "mention-current",
- channelId: "ch-1",
- authorName: "Alice",
- })
- expect(submitReadIntent(lease, {
- kind: "timeline",
- channelId: "ch-1",
- messageId: "message-1",
- seq: 1,
- })).toBe(true)
- await vi.advanceTimersByTimeAsync(500)
- await vi.waitFor(() => expect(getCommunityApiFetchMock()).toHaveBeenCalledWith(
- "/api/community/channels/ch-1/read",
- expect.anything(),
- ))
-
- capturedOnMessage!({
- type: "community:mention.create",
- userId: "viewer-1",
- messageId: "mention-next",
- channelId: "ch-1",
- authorName: "Alice",
- })
- capturedOnMessage!({
- ...message,
- message: { ...message.message, id: "message-next", seq: 2 },
- })
- capturedOnMessage!({ type: "community:unread.bump", userId: "viewer-1", channelId: "dm-1" })
- releaseRead()
- await vi.advanceTimersByTimeAsync(500)
-
- expect(invalidationCount(communityKeys.inbox())).toBe(1)
- expect(invalidationCount(communityKeys.dms())).toBe(1)
- releaseReadSurface(lease)
- } finally {
- vi.useRealTimers()
- }
- })
-
- it("carries a deferred wide generation into its narrower successor", async () => {
- vi.useFakeTimers()
- try {
- getCapturedRuntime().ui.actions.subscribe({ channelId: "ch-1" })
- await mountHook({ viewerUserId: "viewer-1" })
- let releaseRead!: () => void
- const readGate = new Promise<void>((resolve) => {
- releaseRead = resolve
- })
- getCommunityApiFetchMock().mockImplementation(async (url: unknown) => {
- if (typeof url === "string" && url.endsWith("/read")) {
- await readGate
- return { changed: true, revision: 1, targetSeq: 1 }
- }
- if (url === "/api/community/users/me/read-state") {
- return {
- revision: 1,
- readStates: [{
- channelId: "ch-1",
- lastReadMessageId: "message-1",
- lastReadAt: "2026-08-27T00:00:00.000Z",
- lastReadSeq: 1,
- }],
- }
- }
- throw new Error(`unexpected API fetch: ${String(url)}`)
- })
- vi.spyOn(capturedQueryClient, "invalidateQueries")
- const lease = registerReadSurface(
- capturedQueryClient,
- "viewer-1",
- { kind: "timeline", channelId: "ch-1" },
- )
-
- capturedOnMessage!(message)
- capturedOnMessage!({ type: "community:unread.bump", userId: "viewer-1", channelId: "dm-1" })
- expect(submitReadIntent(lease, {
- kind: "timeline",
- channelId: "ch-1",
- messageId: "message-1",
- seq: 1,
- })).toBe(true)
- await vi.advanceTimersByTimeAsync(500)
- await vi.waitFor(() => expect(getCommunityApiFetchMock()).toHaveBeenCalledWith(
- "/api/community/channels/ch-1/read",
- expect.anything(),
- ))
-
- capturedOnMessage!({
- type: "community:mention.create",
- userId: "viewer-1",
- messageId: "mention-2",
- channelId: "ch-1",
- authorName: "Alice",
- })
- releaseRead()
- await vi.advanceTimersByTimeAsync(500)
-
- expect(invalidationCount(communityKeys.inbox())).toBe(1)
- expect(invalidationCount(communityKeys.dms())).toBe(1)
- releaseReadSurface(lease)
- } finally {
- vi.useRealTimers()
- }
- })
-
- it("preserves attention reconciliation across deferred read intents", async () => {
- vi.useFakeTimers()
- try {
- getCapturedRuntime().ui.actions.subscribe({ channelId: "ch-1" })
- await mountHook({ viewerUserId: "viewer-1" })
- let releaseFirstRead!: () => void
- const firstReadGate = new Promise<void>((resolve) => {
- releaseFirstRead = resolve
- })
- let readCalls = 0
- getCommunityApiFetchMock().mockImplementation(async (url: unknown) => {
- if (typeof url === "string" && url.endsWith("/read")) {
- readCalls += 1
- if (readCalls === 1) await firstReadGate
- return { changed: true, revision: readCalls, targetSeq: readCalls }
- }
- if (url === "/api/community/users/me/read-state") {
- return {
- revision: readCalls,
- readStates: [{
- channelId: "ch-1",
- lastReadMessageId: `message-${readCalls}`,
- lastReadAt: "2026-08-27T00:00:00.000Z",
- lastReadSeq: readCalls,
- }],
- }
- }
- throw new Error(`unexpected API fetch: ${String(url)}`)
- })
- vi.spyOn(capturedQueryClient, "invalidateQueries")
- vi.spyOn(capturedQueryClient, "query")
- const lease = registerReadSurface(
- capturedQueryClient,
- "viewer-1",
- { kind: "timeline", channelId: "ch-1" },
- )
-
- capturedOnMessage!(message)
- capturedOnMessage!({ type: "community:unread.bump", userId: "viewer-1", channelId: "dm-1" })
- expect(submitReadIntent(lease, {
- kind: "timeline",
- channelId: "ch-1",
- messageId: "message-1",
- seq: 1,
- })).toBe(true)
- await vi.advanceTimersByTimeAsync(500)
- await vi.waitFor(() => expect(readCalls).toBe(1))
-
- expect(submitReadIntent(lease, {
- kind: "timeline",
- channelId: "ch-1",
- messageId: "message-2",
- seq: 2,
- })).toBe(true)
- releaseFirstRead()
- await vi.advanceTimersByTimeAsync(499)
- expect(readCalls).toBe(1)
- expect(attentionReconcileCount()).toBe(2)
-
- await vi.advanceTimersByTimeAsync(1)
- await vi.waitFor(() => expect(readCalls).toBe(2))
- expect(attentionReconcileCount()).toBe(3)
- releaseReadSurface(lease)
- } finally {
- vi.useRealTimers()
- }
- })
-
it("decodes all children before one dispatch, deduplicates invalidations, and suppresses same-digest replay", async () => {
vi.useFakeTimers()
try {
@@ -414,14 +203,8 @@ describe("useCommunityWs — operation bundles", () => {
expect(capturedQueryClient.getQueryData<{ servers: Array<{ id: string; mentions: number }> }>(
communityKeys.servers(),
)?.servers[0]?.mentions).toBe(5)
- const unreadProjection = getActiveAccountUnreadProjection(capturedQueryClient)
- expect(unreadProjection.projectUnread("servers", "ch-1", false)).toBe(true)
- // A correlated bundle carries seq=1 dispatch-locally, so a real visible
- // read can cover it. An orphan/sticky bump would deliberately survive.
- unreadProjection.recordRead("ch-1", 1)
- expect(unreadProjection.projectUnread("servers", "ch-1", false)).toBe(false)
expect(attentionReconcileCount()).toBe(0)
- expect(invalidationCount(communityKeys.servers())).toBe(1)
+ expect(invalidationCount(communityKeys.servers())).toBe(0)
await vi.advanceTimersByTimeAsync(500)
expect(attentionReconcileCount()).toBe(1)
@@ -438,7 +221,7 @@ describe("useCommunityWs — operation bundles", () => {
}
})
- it("treats an ambiguous same-channel bundle as sticky instead of temporally pairing", async () => {
+ it("does not invent attention from an ambiguous same-channel bundle", async () => {
await mountHook({ viewerUserId: "viewer-1" })
const frame = await batchFor("ambiguous-bump", [
{ ...message, message: { ...message.message, id: "ambiguous-1", seq: 1 } },
@@ -446,12 +229,9 @@ describe("useCommunityWs — operation bundles", () => {
mentionEvents[1]!,
])
capturedOnMessage!(frame)
- const projection = getActiveAccountUnreadProjection(capturedQueryClient)
- projection.recordRead("ch-1", 999)
- expect(projection.projectUnread("servers", "ch-1", false)).toBe(true)
})
- it("correlates a unique same-channel bump regardless of child order", async () => {
+ it("keeps content and refreshes attention regardless of child order", async () => {
await mountHook({ viewerUserId: "viewer-1" })
const frame = await batchFor("reordered-bump", [
mentionEvents[1]!,
@@ -459,13 +239,9 @@ describe("useCommunityWs — operation bundles", () => {
mentionEvents[0]!,
])
capturedOnMessage!(frame)
- const projection = getActiveAccountUnreadProjection(capturedQueryClient)
- expect(projection.projectUnread("servers", "ch-1", false)).toBe(true)
- projection.recordRead("ch-1", 1)
- expect(projection.projectUnread("servers", "ch-1", false)).toBe(false)
})
- it("does not borrow seq evidence for a different mention message id", async () => {
+ it("does not invent attention from a different mention message id", async () => {
await mountHook({ viewerUserId: "viewer-1" })
const frame = await batchFor("mismatched-mention", [
message,
@@ -478,9 +254,6 @@ describe("useCommunityWs — operation bundles", () => {
},
])
capturedOnMessage!(frame)
- const projection = getActiveAccountUnreadProjection(capturedQueryClient)
- projection.recordRead("ch-1", 999)
- expect(projection.projectUnread("inbox-mentions", "ch-1", false)).toBe(true)
})
it("does not cancel or restart an in-flight raw server resource for a projected bump", async () => {
@@ -507,8 +280,6 @@ describe("useCommunityWs — operation bundles", () => {
expect(queryCalls).toBe(1)
expect(cancel.mock.calls.filter(([filters]) => JSON.stringify(filters.queryKey) === JSON.stringify(key))).toEqual([])
- expect(getActiveAccountUnreadProjection(capturedQueryClient)
- .projectServerUnread("server-1", [])).toBe(true)
await capturedQueryClient.cancelQueries({ queryKey: key, exact: true })
await first
})
@@ -530,7 +301,7 @@ describe("useCommunityWs — operation bundles", () => {
communityKeys.servers(),
)?.servers[0]?.mentions).toBe(9)
expect(attentionReconcileCount()).toBe(0)
- expect(invalidationCount(communityKeys.servers())).toBe(1)
+ expect(invalidationCount(communityKeys.servers())).toBe(0)
await vi.advanceTimersByTimeAsync(500)
expect(attentionReconcileCount()).toBe(1)
} finally {
@@ -618,9 +389,12 @@ describe("useCommunityWs — operation bundles", () => {
channels: [{ id: "text-parent", type: "text", unread: false }],
}],
})
- const unreadProjection = getActiveAccountUnreadProjection(capturedQueryClient)
- const recordArrival = vi.spyOn(unreadProjection, "recordArrival")
- .mockImplementationOnce(() => { throw new Error("second-child fault") })
+ const originalProject = canonicalSync.projectCommunityWsEventToDb
+ let fail = true
+ const recordArrival = vi.spyOn(canonicalSync, "projectCommunityWsEventToDb").mockImplementation((...args) => {
+ if (fail && args[1].type === "community:unread.bump") { fail = false; throw new Error("second-child fault") }
+ return originalProject(...args)
+ })
vi.spyOn(capturedQueryClient, "invalidateQueries")
const events: CommunityWsEvent[] = [
{
@@ -672,11 +446,6 @@ describe("useCommunityWs — operation bundles", () => {
expect(getCapturedRuntime().ws.get().seenMessageIds.size).toBe(1)
expect(getMessageStreamState(capturedQueryClient, { kind: "channel", id: "ch-1", serverId: "s1" }).liveIds.length)
.toBe(1)
- expect(unreadProjection.projectServerChannelUnread(
- "s1",
- "text-parent",
- [],
- )).toBe(true)
const invalidationsAfterCompletion = vi.mocked(capturedQueryClient.invalidateQueries).mock.calls.length
capturedOnMessage!(frame)
@@ -783,11 +552,6 @@ describe("useCommunityWs — operation bundles", () => {
// All preceding children are legal committed-message projections. Their
// writes remain visible when the final parent projection throws.
expect(getCapturedRuntime().ws.get().seenMessageIds.has("message-before-fault")).toBe(true)
- expect(getActiveAccountUnreadProjection(capturedQueryClient).projectUnread(
- "server-detail:s1",
- "ch-1",
- false,
- )).toBe(true)
expect(capturedQueryClient.getQueryData<{
servers: Array<{ id: string; mentions: number }>
}>(communityKeys.servers())?.servers[0]?.mentions).toBe(5)
@@ -809,11 +573,6 @@ describe("useCommunityWs — operation bundles", () => {
expect(capturedQueryClient.getQueryData<{
servers: Array<{ id: string; mentions: number }>
}>(communityKeys.servers())?.servers[0]?.mentions).toBe(5)
- expect(getActiveAccountUnreadProjection(capturedQueryClient).projectUnread(
- "server-detail:s1",
- "ch-1",
- false,
- )).toBe(true)
expect(capturedQueryClient.getQueryData<{
pages: Array<{ messages: Array<{ thread: { messageCount: number } }> }>
}>(communityKeys.channelMessages("forum_1"))?.pages[0]?.messages[0]?.thread.messageCount)
@@ -827,141 +586,6 @@ describe("useCommunityWs — operation bundles", () => {
.toHaveBeenCalledTimes(invalidationsAfterSuccess)
})
- it.each(["before", "after"] as const)(
- "keeps one barrier-owned refresh when an identical retry lands %s the first deadline",
- async (retryTiming) => {
- vi.useFakeTimers()
- try {
- getCapturedRuntime().ui.actions.subscribe({ channelId: "ch-1" })
- await mountHook({ viewerUserId: "viewer-1" })
- capturedQueryClient.setQueryData(communityKeys.server("s1"), {
- id: "s1",
- categories: [{
- id: "category-1",
- channels: [{ id: "parent-1", type: "text", unread: false }],
- }],
- })
- getCommunityApiFetchMock().mockImplementation(async (url: unknown) => {
- if (typeof url === "string" && url.endsWith("/read")) {
- return { changed: true, revision: 1, targetSeq: 1 }
- }
- if (url === "/api/community/users/me/read-state") {
- return {
- revision: 1,
- readStates: [{
- channelId: "ch-1",
- lastReadMessageId: `retry-${retryTiming}`,
- lastReadAt: "2026-08-27T00:00:00.000Z",
- lastReadSeq: 1,
- }],
- }
- }
- throw new Error(`unexpected API fetch: ${String(url)}`)
- })
- const unreadProjection = getActiveAccountUnreadProjection(capturedQueryClient)
- const recordArrival = vi.spyOn(unreadProjection, "recordArrival")
- .mockImplementationOnce(() => { throw new Error("later child fault") })
- const { captureChannelMetadataToken } = await import("@/hooks/community/channel-metadata")
- const verification = captureChannelMetadataToken(capturedQueryClient, "ch-1")
- await act(async () => { await seedConversationEntry(capturedQueryClient, conversationEntryFromChannel({ id: "ch-1", serverId: "s1", type: "thread", name: "thread", parentChannelId: "forum_1", parentMessageId: "opener-1", creatorId: "viewer-1", archived: false, createdAt: "2026-08-20T00:00:00.000Z" }, verification.viewerId!)) })
- vi.spyOn(capturedQueryClient, "invalidateQueries")
- const messageId = `retry-${retryTiming}`
- const frame = await batchFor(messageId, [
- {
- ...message,
- serverId: "s1",
- parentChannelId: "parent-1",
- message: { ...message.message, id: messageId },
- },
- {
- type: "community:unread.bump",
- userId: "viewer-1",
- channelId: "ch-1",
- serverId: "s1",
- railChannelId: "parent-1",
- isMention: false,
- },
- ])
- const lease = registerReadSurface(
- capturedQueryClient,
- "viewer-1",
- { kind: "timeline", channelId: "ch-1" },
- )
-
- capturedOnMessage!(frame)
- expect(reconcileCommunityWsReconnect).toHaveBeenCalledWith(
- capturedQueryClient,
- 0,
- { excludePolicies: ["inbox-dms"] },
- )
- expect(invalidationCount(communityKeys.inbox())).toBe(0)
- expect(invalidationCount(communityKeys.dms())).toBe(0)
- expect(submitReadIntent(lease, {
- kind: "timeline",
- channelId: "ch-1",
- messageId,
- seq: 1,
- })).toBe(true)
-
- recordArrival.mockRestore()
- if (retryTiming === "before") capturedOnMessage!(frame)
- await vi.advanceTimersByTimeAsync(500)
- expect(invalidationCount(communityKeys.inbox())).toBe(1)
- expect(invalidationCount(communityKeys.dms())).toBe(1)
- if (retryTiming === "after") capturedOnMessage!(frame)
- await vi.advanceTimersByTimeAsync(500)
-
- expect(invalidationCount(communityKeys.inbox())).toBe(1)
- expect(invalidationCount(communityKeys.dms())).toBe(1)
- const { useCommunityWsStore } = await import("@/stores/community/ws")
- expect(getCapturedRuntime().ws.get().seenDeliveryOperations.get(frame.operationId))
- .toEqual({ digest: frame.operationDigest, completed: true })
- releaseReadSurface(lease)
- } finally {
- vi.useRealTimers()
- }
- },
- )
-
- it("bounds normal and conflict refresh keys with the delivery-operation limits", async () => {
- vi.useFakeTimers()
- try {
- await mountHook({ viewerUserId: "viewer-1" })
- vi.spyOn(capturedQueryClient, "invalidateQueries")
- vi.spyOn(capturedQueryClient, "query")
- const original = await batchFor("bounded-operation", [{
- ...message,
- message: { ...message.message, id: "bounded-operation" },
- }, mentionEvents[1]!])
- capturedOnMessage!(original)
- const conflicts: Awaited<ReturnType<typeof batchFor>>[] = []
- for (let index = 0; index < SEEN_DELIVERY_OPERATION_MAX; index += 1) {
- const conflict = await batchFor("bounded-operation", [{
- ...message,
- message: {
- ...message.message,
- id: "bounded-operation",
- content: `conflict-${index}`,
- },
- }, mentionEvents[1]!])
- conflicts.push(conflict)
- capturedOnMessage!(conflict)
- }
-
- await vi.advanceTimersByTimeAsync(500)
- expect(attentionReconcileCount()).toBe(1)
- capturedOnMessage!(conflicts[0]!)
- await vi.advanceTimersByTimeAsync(500)
- expect(attentionReconcileCount()).toBe(1)
- capturedOnMessage!(conflicts.at(-1)!)
- await vi.advanceTimersByTimeAsync(500)
- expect(attentionReconcileCount()).toBe(1)
- expect(SEEN_DELIVERY_OPERATION_TRIM_TO).toBeLessThan(SEEN_DELIVERY_OPERATION_MAX)
- } finally {
- vi.useRealTimers()
- }
- })
-
it("reports a rejected authoritative reconciliation after a digest conflict", async () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {})
reconcileCommunityWsReconnect.mockRejectedValueOnce(new Error("reconcile unavailable"))
diff --git a/src/web/src/hooks/community/community-ws/handler-context.ts b/src/web/src/hooks/community/community-ws/handler-context.ts
index 9cd33f804..f48940ad1 100644
--- a/src/web/src/hooks/community/community-ws/handler-context.ts
+++ b/src/web/src/hooks/community/community-ws/handler-context.ts
@@ -24,11 +24,6 @@ export type UseCommunityWsOptions = {
viewerUserId?: string | null
}
-export type CommunityInboxRefreshRequest = {
- inbox: true
- dms: boolean
-}
-
export type CommunityWsDispatchContext = {
contract?: CommunityContract
deliveryMode: "single" | "batch"
@@ -38,7 +33,6 @@ export type CommunityWsDispatchContext = {
sub: Subscription
viewerUserIdRef: { current: string | null }
matchesFocus: (event: { channelId?: string }) => boolean
- scheduleInboxInvalidate: (request: CommunityInboxRefreshRequest) => void
}
export type CommunityWsHandlerContext = CommunityWsDispatchContext & {
@@ -71,7 +65,7 @@ export type MembershipEventContext = Pick<
export type SocialEventContext = Pick<
CommunityWsHandlerContext,
"deliveryMode" | "queryClient" | "sub" | "viewerUserIdRef" | "projection"
- | "scheduleInboxInvalidate" | "unreadBumpEvidence" | "messageEvidenceByChannel"
+ | "unreadBumpEvidence" | "messageEvidenceByChannel"
>
export type PresenceMachineEventContext = Pick<
CommunityWsHandlerContext,
diff --git a/src/web/src/hooks/community/community-ws/invalidation-projections.ts b/src/web/src/hooks/community/community-ws/invalidation-projections.ts
index 6b502f987..2bf2d805b 100644
--- a/src/web/src/hooks/community/community-ws/invalidation-projections.ts
+++ b/src/web/src/hooks/community/community-ws/invalidation-projections.ts
@@ -87,13 +87,7 @@ export function invalidateFriends(
export function invalidateInbox(
projection: CommunityWsProjectionTransaction,
) {
- projection.invalidate("inbox", { queryKey: communityKeys.inbox() })
-}
-
-export function invalidateDms(
- projection: CommunityWsProjectionTransaction,
-) {
- projection.invalidate("dms", { queryKey: communityKeys.dms() })
+ projection.invalidate("attention", { queryKey: communityKeys.accountAttention(), exact: true })
}
export function invalidatePresence(
diff --git a/src/web/src/hooks/community/community-ws/membership-events.dom.test.ts b/src/web/src/hooks/community/community-ws/membership-events.dom.test.ts
index 425cf1f2f..828124aab 100644
--- a/src/web/src/hooks/community/community-ws/membership-events.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/membership-events.dom.test.ts
@@ -1,3 +1,5 @@
+import { getCommunityDbRegistry } from "@/lib/community-db/collections"
+import { seedCommunityAttentionScope } from "@/test/community-query-owner"
import { conversationEntryFixture, conversationEntryFromChannel } from "@/test/conversation-entry-fixtures"
import type { MessageWindowData } from "@/lib/community/message-window"
import { canonicalMessage } from "./test-harness"
@@ -14,7 +16,6 @@ import { deriveCommunityDeliveryOperationId, encodeCommunityBrowserEventBatch, p
import { getMessageStreamState } from "@/test/community-query-owner"
import type { PresenceResponse } from "@/hooks/community/use-server-panels"
import { communityKeys } from "@/lib/query-keys"
-import { getAccountUnreadProjection } from "@/hooks/community/account-unread-projection"
import {
getCanonicalCommunityChannels,
patchCanonicalCommunityChannel,
@@ -46,8 +47,8 @@ afterEach(cleanupCommunityWsHarness)
describe("useCommunityWs — member events", () => {
it("clears the active private route immediately when the viewer leaves the server", async () => {
await mountHook({ viewerUserId: "u_me" })
- const unreadProjection = getAccountUnreadProjection(capturedQueryClient, "u_me")
- unreadProjection.recordArrival({ channelId: "private_child", serverId: "srv_1", seq: 1 })
+
+ seedCommunityAttentionScope(capturedQueryClient, { channelId: "private_child", serverId: "srv_1", seq: 1 })
const { useCommunityStore } = await import("@/stores/community")
getCapturedRuntime().ui.actions.setCurrentServerId("srv_1")
getCapturedRuntime().ui.actions.setCurrentChannelId("private_child")
@@ -92,8 +93,8 @@ describe("useCommunityWs — member events", () => {
expect(capturedQueryClient.getQueryState(communityKeys.server("srv_1"))).toBeUndefined()
expect(capturedQueryClient.getQueryState(communityKeys.reactionDetails("message_1"))).toBeUndefined()
expect(capturedQueryClient.getQueryState(communityKeys.reactionDetails("message_2"))).toBeDefined()
- expect(unreadProjection.projectUnread("servers", "private_child", false)).toBe(false)
- expect(unreadProjection.projectUnread("inbox-unreads", "private_child", true, 1)).toBe(false)
+ expect(Boolean(getCommunityDbRegistry(capturedQueryClient)!.collections.attentionScopes.get("private_child")?.ordinaryUnread)).toBe(false)
+ expect(Boolean(getCommunityDbRegistry(capturedQueryClient)!.collections.attentionScopes.get("private_child")?.ordinaryUnread)).toBe(false)
})
it("evicts an unresolved reaction-details request when the viewer leaves", async () => {
@@ -429,13 +430,13 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",
await mountHook({ viewerUserId: "u_me" })
const { useCommunityWsStore } = await import("@/stores/community/ws")
seedCanonicalThread("srv_1", "private_parent", "forum", "private")
- const projection = getAccountUnreadProjection(capturedQueryClient, "u_me")
- projection.recordArrival({ channelId: "private", serverId: "srv_1", seq: 1 })
+
+ seedCommunityAttentionScope(capturedQueryClient, { channelId: "private", serverId: "srv_1", seq: 1 })
capturedOnMessage!({ type: "community:channel.membership.change", relation: "notify", present: false, serverId: "srv_1", channelId: "private", userId: "u_me" })
- expect(projection.projectUnread("inbox-unreads", "private", true, 1)).toBe(false)
+ expect(Boolean(getCommunityDbRegistry(capturedQueryClient)!.collections.attentionScopes.get("private")?.ordinaryUnread)).toBe(false)
expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("private")).toBe(false)
- projection.recordArrival({ channelId: "private", serverId: "srv_1", seq: 2 })
- expect(projection.projectUnread("inbox-unreads", "private", false)).toBe(true)
+ seedCommunityAttentionScope(capturedQueryClient, { channelId: "private", serverId: "srv_1", seq: 2 })
+ expect(Boolean(getCommunityDbRegistry(capturedQueryClient)!.collections.attentionScopes.get("private")?.ordinaryUnread)).toBe(true)
})
@@ -543,7 +544,7 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",
expect(hasCanonicalChannelAccess("post_1", "u_me")).toBe(true)
expect(hasCanonicalChannelNotify("post_1", "u_me")).toBe(false)
expect(getCanonicalCommunityChannels(capturedQueryClient)
- .find(({ id }) => id === "post_1")?.unread).toBe(true)
+ .find(({ id }) => id === "post_1")).not.toHaveProperty("unread")
expect(readCurrentCommunityChannelMeta(capturedQueryClient)?.name).toBe("Private forum title")
await act(async () => { capturedOnMessage!({
@@ -642,8 +643,8 @@ describe("membership metadata and access lifetime", () => {
capturedQueryClient.setQueryData(otherKey, { pages: [{ messages: [{ id: "other" }] }] })
getCapturedRuntime().ui.actions.setCurrentChannelId("dm-private")
getCapturedRuntime().ui.actions.subscribe({ dmConversationId: "dm-private", channelId: "other-channel" })
- const unread = getAccountUnreadProjection(capturedQueryClient, "u_me")
- unread.recordArrival({ channelId: "dm-private", serverId: null, seq: 2 })
+
+ seedCommunityAttentionScope(capturedQueryClient, { channelId: "dm-private", serverId: null, seq: 2 })
const api = getCommunityApiFetchMock()
api.mockRejectedValue(new ApiError("DM blocked", 403))
capturedOnMessage!({ type: "community:channel.membership.change", channelId: "dm-private", serverId: null, userId: "u_me", relation: "access", present: false })
@@ -651,7 +652,7 @@ describe("membership metadata and access lifetime", () => {
expect(capturedQueryClient.getQueryData(otherKey)).toBeDefined()
expect(getCapturedRuntime().ui.get()).toMatchObject({ currentChannelId: null, subscription: { channelId: "other-channel" } })
expect(getCapturedRuntime().ui.get().subscription.dmConversationId).toBeUndefined()
- expect(unread.projectUnread("inbox-unreads", "dm-private", true, 2)).toBe(false)
+ expect(Boolean(getCommunityDbRegistry(capturedQueryClient)!.collections.attentionScopes.get("dm-private")?.ordinaryUnread)).toBe(false)
await vi.waitFor(() => expect(capturedQueryClient.getQueryState(entryKey(null, "dm-private"))?.status).toBe("error"))
expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("dm-private", null)).toBe(true)
})
@@ -979,15 +980,15 @@ describe("membership metadata and access lifetime", () => {
const api = getCommunityApiFetchMock()
const base = communityKeys.forumSidebarThreads("server")
capturedQueryClient.setQueryData(base, { threads: [], serverNow: "2026-10-01T00:00:00Z", verifiedEpoch: 0, serverClockOffsetMs: 0 })
- const unread = getAccountUnreadProjection(capturedQueryClient, "u_me")
- unread.recordArrival({ channelId: "child", serverId: "server", railChannelId: "forum", seq: 1, isMention: true })
+
+ seedCommunityAttentionScope(capturedQueryClient, { channelId: "child", serverId: "server", parentChannelId: "forum", seq: 1, attentionCount: 1 })
api.mockResolvedValue(conversationEntryFromChannel({ categoryId: null, topic: "", position: 0, messageCount: 1, creatorId: "peer", createdAt: "2026-10-01T00:00:00Z", lastMessageAt: "2026-10-01T00:00:01Z", id: "child", serverId: "server", type: "thread", parentChannelId: "forum", parentMessageId: "opener", name: "New post", archived: false }, "u_me"))
capturedOnMessage!({ type: "community:channel.member_add", channelId: "child", serverId: "server", userId: "u_me" })
await vi.waitFor(() => expect(capturedQueryClient.getQueryData(entryKey("server", "child"))).toMatchObject({ channelId: "child", proof: expect.any(Object) }))
await vi.waitFor(() => expect(hasCanonicalChannelNotify("child", "u_me")).toBe(true))
await vi.waitFor(() => expect(capturedQueryClient.getQueryState(base)?.isInvalidated).toBe(true))
expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("child", "server")).toBe(false)
- expect(unread.projectUnread("servers", "child", false)).toBe(true)
+ expect(Boolean(getCommunityDbRegistry(capturedQueryClient)!.collections.attentionScopes.get("child")?.ordinaryUnread)).toBe(true)
})
it.each([403, 404, 500].flatMap((status) => (["community:channel.member_add", "community:channel.member_remove"] as const).map((type) => ({ status, type }))))("keeps unknown legacy content retired after $type when the access recheck returns $status", async ({ status, type }) => {
diff --git a/src/web/src/hooks/community/community-ws/membership-events.ts b/src/web/src/hooks/community/community-ws/membership-events.ts
index e7a943bd7..06b813a04 100644
--- a/src/web/src/hooks/community/community-ws/membership-events.ts
+++ b/src/web/src/hooks/community/community-ws/membership-events.ts
@@ -38,7 +38,6 @@ import {
refreshServerReactionDetails,
removeServerReactionDetails,
} from "./reaction-details-invalidation"
-import { getAccountUnreadProjection } from "@/hooks/community/account-unread-projection"
import {
getCanonicalCommunityChannels,
retireCommunityChannelReading,
@@ -69,7 +68,6 @@ function refreshChannelAccess(event: { serverId: string | null; channelId: strin
const channel = getCanonicalCommunityChannels(queryClient).find((row) => row.id === event.channelId && row.serverId === event.serverId)
if (channel?.archived) runCommunityWsProjectionTransaction(queryClient, (projection) => retireChannelAccess(event, { ...context, projection }))
else if (channel) {
- getAccountUnreadProjection(queryClient, context.viewerUserIdRef.current!).grantAccessScope({ kind: "channel", channelId: event.channelId })
if (legacyEvent && channel.type === "thread") runCommunityWsProjectionTransaction(queryClient, (projection) => {
handleChannelMembershipChange({ ...legacyEvent, type: "community:channel.membership.change", relation: "notify", present: legacyEvent.type === "community:channel.member_add" }, { ...context, projection })
})
@@ -95,7 +93,6 @@ export function handleChannelMembershipChange(event: CommunityChannelMembershipC
invalidateForumSidebar(projection, event.serverId)
}
if (event.relation === "notify") {
- if (!event.present) getAccountUnreadProjection(queryClient, event.userId).retireNotificationScope({ kind: "channel", channelId: event.channelId })
return
}
if (!event.present) retireChannelAccess(event, context)
@@ -152,10 +149,6 @@ export function handleMemberJoin(
const viewerId = viewerUserIdRef.current
if (viewerId) {
getCommunityRuntime(context.queryClient).ws.actions.grantServerAccess(event.serverId)
- getAccountUnreadProjection(queryClient, viewerId).grantAccessScope({
- kind: "server",
- serverId: event.serverId,
- })
}
invalidateChannelRefDirectory(projection)
invalidateServersList(projection)
diff --git a/src/web/src/hooks/community/community-ws/projection-transaction.test.ts b/src/web/src/hooks/community/community-ws/projection-transaction.test.ts
index 031ac2fc4..32e05204d 100644
--- a/src/web/src/hooks/community/community-ws/projection-transaction.test.ts
+++ b/src/web/src/hooks/community/community-ws/projection-transaction.test.ts
@@ -35,14 +35,14 @@ describe("community WS projection transaction", () => {
it("deduplicates only identical owner and filter pairs in first-seen order", () => {
const queryClient = new QueryClient()
const invalidate = vi.spyOn(queryClient, "invalidateQueries").mockResolvedValue()
- const first = { queryKey: ["community", "inbox"] as const }
- const conflict = { queryKey: ["community", "inbox"] as const, exact: true }
+ const first = { queryKey: ["community", "attention"] as const, exact: true }
+ const conflict = { queryKey: ["community", "attention"] as const }
const second = { queryKey: ["community", "servers"] as const, exact: true }
runCommunityWsProjectionTransaction(queryClient, (transaction) => {
invalidateInbox(transaction)
invalidateInbox(transaction)
- transaction.invalidate("inbox", conflict)
+ transaction.invalidate("attention", conflict)
transaction.invalidate("servers", second)
})
diff --git a/src/web/src/hooks/community/community-ws/read-state-events.test.ts b/src/web/src/hooks/community/community-ws/read-state-events.test.ts
index 9576aed06..360c22f8c 100644
--- a/src/web/src/hooks/community/community-ws/read-state-events.test.ts
+++ b/src/web/src/hooks/community/community-ws/read-state-events.test.ts
@@ -1,294 +1,63 @@
-import { seedCommunityReadState } from "@/test/community-query-owner"
-import { currentConversationReadState } from "@/lib/community/conversation-entry"
-import { createCommunityDbRegistry } from "@/lib/community-db/collections"
+import { afterEach, beforeEach, expect, it, vi } from "vitest"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
-import { QueryClient } from "@tanstack/react-query"
+import { currentConversationReadState } from "@/lib/community/conversation-entry"
+import { captureCommunityLiveSnapshotToken, ingestReadStateSnapshot, publishCommunityConversationReadState } from "@/lib/community-db/sync"
import { communityKeys } from "@/lib/query-keys"
-
-const apiFetch = vi.hoisted(() => vi.fn())
-vi.mock("@/lib/api/client", () => ({
- apiFetch: (...args: unknown[]) => apiFetch(...args),
-}))
-
import { dispatchCommunityWsEvent } from "./registry"
import type { CommunityWsDispatchContext } from "./handler-context"
-import { getAccountUnreadProjection } from "@/hooks/community/account-unread-projection"
import { notificationSettingsQueryFn } from "@/hooks/community/use-notification-settings"
import { disposeAccountReadStateReconciliation } from "./read-state-reconciliation"
-function context(
- queryClient: QueryClient,
- scheduleInboxInvalidate = vi.fn(),
-): CommunityWsDispatchContext {
- const runtime = createCommunityDbRegistry(queryClient, "u1").runtime
- return {
- deliveryMode: "single",
- queryClient,
- communityStore: runtime.ui,
- wsStore: runtime.ws,
- sub: {},
- viewerUserIdRef: { current: "u1" },
- matchesFocus: () => false,
- scheduleInboxInvalidate,
- }
-}
-
-describe("same-account read-state WS events", () => {
- let queryClient: QueryClient
-
- beforeEach(async () => {
- queryClient = (await createCommunityQueryOwner("u1")).client
- apiFetch.mockReset()
- })
-
- afterEach(() => {
- disposeAccountReadStateReconciliation(queryClient)
- queryClient.clear()
- })
-
- it("pulls and projects the authoritative replacement for an exact-next hint", async () => {
- queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
- revision: 2,
- readStates: [],
- })
- seedCommunityReadState(queryClient, "dm1", {
- lastReadMessageId: null,
- lastReadAt: null,
- lastReadSeq: 0,
- })
-
- apiFetch.mockResolvedValue({
- revision: 3,
- readStates: [{
- channelId: "dm1",
- lastReadMessageId: "m4",
- lastReadAt: "2026-08-24T00:00:04.000Z",
- lastReadSeq: 4,
- }],
- })
- dispatchCommunityWsEvent({
- type: "community:read_state.advanced",
- revision: 3,
- inboxChanged: true,
- }, context(queryClient))
-
- await vi.waitFor(() => expect(currentConversationReadState(queryClient, "dm1",
- )).toMatchObject({
- lastReadMessageId: "m4",
- lastReadSeq: 4,
- }))
- expect(apiFetch.mock.calls.filter(([path]) => path === "/api/community/users/me/read-state")).toHaveLength(1)
- })
-
- it("repairs a revision gap from the authoritative snapshot", async () => {
- queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
- revision: 2,
- readStates: [],
- })
- apiFetch.mockResolvedValue({
- revision: 5,
- readStates: [{
- channelId: "c1",
- lastReadMessageId: "m8",
- lastReadAt: "2026-08-24T00:00:08.000Z",
- lastReadSeq: 8,
- }],
- })
-
- dispatchCommunityWsEvent({
- type: "community:read_state.advanced",
- revision: 5,
- inboxChanged: true,
- }, context(queryClient))
-
- await vi.waitFor(() => expect(queryClient.getQueryData(
- communityKeys.accountReadStateSnapshot(),
- )).toMatchObject({ revision: 5 }))
- expect(apiFetch.mock.calls.filter(([path]) => path === "/api/community/users/me/read-state")).toHaveLength(1)
- })
-
- it("pulls one full read-all replacement and ignores its stale replay", async () => {
- queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
- revision: 7,
- readStates: [],
- })
- seedCommunityReadState(queryClient, "c1", { lastReadSeq: 0 })
-
- apiFetch.mockResolvedValue({
- revision: 8,
- readStates: [{
- channelId: "c1",
- lastReadMessageId: "m8",
- lastReadAt: "2026-08-24T00:00:08.000Z",
- lastReadSeq: 8,
- }],
- })
-
- const event = {
- type: "community:inbox.changed",
- revision: 8,
- inboxChanged: true,
- reason: "read_all",
- } as const
- dispatchCommunityWsEvent(event, context(queryClient))
- await vi.waitFor(() => expect(currentConversationReadState(queryClient, "c1",
- )).toMatchObject({
- lastReadSeq: 8,
- }))
- expect(apiFetch.mock.calls.filter(([path]) => path === "/api/community/users/me/read-state")).toHaveLength(1)
-
- dispatchCommunityWsEvent(event, context(queryClient))
- expect(apiFetch.mock.calls.filter(([path]) => path === "/api/community/users/me/read-state")).toHaveLength(1)
- })
-
- it("absorbs an authoritative repair failure after receiving a newer hint", async () => {
- queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
- revision: 2,
- readStates: [],
- })
- apiFetch.mockRejectedValue(new Error("temporary snapshot failure"))
-
- dispatchCommunityWsEvent({
- type: "community:read_state.advanced",
- revision: 3,
- inboxChanged: true,
- }, context(queryClient))
-
- await vi.waitFor(() => expect(apiFetch.mock.calls.filter(([path]) => path === "/api/community/users/me/read-state")).toHaveLength(1))
- await vi.waitFor(() => expect(queryClient.getQueryState(
- communityKeys.accountReadStateSnapshot(),
- )?.fetchStatus).toBe("idle"))
- expect(queryClient.getQueryData(communityKeys.accountReadStateSnapshot()))
- .toMatchObject({ revision: 2 })
- })
-
- it("schedules the owner immediately while the snapshot repairs only non-Inbox surfaces", async () => {
- queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
- revision: 2,
- readStates: [],
- })
- let resolveSnapshot!: (value: unknown) => void
- apiFetch.mockReturnValue(new Promise((resolve) => { resolveSnapshot = resolve }))
- const invalidate = vi.spyOn(queryClient, "invalidateQueries")
- const scheduleInboxInvalidate = vi.fn()
-
- dispatchCommunityWsEvent({
- type: "community:inbox.changed",
- revision: 3,
- inboxChanged: true,
- reason: "read_all",
- }, context(queryClient, scheduleInboxInvalidate))
-
- expect(scheduleInboxInvalidate).toHaveBeenCalledOnce()
- expect(scheduleInboxInvalidate).toHaveBeenCalledWith({ inbox: true, dms: true })
- expect(invalidate).not.toHaveBeenCalledWith(expect.objectContaining({
- queryKey: communityKeys.inbox(),
- }), expect.anything())
- expect(invalidate).not.toHaveBeenCalledWith(expect.objectContaining({
- queryKey: communityKeys.dms(),
- }), expect.anything())
-
- resolveSnapshot({ revision: 3, readStates: [] })
- await vi.waitFor(() => {
- expect(invalidate).toHaveBeenCalledWith(
- expect.objectContaining({ queryKey: communityKeys.servers() }),
- expect.anything(),
- )
- })
- expect(invalidate).not.toHaveBeenCalledWith(expect.objectContaining({
- queryKey: communityKeys.inbox(),
- }), expect.anything())
- expect(invalidate).not.toHaveBeenCalledWith(expect.objectContaining({
- queryKey: communityKeys.dms(),
- }), expect.anything())
- })
-
- it.each([
- ["nothing", "all", [], true],
- ["all", "nothing", [{ serverId: "s1", channelId: null, level: "nothing" }], false],
- ] as const)("reconciles a peer tab from %s to %s policy", async (
- initial,
- _next,
- settings,
- expected,
- ) => {
- const sourceClient = (await createCommunityQueryOwner("u1")).client
- const peerClient = (await createCommunityQueryOwner("u1")).client
- const source = getAccountUnreadProjection(sourceClient, "u1")
- const peer = getAccountUnreadProjection(peerClient, "u1")
- source.setNotificationPolicy({ server: { s1: expected ? "all" : "nothing" } })
- peer.setNotificationPolicy({ server: { s1: initial } })
- source.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })
- peer.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })
- peerClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
- revision: 1,
- readStates: [],
- })
- apiFetch.mockImplementation(async (path: string) => (
- path === "/api/community/users/me/notifications"
- ? settings
- : { revision: 2, readStates: [] }
- ))
-
- dispatchCommunityWsEvent({
- type: "community:inbox.changed",
- revision: 2,
- inboxChanged: true,
- reason: "notification_policy",
- }, context(peerClient))
-
- await vi.waitFor(() => expect(
- peer.projectUnread("servers", "c1", false),
- ).toBe(expected))
- expect(peer.projectUnread("servers", "c1", false)).toBe(
- source.projectUnread("servers", "c1", false),
- )
- })
-
- it("cancels an older in-flight policy fetch and keeps an old unread snapshot positive-only", async () => {
- const projection = getAccountUnreadProjection(queryClient, "u1")
- projection.setNotificationPolicy({ server: { s1: "nothing" } })
- projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })
- const stalePolicySnapshot = projection.beginSnapshot("servers", "channels")
- queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
- revision: 1,
- readStates: [],
- })
- let resolveOldPolicy!: (value: unknown) => void
- let policyCalls = 0
- apiFetch.mockImplementation((path: string) => {
- if (path !== "/api/community/users/me/notifications") {
- return Promise.resolve({ revision: 2, readStates: [] })
- }
- policyCalls += 1
- if (policyCalls === 1) {
- return new Promise((resolve) => { resolveOldPolicy = resolve })
- }
- return Promise.resolve([])
- })
- const oldRequest = queryClient.query({
- queryKey: communityKeys.notificationSettings(),
- queryFn: notificationSettingsQueryFn,
- }).catch(() => undefined)
- await vi.waitFor(() => expect(policyCalls).toBe(1))
+const apiFetch = vi.hoisted(() => vi.fn())
+vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => apiFetch(...args) }))
+let owner: Awaited<ReturnType<typeof createCommunityQueryOwner>>
+const emptyAttention = { scopes: [], items: [], limit: 100, truncated: false, included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } }
+function context(): CommunityWsDispatchContext { return { deliveryMode: "single", queryClient: owner.client, communityStore: owner.runtime.ui, wsStore: owner.runtime.ws, sub: {}, viewerUserIdRef: { current: "u1" }, matchesFocus: () => false } }
+beforeEach(async () => { owner = await createCommunityQueryOwner("u1"); apiFetch.mockReset() })
+afterEach(async () => { disposeAccountReadStateReconciliation(owner.client); await owner.registry.cleanup(); owner.client.clear() })
+
+it.each(["community:read_state.advanced", "community:inbox.changed"] as const)("fills the account snapshot after a confirmed read once for %s and ignores an old hint", async type => {
+ const snapshot = { revision: 8, readStates: [
+ { channelId: "c1", lastReadMessageId: "m8", lastReadAt: "2026-10-27T00:00:08.000Z", lastReadSeq: 8 },
+ { channelId: "c2", lastReadMessageId: "m7", lastReadAt: "2026-10-27T00:00:07.000Z", lastReadSeq: 7 },
+ ] }
+ publishCommunityConversationReadState(owner.client, snapshot.readStates[0], 8, { token: captureCommunityLiveSnapshotToken(owner.client), signal: undefined })
+ expect(owner.registry.collections.readStateClock.get("account")).toBeUndefined()
+ apiFetch.mockImplementation(async (path: string) => path.endsWith("/read-state") ? snapshot : emptyAttention)
+ const event = { type, revision: 8, inboxChanged: true, ...(type === "community:inbox.changed" ? { reason: "read_all" as const } : {}) }
+ dispatchCommunityWsEvent(event, context())
+ await vi.waitFor(() => expect(owner.registry.collections.readStateClock.get("account")?.revision).toBe(8))
+ expect(currentConversationReadState(owner.client, "c1")?.lastReadSeq).toBe(8)
+ expect(currentConversationReadState(owner.client, "c2")?.lastReadSeq).toBe(7)
+ await vi.waitFor(() => expect(apiFetch.mock.calls.filter(([path]) => path.endsWith("/attention"))).toHaveLength(1))
+ dispatchCommunityWsEvent(event, context())
+ expect(apiFetch.mock.calls.filter(([path]) => path.endsWith("/read-state"))).toHaveLength(1)
+ expect(apiFetch.mock.calls.filter(([path]) => path.endsWith("/attention"))).toHaveLength(1)
+ expect(apiFetch.mock.calls.some(([path]) => path === "/api/community/servers" || path.endsWith("/dms"))).toBe(false)
+})
- dispatchCommunityWsEvent({
- type: "community:inbox.changed",
- revision: 2,
- inboxChanged: true,
- reason: "notification_policy",
- }, context(queryClient))
- await vi.waitFor(() => expect(policyCalls).toBe(2))
- resolveOldPolicy([{ serverId: "s1", channelId: null, level: "nothing" }])
- await oldRequest
- await vi.waitFor(() => expect(projection.getPolicyGeneration()).toBeGreaterThan(1))
- expect(queryClient.getQueryData(communityKeys.notificationSettings())).toMatchObject({
- ids: [],
- })
- expect(createCommunityDbRegistry(queryClient, "u1").collections.notificationSettings.size).toBe(0)
+it("refreshes notification policy and invalidates native attention even after its read revision was observed", async () => {
+ ingestReadStateSnapshot(owner.registry, { revision: 2, readStates: [] })
+ owner.client.setQueryData(communityKeys.accountAttention(), { loaded: true })
+ apiFetch.mockResolvedValue([{ serverId: "s1", channelId: null, level: "nothing" }])
+ dispatchCommunityWsEvent({ type: "community:inbox.changed", revision: 2, inboxChanged: true, reason: "notification_policy" }, context())
+ await vi.waitFor(() => expect(owner.registry.collections.notificationSettings.get("server:s1")?.level).toBe("nothing"))
+ await vi.waitFor(() => expect(owner.client.getQueryState(communityKeys.accountAttention())?.isInvalidated).toBe(true))
+ expect(apiFetch.mock.calls.map(([path]) => path)).toEqual(["/api/community/users/me/notifications"])
+})
- projection.absorbSnapshot(stalePolicySnapshot, [], { truncated: false })
- expect(projection.projectUnread("servers", "c1", false)).toBe(true)
- })
+it("cancels an older policy transport and rejects its ignored-abort response", async () => {
+ ingestReadStateSnapshot(owner.registry, { revision: 2, readStates: [] })
+ let release!: (rows: unknown) => void, policyCalls = 0
+ apiFetch.mockImplementation((path: string) => {
+ if (path.endsWith("/notifications")) return ++policyCalls === 1 ? new Promise(done => { release = done }) : Promise.resolve([])
+ return Promise.resolve(emptyAttention)
+ })
+ const old = owner.client.query({ queryKey: communityKeys.notificationSettings(), queryFn: notificationSettingsQueryFn }).catch(() => undefined)
+ await vi.waitFor(() => expect(policyCalls).toBe(1))
+ dispatchCommunityWsEvent({ type: "community:inbox.changed", revision: 2, inboxChanged: true, reason: "notification_policy" }, context())
+ await vi.waitFor(() => expect(policyCalls).toBe(2))
+ release([{ serverId: "s1", channelId: null, level: "nothing" }]); await old
+ await vi.waitFor(() => expect(owner.client.getQueryData(communityKeys.notificationSettings())).toEqual({ ids: [] }))
+ expect(owner.registry.collections.notificationSettings.size).toBe(0)
})
diff --git a/src/web/src/hooks/community/community-ws/read-state-reconciliation.dom.test.ts b/src/web/src/hooks/community/community-ws/read-state-reconciliation.dom.test.ts
new file mode 100644
index 000000000..e823a8fbf
--- /dev/null
+++ b/src/web/src/hooks/community/community-ws/read-state-reconciliation.dom.test.ts
@@ -0,0 +1,33 @@
+import { createElement, type PropsWithChildren } from "react"
+import { expect, it, vi } from "vitest"
+import { act, renderHook } from "@/test/react-dom-harness"
+import { CommunityTestProvider } from "@/test/community-owner-fixture"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { communityKeys } from "@/lib/query-keys"
+import { disposeAccountReadStateReconciliation, useAccountReadState } from "./read-state-reconciliation"
+
+const apiFetch = vi.hoisted(() => vi.fn())
+vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => apiFetch(...args) }))
+
+it("lets the native shell observer retry quiet failures and stops its HTTP after owner retirement", async () => {
+ const owner = await createCommunityQueryOwner("viewer", { defaultOptions: { queries: { retry: 3 } } })
+ vi.useFakeTimers()
+ let requests = 0
+ apiFetch.mockImplementation(async () => {
+ requests += 1
+ if (requests <= 4) throw new Error("offline")
+ return { revision: 8, readStates: [{ channelId: "c1", lastReadMessageId: "m8", lastReadAt: "2026-10-27T00:00:08.000Z", lastReadSeq: 8 }] }
+ })
+ const wrapper = ({ children }: PropsWithChildren) => createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, retainOwner: true }, children)
+ const rendered = renderHook(useAccountReadState, { wrapper })
+ const original = owner.client.getQueryCache().find({ queryKey: communityKeys.accountReadStateSnapshot(), exact: true })
+ try {
+ await act(async () => { await vi.advanceTimersByTimeAsync(12_000) })
+ expect(owner.registry.collections.readStates.get("c1")?.lastReadSeq).toBe(8)
+ expect(owner.client.getQueryCache().find({ queryKey: communityKeys.accountReadStateSnapshot(), exact: true })).toBe(original)
+ disposeAccountReadStateReconciliation(owner.client)
+ const before = requests
+ await act(async () => { await vi.advanceTimersByTimeAsync(20_000) })
+ expect(requests).toBe(before)
+ } finally { rendered.unmount(); await owner.client.cancelQueries(); vi.useRealTimers() }
+})
diff --git a/src/web/src/hooks/community/community-ws/read-state-reconciliation.test.ts b/src/web/src/hooks/community/community-ws/read-state-reconciliation.test.ts
index 47d45a225..b9cca7b1f 100644
--- a/src/web/src/hooks/community/community-ws/read-state-reconciliation.test.ts
+++ b/src/web/src/hooks/community/community-ws/read-state-reconciliation.test.ts
@@ -1,937 +1,136 @@
-import { seedCommunityReadState } from "@/test/community-query-owner"
-import { currentConversationReadState } from "@/lib/community/conversation-entry"
-import { createCommunityDbRegistry } from "@/lib/community-db/collections"
-import { beforeEach, describe, expect, it, vi } from "vitest"
-import { QueryClient, QueryObserver } from "@tanstack/react-query"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
import { communityKeys } from "@/lib/query-keys"
-import { ConversationReadTimeoutError, withConversationReadDeadline } from "@/lib/community/conversation-read"
+import { captureCommunityLiveSnapshotToken, publishCommunityConversationReadState } from "@/lib/community-db/sync"
+import { currentConversationReadState } from "@/lib/community/conversation-entry"
+import { disposeAccountReadStateReconciliation, projectReadStateEnvelope, reconcileAccountReadState } from "./read-state-reconciliation"
const apiFetch = vi.hoisted(() => vi.fn())
-vi.mock("@/lib/api/client", () => ({
- apiFetch: (...args: unknown[]) => apiFetch(...args),
-}))
-
-import {
- disposeAccountReadStateReconciliation,
- projectReadStateEnvelope,
- reconcileAccountReadState,
- type AccountReadStateSnapshot,
-} from "./read-state-reconciliation"
-
-describe("account read-state reconciliation", () => {
- let queryClient: QueryClient
-
- beforeEach(() => {
- vi.useRealTimers()
- queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- createCommunityDbRegistry(queryClient, "viewer")
- apiFetch.mockReset()
- })
-
- it("treats every newer bounded hint as an authoritative-snapshot gap", () => {
- queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
- revision: 6,
- readStates: [],
- })
- expect(projectReadStateEnvelope(queryClient, {
- revision: 6,
- inboxChanged: true,
- })).toBe("stale")
- expect(projectReadStateEnvelope(queryClient, {
- revision: 7,
- inboxChanged: true,
- })).toBe("gap")
- expect(projectReadStateEnvelope(queryClient, {
- revision: 8,
- inboxChanged: true,
- })).toBe("gap")
- queryClient.removeQueries({ queryKey: communityKeys.accountReadStateSnapshot() })
- expect(projectReadStateEnvelope(queryClient, {
- revision: 1,
- inboxChanged: true,
- })).toBe("gap")
- })
-
- it("loads the authoritative full replacement, including regression and removal", async () => {
- seedCommunityReadState(queryClient, "c1", { lastReadSeq: 1 })
- seedCommunityReadState(queryClient, "dm1", { lastReadSeq: 2 })
- apiFetch.mockResolvedValue({
- revision: 10,
- readStates: [{
- channelId: "c1",
- lastReadMessageId: "m0",
- lastReadAt: "2026-08-24T00:00:00.000Z",
- lastReadSeq: 0,
- }],
- })
-
- await reconcileAccountReadState(queryClient, { invalidateSurfaces: false })
- expect(apiFetch).toHaveBeenCalledWith("/api/community/users/me/read-state", expect.objectContaining({ signal: expect.any(AbortSignal) }))
- expect(currentConversationReadState(queryClient, "c1")).toMatchObject({
- lastReadMessageId: "m0",
- lastReadSeq: 0,
- })
- expect(currentConversationReadState(queryClient, "dm1")).toMatchObject({
- lastReadMessageId: null,
- lastReadAt: null,
- lastReadSeq: 0,
- })
- })
-
- it("discards an in-flight snapshot superseded by a newer target revision", async () => {
- queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
- revision: 4,
- readStates: [],
- })
- seedCommunityReadState(queryClient, "c1", {
- lastReadMessageId: "m4",
- lastReadAt: "2026-08-24T00:00:04.000Z",
- lastReadSeq: 4,
- })
- const releases: Array<(snapshot: AccountReadStateSnapshot) => void> = []
- apiFetch.mockImplementation(() => new Promise<AccountReadStateSnapshot>((resolve) => {
- releases.push(resolve)
- }))
-
- const first = reconcileAccountReadState(queryClient, {
- invalidateSurfaces: false,
- targetRevision: 5,
- })
- await vi.waitFor(() => expect(releases).toHaveLength(1))
- const second = reconcileAccountReadState(queryClient, {
- invalidateSurfaces: false,
- targetRevision: 6,
- })
- releases[0]!({
- revision: 5,
- readStates: [{
- channelId: "c1",
- lastReadMessageId: "m5",
- lastReadAt: "2026-08-24T00:00:05.000Z",
- lastReadSeq: 5,
- }],
- })
- await vi.waitFor(() => expect(releases).toHaveLength(2))
-
- expect(queryClient.getQueryData(communityKeys.accountReadStateSnapshot()))
- .toMatchObject({ revision: 4 })
- expect(currentConversationReadState(queryClient, "c1"))
- .toMatchObject({ lastReadSeq: 4 })
-
- releases[1]!({
- revision: 6,
- readStates: [{
- channelId: "c1",
- lastReadMessageId: "m6",
- lastReadAt: "2026-08-24T00:00:06.000Z",
- lastReadSeq: 6,
- }],
- })
- await expect(Promise.all([first, second])).resolves.toEqual([
- expect.objectContaining({ revision: 6 }),
- expect.objectContaining({ revision: 6 }),
- ])
- expect(currentConversationReadState(queryClient, "c1"))
- .toMatchObject({ lastReadSeq: 6 })
- })
-
- it("uses all surfaces when options are omitted", async () => {
- apiFetch.mockResolvedValue({ revision: 1, readStates: [] })
- const invalidate = vi.spyOn(queryClient, "invalidateQueries")
-
- await expect(reconcileAccountReadState(queryClient)).resolves.toEqual({
- revision: 1,
- readStates: [],
- })
-
- expect(invalidate).toHaveBeenCalledWith({
- queryKey: communityKeys.inbox(),
- refetchType: "active",
- }, { throwOnError: true, cancelRefetch: true })
- expect(invalidate).toHaveBeenCalledWith({
- queryKey: communityKeys.servers(),
- exact: true,
- refetchType: "active",
- predicate: expect.any(Function),
- }, { throwOnError: true, cancelRefetch: true })
- })
-
- it("reprojects leaf caches when a lifecycle read returns the current revision", async () => {
- queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
- revision: 10,
- readStates: [],
- })
- seedCommunityReadState(queryClient, "late", {
- lastReadMessageId: null,
- lastReadAt: null,
- lastReadSeq: 0,
- })
- apiFetch.mockResolvedValue({
- revision: 10,
- readStates: [{
- channelId: "late",
- lastReadMessageId: "m3",
- lastReadAt: "2026-08-24T00:00:03.000Z",
- lastReadSeq: 3,
- }],
- })
-
- await reconcileAccountReadState(queryClient, { invalidateSurfaces: false })
-
- expect(currentConversationReadState(queryClient, "late"))
- .toMatchObject({ lastReadMessageId: "m3", lastReadSeq: 3 })
- })
-
- it("refetches cached server details without refetching the channel-ref directory", async () => {
- queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
- revision: 1,
- readStates: [],
- })
- let serverFetches = 0
- let directoryFetches = 0
- const serverObserver = new QueryObserver(queryClient, {
- queryKey: communityKeys.server("server-1"),
- queryFn: async () => {
- serverFetches += 1
- return { id: "server-1" }
- },
- staleTime: Infinity,
- })
- const directoryObserver = new QueryObserver(queryClient, {
- queryKey: communityKeys.channelRefDirectory(),
- queryFn: async () => {
- directoryFetches += 1
- return { servers: [] }
- },
- staleTime: Infinity,
- })
- const unsubscribeServer = serverObserver.subscribe(() => {})
- const unsubscribeDirectory = directoryObserver.subscribe(() => {})
- await vi.waitFor(() => {
- expect(serverFetches).toBe(1)
- expect(directoryFetches).toBe(1)
- })
- queryClient.setQueryData(communityKeys.server("__none__"), { id: "__none__" })
- apiFetch.mockResolvedValue({ revision: 2, readStates: [] })
- const invalidate = vi.spyOn(queryClient, "invalidateQueries")
-
- await reconcileAccountReadState(queryClient, { targetRevision: 2 })
-
- expect(serverFetches).toBe(2)
- expect(directoryFetches).toBe(1)
- expect(invalidate).toHaveBeenCalledWith(
- { queryKey: communityKeys.server("server-1"), exact: true, refetchType: "active", predicate: expect.any(Function) },
- { throwOnError: true, cancelRefetch: true },
- )
- expect(invalidate).not.toHaveBeenCalledWith(
- { queryKey: communityKeys.channelRefDirectory(), exact: true, refetchType: "active" },
- expect.anything(),
- )
- expect(invalidate).not.toHaveBeenCalledWith(
- { queryKey: communityKeys.server("__none__"), exact: true, refetchType: "active" },
- expect.anything(),
- )
- unsubscribeDirectory()
- unsubscribeServer()
- })
-
- it("deduplicates concurrent lifecycle and gap reconciliations per query client", async () => {
- let release!: (snapshot: AccountReadStateSnapshot) => void
- apiFetch.mockReturnValue(new Promise<AccountReadStateSnapshot>((resolve) => {
- release = resolve
- }))
-
- const first = reconcileAccountReadState(queryClient, { invalidateSurfaces: false })
- const second = reconcileAccountReadState(queryClient, { invalidateSurfaces: false })
- expect(apiFetch).toHaveBeenCalledTimes(1)
-
- release({ revision: 3, readStates: [] })
- await expect(Promise.all([first, second])).resolves.toEqual([
- { revision: 3, readStates: [] },
- { revision: 3, readStates: [] },
- ])
- })
-
- it("does not lose a live revision behind a cold auth snapshot in flight", async () => {
- let releaseAuth!: (snapshot: AccountReadStateSnapshot) => void
- let releaseFresh!: (snapshot: AccountReadStateSnapshot) => void
- apiFetch
- .mockReturnValueOnce(new Promise<AccountReadStateSnapshot>((resolve) => {
- releaseAuth = resolve
- }))
- .mockReturnValueOnce(new Promise<AccountReadStateSnapshot>((resolve) => {
- releaseFresh = resolve
- }))
- seedCommunityReadState(queryClient, "c1", { lastReadSeq: 0 })
- seedCommunityReadState(queryClient, "removed", { lastReadSeq: 4 })
-
- const auth = reconcileAccountReadState(queryClient, { invalidateSurfaces: false })
- expect(projectReadStateEnvelope(queryClient, {
- revision: 5,
- inboxChanged: true,
- })).toBe("gap")
- const live = reconcileAccountReadState(queryClient, {
- invalidateSurfaces: false,
- targetRevision: 5,
- })
- expect(apiFetch).toHaveBeenCalledTimes(1)
-
- releaseAuth({ revision: 4, readStates: [] })
- await vi.waitFor(() => expect(apiFetch).toHaveBeenCalledTimes(2))
- releaseFresh({
- revision: 5,
- readStates: [{
- channelId: "c1",
- lastReadMessageId: "m5",
- lastReadAt: "2026-08-24T00:00:05.000Z",
- lastReadSeq: 5,
- }],
- })
-
- await expect(Promise.all([auth, live])).resolves.toEqual([
- {
- revision: 5,
- readStates: [{
- channelId: "c1",
- lastReadMessageId: "m5",
- lastReadAt: "2026-08-24T00:00:05.000Z",
- lastReadSeq: 5,
- }],
- },
- {
- revision: 5,
- readStates: [{
- channelId: "c1",
- lastReadMessageId: "m5",
- lastReadAt: "2026-08-24T00:00:05.000Z",
- lastReadSeq: 5,
- }],
- },
- ])
- expect(currentConversationReadState(queryClient, "c1")).toMatchObject({
- lastReadMessageId: "m5",
- lastReadSeq: 5,
- })
- expect(currentConversationReadState(queryClient, "removed")).toMatchObject({
- lastReadMessageId: null,
- lastReadAt: null,
- lastReadSeq: 0,
- })
- })
-
- it("immediately refetches when a successful snapshot remains below the live target", async () => {
- queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
- revision: 4,
- readStates: [],
- })
- apiFetch
- .mockResolvedValueOnce({ revision: 4, readStates: [] })
- .mockResolvedValueOnce({ revision: 5, readStates: [] })
-
- await expect(reconcileAccountReadState(queryClient, {
- invalidateSurfaces: false,
- targetRevision: 5,
- })).resolves.toEqual({ revision: 5, readStates: [] })
-
- expect(apiFetch).toHaveBeenCalledTimes(2)
- })
-
- it("retains a live target after a transient snapshot failure and lets a later caller take over", async () => {
- queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
- revision: 4,
- readStates: [],
- })
- seedCommunityReadState(queryClient, "c1", {
- lastReadMessageId: null,
- lastReadAt: null,
- lastReadSeq: 0,
- })
- apiFetch
- .mockRejectedValueOnce(new Error("temporary primary failure"))
- .mockResolvedValueOnce({
- revision: 5,
- readStates: [{
- channelId: "c1",
- lastReadMessageId: "m5",
- lastReadAt: "2026-08-24T00:00:05.000Z",
- lastReadSeq: 5,
- }],
- })
-
- await expect(reconcileAccountReadState(queryClient, {
- invalidateSurfaces: false,
- targetRevision: 5,
- })).rejects.toThrow("temporary primary failure")
-
- await expect(reconcileAccountReadState(queryClient, {
- invalidateSurfaces: false,
- targetRevision: 5,
- })).resolves.toMatchObject({ revision: 5 })
- expect(apiFetch).toHaveBeenCalledTimes(2)
- expect(currentConversationReadState(queryClient, "c1"))
- .toMatchObject({ lastReadSeq: 5 })
- })
-
- it("automatically retries a retained target after the bounded initial backoff", async () => {
- vi.useFakeTimers()
- queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
- revision: 4,
- readStates: [],
- })
- apiFetch
- .mockRejectedValueOnce(new Error("temporary primary failure"))
- .mockResolvedValueOnce({ revision: 5, readStates: [] })
-
- await expect(reconcileAccountReadState(queryClient, {
- invalidateSurfaces: false,
- targetRevision: 5,
- })).rejects.toThrow("temporary primary failure")
- expect(apiFetch).toHaveBeenCalledTimes(1)
-
- await vi.advanceTimersByTimeAsync(100)
- await vi.waitFor(() => expect(queryClient.getQueryData(
- communityKeys.accountReadStateSnapshot(),
- )).toMatchObject({ revision: 5 }))
- expect(apiFetch).toHaveBeenCalledTimes(2)
- vi.useRealTimers()
- })
-
- it("contains a rejected snapshot retry and rearms the next backoff", async () => {
- vi.useFakeTimers()
- queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
- revision: 4,
- readStates: [],
- })
- apiFetch
- .mockRejectedValueOnce(new Error("first snapshot failure"))
- .mockRejectedValueOnce(new Error("second snapshot failure"))
- .mockResolvedValueOnce({ revision: 5, readStates: [] })
-
- await expect(reconcileAccountReadState(queryClient, {
- invalidateSurfaces: false,
- targetRevision: 5,
- })).rejects.toThrow("first snapshot failure")
- await vi.advanceTimersByTimeAsync(100)
- await vi.waitFor(() => expect(apiFetch).toHaveBeenCalledTimes(2))
- await vi.advanceTimersByTimeAsync(200)
- await vi.waitFor(() => expect(queryClient.getQueryData(
- communityKeys.accountReadStateSnapshot(),
- )).toMatchObject({ revision: 5 }))
- expect(apiFetch).toHaveBeenCalledTimes(3)
- vi.useRealTimers()
- })
-
- it("cancels retained retry work on exit without another GET or projection", async () => {
- vi.useFakeTimers()
- queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
- revision: 4,
- readStates: [],
- })
- seedCommunityReadState(queryClient, "c1", {
- lastReadMessageId: null,
- lastReadAt: null,
- lastReadSeq: 0,
- })
- apiFetch
- .mockRejectedValueOnce(new Error("temporary primary failure"))
- .mockResolvedValueOnce({
- revision: 5,
- readStates: [{
- channelId: "c1",
- lastReadMessageId: "m5",
- lastReadAt: "2026-08-24T00:00:05.000Z",
- lastReadSeq: 5,
- }],
- })
-
- await expect(reconcileAccountReadState(queryClient, {
- invalidateSurfaces: false,
- targetRevision: 5,
- })).rejects.toThrow("temporary primary failure")
- disposeAccountReadStateReconciliation(queryClient)
- await vi.advanceTimersByTimeAsync(10_000)
-
- expect(apiFetch).toHaveBeenCalledTimes(1)
- expect(queryClient.getQueryData(communityKeys.accountReadStateSnapshot()))
- .toMatchObject({ revision: 4 })
- expect(currentConversationReadState(queryClient, "c1"))
- .toMatchObject({ lastReadSeq: 0 })
- await expect(reconcileAccountReadState(queryClient, {
- targetRevision: 5,
- })).rejects.toThrow("account read-state reconciliation disposed")
- vi.useRealTimers()
- })
-
- it("aborts and fences an active primary request on exit", async () => {
- queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
- revision: 4,
- readStates: [],
- })
- let release!: (snapshot: AccountReadStateSnapshot) => void
- let requestSignal: AbortSignal | undefined
- apiFetch.mockImplementationOnce((_path: string, options: { signal?: AbortSignal }) => {
- requestSignal = options.signal
- return new Promise<AccountReadStateSnapshot>((resolve) => {
- release = resolve
- })
- })
-
- const worker = reconcileAccountReadState(queryClient, {
- invalidateSurfaces: false,
- targetRevision: 5,
- })
- expect(requestSignal?.aborted).toBe(false)
- disposeAccountReadStateReconciliation(queryClient)
- expect(requestSignal?.aborted).toBe(true)
- release({ revision: 5, readStates: [] })
-
- await expect(worker).rejects.toThrow("account read-state reconciliation disposed")
- expect(queryClient.getQueryData(communityKeys.accountReadStateSnapshot()))
- .toMatchObject({ revision: 4 })
- })
-
- it("retains a real active-query refetch failure until same-revision takeover succeeds", async () => {
- queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
- revision: 4,
- readStates: [],
- })
- apiFetch.mockResolvedValue({
- revision: 5,
- readStates: [],
- })
- let inboxFetches = 0
- const inboxObserver = new QueryObserver(queryClient, {
- queryKey: communityKeys.inbox(),
- queryFn: async () => {
- inboxFetches += 1
- if (inboxFetches === 2) throw new Error("temporary inbox failure")
- return []
- },
- })
- const unsubscribe = inboxObserver.subscribe(() => undefined)
- await vi.waitFor(() => expect(inboxObserver.getCurrentResult().status).toBe("success"))
-
- await expect(reconcileAccountReadState(queryClient, {
- targetRevision: 5,
- })).rejects.toThrow("read-state surface reconciliation failed")
- expect(queryClient.getQueryData(communityKeys.accountReadStateSnapshot()))
- .toMatchObject({ revision: 5 })
- expect(projectReadStateEnvelope(queryClient, {
- revision: 5,
- inboxChanged: true,
- })).toBe("gap")
-
- await expect(reconcileAccountReadState(queryClient, {
- targetRevision: 5,
- })).resolves.toMatchObject({ revision: 5 })
- expect(apiFetch).toHaveBeenCalledTimes(1)
- expect(inboxFetches).toBe(3)
- expect(inboxObserver.getCurrentResult()).toMatchObject({
- status: "success",
- data: [],
- })
- expect(projectReadStateEnvelope(queryClient, {
- revision: 5,
- inboxChanged: true,
- })).toBe("stale")
- unsubscribe()
- })
-
- it("contains a rejected Inbox retry and rearms the next backoff", async () => {
- vi.useFakeTimers()
- apiFetch.mockResolvedValue({ revision: 1, readStates: [] })
- let inboxFetches = 0
- const inboxObserver = new QueryObserver(queryClient, {
- queryKey: communityKeys.inbox(),
- queryFn: async () => {
- inboxFetches += 1
- if (inboxFetches === 2 || inboxFetches === 3) {
- throw new Error("temporary inbox failure")
- }
- return []
- },
- })
- const unsubscribe = inboxObserver.subscribe(() => undefined)
- await vi.waitFor(() => expect(inboxObserver.getCurrentResult().status).toBe("success"))
-
- await expect(reconcileAccountReadState(queryClient, {
- surfaceMode: "inbox-dms",
- targetRevision: 1,
- })).rejects.toThrow("read-state surface reconciliation failed")
- await vi.advanceTimersByTimeAsync(100)
- await vi.waitFor(() => expect(inboxFetches).toBe(3))
- await vi.advanceTimersByTimeAsync(200)
- await vi.waitFor(() => expect(inboxFetches).toBe(4))
-
- expect(inboxObserver.getCurrentResult()).toMatchObject({ status: "success", data: [] })
- unsubscribe()
- vi.useRealTimers()
- })
-
- it("contains failed surface kicks after snapshot recovery and retries both families", async () => {
- vi.useFakeTimers()
- apiFetch
- .mockRejectedValueOnce(new Error("snapshot unavailable"))
- .mockResolvedValueOnce({ revision: 1, readStates: [] })
- let inboxFetches = 0
- const inboxObserver = new QueryObserver(queryClient, {
- queryKey: communityKeys.inbox(),
- queryFn: async () => {
- inboxFetches += 1
- if (inboxFetches === 2) throw new Error("inbox kick failed")
- return []
- },
- })
- let serverFetches = 0
- const serverObserver = new QueryObserver(queryClient, {
- queryKey: communityKeys.server("server-1"),
- queryFn: async () => {
- serverFetches += 1
- if (serverFetches === 2) throw new Error("server kick failed")
- return { id: "server-1" }
- },
- })
- const unsubscribeInbox = inboxObserver.subscribe(() => undefined)
- const unsubscribeServer = serverObserver.subscribe(() => undefined)
- await Promise.all([
- vi.waitFor(() => expect(inboxObserver.getCurrentResult().status).toBe("success")),
- vi.waitFor(() => expect(serverObserver.getCurrentResult().status).toBe("success")),
- ])
-
- await expect(reconcileAccountReadState(queryClient, {
- targetRevision: 1,
- })).rejects.toThrow("snapshot unavailable")
- await vi.advanceTimersByTimeAsync(100)
- await vi.waitFor(() => {
- expect(inboxFetches).toBe(2)
- expect(serverFetches).toBe(2)
- })
- await vi.advanceTimersByTimeAsync(100)
- await vi.waitFor(() => {
- expect(inboxFetches).toBe(3)
- expect(serverFetches).toBe(3)
- })
-
- unsubscribeInbox()
- unsubscribeServer()
- vi.useRealTimers()
+vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => apiFetch(...args) }))
+let owner: Awaited<ReturnType<typeof createCommunityQueryOwner>>
+const row = (seq: number) => ({ channelId: "c1", lastReadMessageId: `m${seq}`, lastReadAt: `2026-10-27T00:00:0${seq}.000Z`, lastReadSeq: seq })
+const snapshot = (revision: number, seq = revision) => ({ revision, readStates: [row(seq)] })
+const attention = { scopes: [], items: [], limit: 100, truncated: false, included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } }
+function deferred<T>() { let resolve!: (value: T) => void; const promise = new Promise<T>(done => { resolve = done }); return { promise, resolve } }
+beforeEach(async () => { apiFetch.mockReset(); owner = await createCommunityQueryOwner(); apiFetch.mockImplementation(async (path: string) => path.endsWith("/attention") ? attention : snapshot(1)) })
+afterEach(async () => { await owner.client.cancelQueries(); await owner.registry.cleanup(); owner.client.clear(); vi.useRealTimers() })
+
+describe("native account read-state reconciliation", () => {
+ it("publishes canonical cursors and caches only the transport revision", async () => {
+ await reconcileAccountReadState(owner.client)
+ expect(currentConversationReadState(owner.client, "c1")).toMatchObject(row(1))
+ expect(owner.client.getQueryData(communityKeys.accountReadStateSnapshot())).toEqual({ revision: 1 })
+ expect(apiFetch.mock.calls.map(([path]) => path)).toEqual(["/api/community/users/me/read-state", "/api/community/users/me/attention", "/api/community/users/me/attention"])
+ expect(projectReadStateEnvelope(owner.client, { revision: 1, inboxChanged: true })).toBe("stale")
+ expect(projectReadStateEnvelope(owner.client, { revision: 2, inboxChanged: true })).toBe("gap")
+ })
+
+ it("shares both native transports without a second attention read when the confirmed revision stays current", async () => {
+ await reconcileAccountReadState(owner.client, { reconcileAttention: false })
+ apiFetch.mockClear()
+ await Promise.all([reconcileAccountReadState(owner.client), reconcileAccountReadState(owner.client)])
+ expect(apiFetch.mock.calls.map(([path]) => path)).toEqual(["/api/community/users/me/read-state", "/api/community/users/me/attention"])
+ })
+
+ it("rechecks an early attention count only after a held read-state advances its confirmed revision", async () => {
+ const gate = deferred<ReturnType<typeof snapshot>>()
+ let attentionReads = 0
+ apiFetch.mockImplementation(async (path: string) => path.endsWith("/read-state") ? gate.promise : {
+ ...attention,
+ scopes: [{ scopeId: "c1", channelId: "c1", serverId: null, parentChannelId: null, ordinaryUnread: true, lastUnreadSeq: 5, unreadCount: ++attentionReads === 1 ? 5 : 3, attentionCount: 0, lastAttentionSeq: null }],
+ included: { ...attention.included, dms: [{ id: "c1", userId: "peer", name: "Peer", discriminator: "0002", avatar: "P", avatarVersion: 0, lastMessageAt: "2026-10-27T00:00:05.000Z", lastUnreadSeq: 5 }], profiles: [{ userId: "peer", name: "Peer", discriminator: "0002", avatar: "P", avatarVersion: 0 }] },
+ })
+ const outcome = reconcileAccountReadState(owner.client).then(() => null, error => error)
+ try {
+ await vi.waitFor(() => expect(owner.registry.collections.attentionScopes.get("c1")?.unreadCount).toBe(5))
+ } finally {
+ gate.resolve(snapshot(3, 2))
+ expect(await outcome).toBeNull()
+ }
+ expect(owner.registry.collections.readStates.get("c1")?.lastReadSeq).toBe(2)
+ expect(owner.registry.collections.attentionScopes.get("c1")).toMatchObject({ lastUnreadSeq: 5, unreadCount: 3 })
+ expect(attentionReads).toBe(2)
})
- it("coalesces repeated live hints into one retry worker without a request storm", async () => {
- queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
- revision: 4,
- readStates: [],
- })
- let release!: (snapshot: AccountReadStateSnapshot) => void
- apiFetch.mockReturnValue(new Promise<AccountReadStateSnapshot>((resolve) => {
- release = resolve
- }))
-
- const workers = Array.from({ length: 12 }, () => reconcileAccountReadState(queryClient, {
- invalidateSurfaces: false,
- targetRevision: 5,
- }))
- expect(apiFetch).toHaveBeenCalledTimes(1)
- release({ revision: 5, readStates: [] })
- await expect(Promise.all(workers)).resolves.toHaveLength(12)
- expect(apiFetch).toHaveBeenCalledTimes(1)
+ it("joins simultaneous reads through the original native Query", async () => {
+ const gate = deferred<ReturnType<typeof snapshot>>()
+ apiFetch.mockReturnValue(gate.promise)
+ const first = reconcileAccountReadState(owner.client, { reconcileAttention: false })
+ const second = reconcileAccountReadState(owner.client, { reconcileAttention: false })
+ expect(apiFetch).toHaveBeenCalledOnce()
+ gate.resolve(snapshot(2))
+ expect((await Promise.all([first, second])).map(value => value.revision)).toEqual([2, 2])
+ expect(apiFetch).toHaveBeenCalledOnce()
})
- it("lets post-PUT consumption finish on Inbox/DM while server retry stays independent", async () => {
+ it("retries an old in-flight snapshot against a later revision target without publishing it", async () => {
vi.useFakeTimers()
- queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
- revision: 4,
- readStates: [],
- })
- apiFetch.mockResolvedValue({ revision: 5, readStates: [] })
-
- let inboxFetches = 0
- const inboxObserver = new QueryObserver(queryClient, {
- queryKey: communityKeys.inbox(),
- queryFn: async () => {
- inboxFetches += 1
- return []
- },
- })
- const unsubscribeInbox = inboxObserver.subscribe(() => undefined)
-
- let serverFetches = 0
- const serverObserver = new QueryObserver(queryClient, {
- queryKey: communityKeys.server("server-1"),
- queryFn: async () => {
- serverFetches += 1
- if (serverFetches === 2) throw new Error("temporary server detail failure")
- return { id: "server-1" }
- },
- })
- const unsubscribeServer = serverObserver.subscribe(() => undefined)
- await Promise.all([
- vi.waitFor(() => expect(inboxObserver.getCurrentResult().status).toBe("success")),
- vi.waitFor(() => expect(serverObserver.getCurrentResult().status).toBe("success")),
- ])
-
- await expect(reconcileAccountReadState(queryClient, {
- surfaceMode: "all",
- awaitSurfaceMode: "inbox-dms",
- targetRevision: 5,
- })).resolves.toMatchObject({ revision: 5 })
- await vi.waitFor(() => expect(serverFetches).toBe(2))
- expect(inboxFetches).toBe(2)
- expect(projectReadStateEnvelope(queryClient, {
- revision: 5,
- inboxChanged: true,
- })).toBe("stale")
-
- await vi.advanceTimersByTimeAsync(100)
- await vi.waitFor(() => expect(serverFetches).toBe(3))
- expect(inboxFetches).toBe(2)
-
- unsubscribeInbox()
- unsubscribeServer()
- vi.useRealTimers()
- })
-
- it("advances the snapshot and runs a second derived pass during invalidation", async () => {
- queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
- revision: 4,
- readStates: [],
- })
- apiFetch
- .mockResolvedValueOnce({ revision: 5, readStates: [] })
- .mockResolvedValueOnce({ revision: 6, readStates: [] })
- let releaseSurface!: () => void
- const surfaceGate = new Promise<void>((resolve) => {
- releaseSurface = resolve
- })
- const invalidate = vi.spyOn(queryClient, "invalidateQueries")
- invalidate.mockReturnValueOnce(surfaceGate).mockResolvedValue(undefined)
-
- const first = reconcileAccountReadState(queryClient, { targetRevision: 5 })
- await vi.waitFor(() => expect(invalidate).toHaveBeenCalledTimes(3))
- const second = reconcileAccountReadState(queryClient, { targetRevision: 6 })
- await vi.waitFor(() => expect(apiFetch).toHaveBeenCalledTimes(2))
-
- releaseSurface()
- await expect(Promise.all([first, second])).resolves.toEqual([
- { revision: 6, readStates: [] },
- { revision: 6, readStates: [] },
- ])
+ const gate = deferred<ReturnType<typeof snapshot>>()
+ apiFetch.mockReturnValueOnce(gate.promise).mockResolvedValue(snapshot(5))
+ const first = reconcileAccountReadState(owner.client, { targetRevision: 2, reconcileAttention: false })
+ const second = reconcileAccountReadState(owner.client, { targetRevision: 5, reconcileAttention: false })
+ gate.resolve(snapshot(2))
+ await vi.advanceTimersByTimeAsync(0)
+ expect(owner.registry.collections.readStates.get("c1")?.lastReadSeq).not.toBe(2)
+ await vi.advanceTimersByTimeAsync(1_000)
+ expect((await Promise.all([first, second])).map(value => value.revision)).toEqual([5, 5])
expect(apiFetch).toHaveBeenCalledTimes(2)
- expect(invalidate).toHaveBeenCalledTimes(6)
})
- it("keeps a necessary cold deadline terminal through retained surface work", async () => {
+ it("reads the newer target when it arrives during native successful-result publication", async () => {
vi.useFakeTimers()
- apiFetch.mockResolvedValue({ revision: 1, readStates: [] })
- let reads = 0
- const observer = new QueryObserver(queryClient, {
- queryKey: communityKeys.server("cold"),
- queryFn: ({ signal }) => {
- reads += 1
- return withConversationReadDeadline(signal, () => new Promise<never>(() => {}))
- },
- retryOnMount: false,
- })
- const unsubscribe = observer.subscribe(() => {})
- const failure = reconcileAccountReadState(queryClient, { surfaceMode: "non-inbox", targetRevision: 1 })
- .catch((error: unknown) => error)
- await vi.advanceTimersByTimeAsync(15_000)
- const error = await failure
- expect(error).toBeInstanceOf(AggregateError)
- expect((error as AggregateError).errors).toEqual([expect.any(ConversationReadTimeoutError)])
- expect(observer.getCurrentResult()).toMatchObject({ status: "error", fetchStatus: "idle", data: undefined })
- expect(queryClient.getQueryData(communityKeys.accountReadStateSnapshot())).toMatchObject({ revision: 1 })
- await vi.advanceTimersByTimeAsync(20_000)
- await expect(reconcileAccountReadState(queryClient, { surfaceMode: "non-inbox", targetRevision: 1 }))
- .rejects.toThrow("read-state surface reconciliation failed")
- expect(reads).toBe(1)
- expect(apiFetch).toHaveBeenCalledTimes(1)
- unsubscribe()
- disposeAccountReadStateReconciliation(queryClient)
- vi.useRealTimers()
- })
-
- it("retries only failed cached targets beside a terminal cold target", async () => {
- vi.useFakeTimers()
- apiFetch.mockResolvedValue({ revision: 1, readStates: [] })
- const reads = { cold: 0, cached: 0, healthy: 0 }
- const observers = [
- new QueryObserver(queryClient, {
- queryKey: communityKeys.server("cold"),
- queryFn: ({ signal }) => {
- reads.cold += 1
- return withConversationReadDeadline(signal, () => new Promise<never>(() => {}))
- },
- }),
- new QueryObserver(queryClient, {
- queryKey: communityKeys.server("cached"),
- initialData: { id: "cached" },
- staleTime: Infinity,
- queryFn: async () => {
- reads.cached += 1
- if (reads.cached === 1) throw new Error("temporary cached failure")
- return { id: "cached" }
- },
- }),
- new QueryObserver(queryClient, {
- queryKey: communityKeys.server("healthy"),
- initialData: { id: "healthy" },
- staleTime: Infinity,
- queryFn: async () => { reads.healthy += 1; return { id: "healthy" } },
- }),
- ]
- const unsubscribes = observers.map((observer) => observer.subscribe(() => {}))
- const failure = reconcileAccountReadState(queryClient, { surfaceMode: "non-inbox", targetRevision: 1 })
- .catch((error: unknown) => error)
- await vi.advanceTimersByTimeAsync(15_000)
- const error = await failure
- expect((error as AggregateError).errors).toEqual(expect.arrayContaining([
- expect.any(ConversationReadTimeoutError), expect.objectContaining({ message: "temporary cached failure" }),
- ]))
- await vi.advanceTimersByTimeAsync(100)
- expect(reads).toEqual({ cold: 1, cached: 2, healthy: 1 })
- expect(observers[0]!.getCurrentResult()).toMatchObject({ status: "error", fetchStatus: "idle" })
- expect(observers[1]!.getCurrentResult().status).toBe("success")
- await vi.advanceTimersByTimeAsync(20_000)
- expect(reads).toEqual({ cold: 1, cached: 2, healthy: 1 })
- unsubscribes.forEach((unsubscribe) => unsubscribe())
- disposeAccountReadStateReconciliation(queryClient)
- vi.useRealTimers()
- })
-
- it.each(["native Retry", "new authoritative generation"])("recovers cold pending work through %s", async (recovery) => {
- vi.useFakeTimers()
- apiFetch.mockImplementation(async () => ({ revision: apiFetch.mock.calls.length, readStates: [] }))
- let reads = 0
- const observer = new QueryObserver(queryClient, {
- queryKey: communityKeys.server("cold"),
- queryFn: ({ signal }) => {
- reads += 1
- return reads === 1
- ? withConversationReadDeadline(signal, () => new Promise<never>(() => {}))
- : Promise.resolve({ id: "cold" })
- },
- })
- const unsubscribe = observer.subscribe(() => {})
- const failure = reconcileAccountReadState(queryClient, { surfaceMode: "non-inbox", targetRevision: 1 })
- .catch((error: unknown) => error)
- await vi.advanceTimersByTimeAsync(15_000)
- expect(await failure).toBeInstanceOf(AggregateError)
- if (recovery === "native Retry") await observer.refetch({ cancelRefetch: false })
- await expect(reconcileAccountReadState(queryClient, {
- surfaceMode: "non-inbox", targetRevision: recovery === "native Retry" ? 1 : 2,
- })).resolves.toMatchObject({ revision: recovery === "native Retry" ? 1 : 2 })
- expect(reads).toBe(2)
- expect(observer.getCurrentResult().status).toBe("success")
- await vi.advanceTimersByTimeAsync(10_000)
- expect(reads).toBe(2)
- unsubscribe()
- disposeAccountReadStateReconciliation(queryClient)
- vi.useRealTimers()
- })
-
- it.each(["removed", "replaced", "inactive", "disposed", "account", "access"])("does not revive a %s retry target", async (retirement) => {
- vi.useFakeTimers()
- apiFetch.mockResolvedValue({ revision: 1, readStates: [] })
- let reads = 0
- const observer = new QueryObserver(queryClient, {
- queryKey: communityKeys.server("cached"),
- initialData: { id: "cached" },
- staleTime: Infinity,
- queryFn: async () => { reads += 1; throw new Error("temporary failure") },
- })
- const unsubscribe = observer.subscribe(() => {})
- await expect(reconcileAccountReadState(queryClient, { surfaceMode: "non-inbox", targetRevision: 1 }))
- .rejects.toThrow("read-state surface reconciliation failed")
- let replacementUnsubscribe: (() => void) | undefined
- const replacementRead = vi.fn(async () => ({ id: "replacement" }))
- if (retirement === "disposed") disposeAccountReadStateReconciliation(queryClient)
- else if (retirement === "inactive") unsubscribe()
- else if (retirement === "account") createCommunityDbRegistry(queryClient, "viewer").runtime.ws.actions.activateProfileAccount("next-viewer")
- else if (retirement === "access") createCommunityDbRegistry(queryClient, "viewer").runtime.ws.setState((state) => ({ ...state, accessEpoch: state.accessEpoch + 1 }))
- else {
- queryClient.removeQueries({ queryKey: communityKeys.server("cached"), exact: true })
- if (retirement === "replaced") {
- const replacement = new QueryObserver(queryClient, {
- queryKey: communityKeys.server("cached"),
- initialData: { id: "replacement" },
- staleTime: Infinity,
- queryFn: replacementRead,
- })
- replacementUnsubscribe = replacement.subscribe(() => {})
+ const newer = deferred<ReturnType<typeof snapshot>>()
+ apiFetch.mockResolvedValueOnce(snapshot(2)).mockReturnValueOnce(newer.promise).mockResolvedValue(snapshot(5))
+ let second: ReturnType<typeof reconcileAccountReadState> | undefined
+ const unsubscribe = owner.client.getQueryCache().subscribe(event => {
+ if (event.type === "updated" && event.action.type === "success"
+ && event.query.queryHash === owner.client.getQueryCache().find({ queryKey: communityKeys.accountReadStateSnapshot(), exact: true })?.queryHash
+ && (event.query.state.data as { revision?: number } | undefined)?.revision === 2) {
+ second = reconcileAccountReadState(owner.client, { targetRevision: 5, reconcileAttention: false })
}
- }
- await vi.advanceTimersByTimeAsync(10_000)
- expect(reads).toBe(1)
- expect(replacementRead).not.toHaveBeenCalled()
- if (retirement === "removed") expect(queryClient.getQueryState(communityKeys.server("cached"))).toBeUndefined()
- if (retirement === "replaced") expect(queryClient.getQueryData(communityKeys.server("cached"))).toEqual({ id: "replacement" })
- if (retirement === "inactive") {
- await expect(reconcileAccountReadState(queryClient, { surfaceMode: "non-inbox", targetRevision: 1 }))
- .rejects.toThrow("read-state surface reconciliation failed")
- expect(reads).toBe(1)
- }
- unsubscribe()
- replacementUnsubscribe?.()
- disposeAccountReadStateReconciliation(queryClient)
- vi.useRealTimers()
- })
-
- it("joins an explicit Retry without cancelling its in-flight cached read", async () => {
- vi.useFakeTimers()
- apiFetch.mockResolvedValue({ revision: 1, readStates: [] })
- let reads = 0
- let release!: (data: { id: string }) => void
- let retrySignal: AbortSignal | undefined
- const observer = new QueryObserver(queryClient, {
- queryKey: communityKeys.server("cached"),
- initialData: { id: "cached" },
- staleTime: Infinity,
- queryFn: ({ signal }) => {
- reads += 1
- if (reads === 1) return Promise.reject(new Error("temporary background failure"))
- retrySignal = signal
- return new Promise<{ id: string }>((resolve) => { release = resolve })
- },
})
- const unsubscribe = observer.subscribe(() => {})
- await expect(reconcileAccountReadState(queryClient, { surfaceMode: "non-inbox", targetRevision: 1 }))
- .rejects.toThrow("read-state surface reconciliation failed")
- const retry = observer.refetch({ cancelRefetch: false })
- await vi.advanceTimersByTimeAsync(100)
- expect(reads).toBe(2)
- expect(retrySignal?.aborted).toBe(false)
- release({ id: "recovered" })
- await retry
- await vi.advanceTimersByTimeAsync(100)
- expect(observer.getCurrentResult()).toMatchObject({ status: "success", data: { id: "recovered" } })
- expect(reads).toBe(2)
- unsubscribe()
- disposeAccountReadStateReconciliation(queryClient)
- vi.useRealTimers()
+ const first = reconcileAccountReadState(owner.client, { targetRevision: 2, reconcileAttention: false })
+ try {
+ await vi.advanceTimersByTimeAsync(0)
+ expect(apiFetch).toHaveBeenCalledTimes(2)
+ newer.resolve(snapshot(3))
+ await vi.advanceTimersByTimeAsync(1_000)
+ expect((await Promise.all([first, second!])).map(value => value.revision)).toEqual([5, 5])
+ expect(apiFetch).toHaveBeenCalledTimes(3)
+ expect(owner.registry.collections.readStates.get("c1")?.lastReadSeq).toBe(5)
+ } finally {
+ unsubscribe()
+ newer.resolve(snapshot(5))
+ await Promise.allSettled([first, second])
+ }
})
- it("keeps access failure dirty without retrying it on a read-state revision", async () => {
- vi.useFakeTimers()
- apiFetch.mockImplementation(async () => ({ revision: apiFetch.mock.calls.length, readStates: [] }))
- const denied = Object.assign(new Error("Forbidden"), { status: 403 })
- const read = vi.fn(async () => { throw denied })
- const observer = new QueryObserver(queryClient, {
- queryKey: communityKeys.server("denied"),
- initialData: { id: "denied" },
- staleTime: Infinity,
- queryFn: read,
- })
- const unsubscribe = observer.subscribe(() => {})
- await expect(reconcileAccountReadState(queryClient, { surfaceMode: "non-inbox", targetRevision: 1 }))
- .rejects.toMatchObject({ errors: [denied] })
- await vi.advanceTimersByTimeAsync(10_000)
- await expect(reconcileAccountReadState(queryClient, { surfaceMode: "non-inbox", targetRevision: 2 }))
- .rejects.toMatchObject({ errors: [denied] })
- expect(read).toHaveBeenCalledOnce()
- expect(queryClient.getQueryData(communityKeys.accountReadStateSnapshot())).toMatchObject({ revision: 2 })
- unsubscribe()
- disposeAccountReadStateReconciliation(queryClient)
- vi.useRealTimers()
+ it("preserves a newer confirmed ACK floor across an older full snapshot", async () => {
+ publishCommunityConversationReadState(owner.client, row(7), 7, { token: captureCommunityLiveSnapshotToken(owner.client), signal: undefined })
+ apiFetch.mockResolvedValue(snapshot(6))
+ await reconcileAccountReadState(owner.client, { reconcileAttention: false })
+ expect(currentConversationReadState(owner.client, "c1")).toMatchObject(row(7))
+ expect(owner.registry.collections.readStateClock.get("account")?.revision).toBe(6)
+ })
+
+ it.each(["query", "account", "access", "owner"] as const)("rejects an ignored-abort response after original %s retirement", async (kind) => {
+ const gate = deferred<ReturnType<typeof snapshot>>()
+ apiFetch.mockReturnValue(gate.promise)
+ const pending = reconcileAccountReadState(owner.client, { reconcileAttention: false }).catch(error => error)
+ if (kind === "query") owner.client.removeQueries({ queryKey: communityKeys.accountReadStateSnapshot(), exact: true })
+ if (kind === "account") owner.runtime.ws.actions.activateProfileAccount("different")
+ if (kind === "access") owner.runtime.ws.actions.revokeChannelAccess("s1", "c1")
+ if (kind === "owner") disposeAccountReadStateReconciliation(owner.client)
+ gate.resolve(snapshot(8))
+ expect(await pending).toBeInstanceOf(Error)
+ expect(owner.registry.collections.readStates.get("c1")).toBeUndefined()
+ })
+
+ it("reports a transport failure without blocking later lifecycle reconciliation", async () => {
+ apiFetch.mockRejectedValueOnce(new Error("offline")).mockResolvedValue(snapshot(3))
+ await expect(reconcileAccountReadState(owner.client, { targetRevision: 3, reconcileAttention: false })).rejects.toThrow("offline")
+ expect(owner.client.getQueryState(communityKeys.accountReadStateSnapshot())?.status).toBe("error")
+ expect((await reconcileAccountReadState(owner.client, { targetRevision: 3, reconcileAttention: false })).revision).toBe(3)
+ expect(apiFetch).toHaveBeenCalledTimes(2)
})
})
diff --git a/src/web/src/hooks/community/community-ws/read-state-reconciliation.ts b/src/web/src/hooks/community/community-ws/read-state-reconciliation.ts
index 6a7375969..e5b60488a 100644
--- a/src/web/src/hooks/community/community-ws/read-state-reconciliation.ts
+++ b/src/web/src/hooks/community/community-ws/read-state-reconciliation.ts
@@ -1,575 +1,102 @@
import type { queries, CommunityInboxChanged } from "@alook/shared"
+import { CancelledError, queryOptions, useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query"
import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle"
-import { notifyManager, type Query, type QueryClient, type QueryKey } from "@tanstack/react-query"
import { apiFetch } from "@/lib/api/client"
-import {
- communityKeys,
- isCommunityServerDetailQueryKey,
-} from "@/lib/query-keys"
+import { communityKeys } from "@/lib/query-keys"
import { projectReadCoordinatorSnapshot } from "@/hooks/community/read-coordinator-snapshot-projection"
-import { acceptAccountUnreadPrimarySnapshot } from "@/hooks/community/account-unread-projection"
-import { assertCommunityLiveSnapshotTokenCurrent, captureCommunityLiveSnapshotToken, publishCommunityLiveSnapshot, type CommunityLiveSnapshotToken } from "@/lib/community-db/sync"
-import { isConversationAccessError } from "@/lib/community/conversation-read"
+import { beginCommunityCommandRevision, assertCommunityLiveSnapshotTokenCurrent, captureCommunityLiveSnapshotToken, publishCommunityLiveSnapshot } from "@/lib/community-db/sync"
+import { getCommunityDbRegistry } from "@/lib/community-db/collections"
+import { conversationReadRetryPolicy, isConversationAccessError } from "@/lib/community/conversation-read"
+import { isAbortError } from "@/lib/errors"
+import { accountAttentionMatchesReadState, reconcileAccountAttention } from "@/hooks/community/use-account-attention"
export type AccountReadStateSnapshot = Awaited<ReturnType<typeof queries.communityReadState.getAccountReadStateSnapshot>>
-
export type ReadStateEnvelope = Pick<CommunityInboxChanged, "revision" | "inboxChanged">
-type ServerSurfaceTarget = {
- queryKey: QueryKey
- query: Query | undefined
- failed: boolean
- error: unknown
-}
-
-type ServerSurfaceWork = {
- generation: number
- targets: ServerSurfaceTarget[]
- owner: CommunityLiveSnapshotToken
-}
-
-type ReconciliationState = {
- highestPendingTargetRevision: number | null
- snapshotRequestedGeneration: number
- snapshotCompletedGeneration: number
- inboxDmsRequestedGeneration: number
- inboxDmsCompletedGeneration: number
- serverRequestedGeneration: number
- serverCompletedGeneration: number
- snapshotWorker: Promise<AccountReadStateSnapshot> | null
- inboxDmsWorker: Promise<void> | null
- serverWorker: Promise<void> | null
- serverSurfaceWork: ServerSurfaceWork | null
- snapshotRetryTimer: ReturnType<typeof setTimeout> | null
- snapshotRetryDelayMs: number
- inboxDmsRetryTimer: ReturnType<typeof setTimeout> | null
- inboxDmsRetryDelayMs: number
- serverRetryTimer: ReturnType<typeof setTimeout> | null
- serverRetryDelayMs: number
- requestController: AbortController | null
- epoch: number
- disposed: boolean
-}
-
-export type ReadStateSurfaceMode = "all" | "inbox-dms" | "non-inbox" | "none"
-
-const INITIAL_RETRY_DELAY_MS = 100
-const MAX_RETRY_DELAY_MS = 5_000
-const reconciliationStates = new WeakMap<QueryClient, ReconciliationState>()
-const disposedReconciliationClients = new WeakSet<QueryClient>()
-
-function applyAccountReadStateSnapshot(
- queryClient: QueryClient,
- snapshot: AccountReadStateSnapshot,
- proof: {
- token: CommunityLiveSnapshotToken
- signal: AbortSignal
- requestGeneration: number
- currentRequestGeneration: number
- targetRevision: number | null
- },
-) {
- const publication = publishCommunityLiveSnapshot(queryClient, {
- snapshot: { kind: "read-state", data: snapshot },
- proof: { kind: "read-state", ...proof },
- })
- if (publication === "superseded") return "superseded" as const
- const current = queryClient.getQueryData<AccountReadStateSnapshot>(
- communityKeys.accountReadStateSnapshot(),
- )
- if (current && snapshot.revision < current.revision) return "stale" as const
- if (current?.revision === snapshot.revision) {
- // Same revision is the same authoritative account snapshot by contract.
- // but do not trigger a second round of derived-surface refetches when
- // concurrent auth/live reconciliations joined the same HTTP request.
- projectReadCoordinatorSnapshot(queryClient, snapshot)
- acceptAccountUnreadPrimarySnapshot(queryClient, snapshot)
- return "stale" as const
- }
- notifyManager.batch(() => {
- queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), snapshot)
- projectReadCoordinatorSnapshot(queryClient, snapshot)
- acceptAccountUnreadPrimarySnapshot(queryClient, snapshot)
- })
- return "applied" as const
-}
-
-async function invalidateInboxDmsSurfaces(queryClient: QueryClient) {
- const refetchOptions = { throwOnError: true, cancelRefetch: true }
- const settled = await Promise.allSettled([
- queryClient.invalidateQueries(
- { queryKey: communityKeys.inbox(), refetchType: "active" },
- refetchOptions,
- ),
- queryClient.invalidateQueries(
- { queryKey: communityKeys.dms(), refetchType: "active" },
- refetchOptions,
- ),
- ])
- if (settled.some((result) => result.status === "rejected")) {
- throw new Error("read-state Inbox/DM reconciliation failed")
- }
-}
-
-function captureServerSurfaceWork(queryClient: QueryClient, generation: number): ServerSurfaceWork {
- const keys: QueryKey[] = [communityKeys.servers()]
- for (const query of queryClient.getQueryCache().getAll()) {
- const key = query.queryKey
- if (isCommunityServerDetailQueryKey(key)) keys.push(key)
- }
- return { generation, owner: captureCommunityLiveSnapshotToken(queryClient), targets: keys.map((queryKey) => {
- const query = queryClient.getQueryCache().find({ queryKey, exact: true })
- return { queryKey, query,
- failed: isConversationAccessError(query?.state.error),
- error: query?.state.error,
- }
- }) }
-}
-
-function isOriginalServerSurface(queryClient: QueryClient, target: ServerSurfaceTarget) {
- return target.query !== undefined
- && queryClient.getQueryCache().get(target.query.queryHash) === target.query
-}
-
-function canRetryServerSurface(queryClient: QueryClient, target: ServerSurfaceTarget) {
- const query = target.query
- return isOriginalServerSurface(queryClient, target) && query !== undefined
- && query.isActive()
- && !isConversationAccessError(query.state.error ?? target.error)
- && !(query.state.data === undefined && query.state.status === "error")
-}
-
-async function invalidateServerSurfaces(queryClient: QueryClient, work: ServerSurfaceWork) {
- assertCommunityLiveSnapshotTokenCurrent(queryClient, work.owner, undefined)
- work.targets = work.targets.filter((target) => !target.failed || (
- isOriginalServerSurface(queryClient, target)
- && target.query?.state.status !== "success"
- ))
- const attempted = work.targets.filter((target) => !target.failed || canRetryServerSurface(queryClient, target))
- const refetchOptions = { throwOnError: true, cancelRefetch: true }
- const settled = await Promise.allSettled(attempted.map((target) => {
- assertCommunityLiveSnapshotTokenCurrent(queryClient, work.owner, undefined)
- return queryClient.invalidateQueries({
- queryKey: target.queryKey,
- exact: true,
- refetchType: "active",
- predicate: (query) => query === target.query,
- }, target.failed ? { ...refetchOptions, cancelRefetch: false } : refetchOptions)
- }))
- settled.forEach((result, index) => {
- const target = attempted[index]!
- if (result.status === "rejected") {
- target.failed = true
- target.error = result.reason
- } else {
- work.targets = work.targets.filter((pending) => pending !== target)
- }
- })
- if (work.targets.length > 0) {
- throw new AggregateError(work.targets.map((target) => target.error), "read-state surface reconciliation failed")
- }
-}
-
-export async function reconcileAccountReadState(
- queryClient: QueryClient,
- options: {
- invalidateSurfaces?: boolean
- surfaceMode?: ReadStateSurfaceMode
- awaitSurfaceMode?: ReadStateSurfaceMode
- targetRevision?: number
- } = {},
-) {
- if (disposedReconciliationClients.has(queryClient)) {
- throw new Error("account read-state reconciliation disposed")
- }
- const state = getReconciliationState(queryClient)
- const currentRevision = cachedAccountRevision(queryClient)
- const targetRevision = options.targetRevision
- const hadSnapshotWork = hasSnapshotWork(state, currentRevision)
-
- if (targetRevision === undefined) {
- // Coalesce concurrent lifecycle callers into the already-pending primary
- // read, but make a later lifecycle event take ownership of a failed worker
- // whose target/dirty state is still queued.
- if (!hadSnapshotWork) state.snapshotRequestedGeneration += 1
- } else if (
- targetRevision > currentRevision
- && (state.highestPendingTargetRevision === null
- || targetRevision > state.highestPendingTargetRevision)
- ) {
- state.highestPendingTargetRevision = targetRevision
- state.snapshotRequestedGeneration += 1
- }
-
- const surfaceMode = options.invalidateSurfaces === false
- ? "none"
- : (options.surfaceMode ?? "all")
- const awaitSurfaceMode = options.awaitSurfaceMode ?? surfaceMode
- const requestedGeneration = state.snapshotRequestedGeneration
- if (surfaceMode === "all" || surfaceMode === "inbox-dms") {
- state.inboxDmsRequestedGeneration = Math.max(
- state.inboxDmsRequestedGeneration,
- requestedGeneration,
- )
- }
- if (surfaceMode === "all" || surfaceMode === "non-inbox") {
- state.serverRequestedGeneration = Math.max(
- state.serverRequestedGeneration,
- requestedGeneration,
- )
- }
-
- clearReconciliationRetry(state, "snapshot")
- if (awaitSurfaceMode === "all" || awaitSurfaceMode === "inbox-dms") {
- clearReconciliationRetry(state, "inbox-dms")
- }
- if (awaitSurfaceMode === "all" || awaitSurfaceMode === "non-inbox") {
- clearReconciliationRetry(state, "non-inbox")
- }
- await ensureSnapshotWorker(queryClient, state)
- const inboxWorker = surfaceMode === "all" || surfaceMode === "inbox-dms"
- ? ensureInboxDmsWorker(queryClient, state)
- : null
- const serverWorker = surfaceMode === "all" || surfaceMode === "non-inbox"
- ? ensureServerWorker(queryClient, state)
- : null
- const awaited: Promise<void>[] = []
- if (awaitSurfaceMode === "all" || awaitSurfaceMode === "inbox-dms") {
- awaited.push(inboxWorker ?? ensureInboxDmsWorker(queryClient, state))
- } else {
- void inboxWorker?.catch(() => undefined)
- }
- if (awaitSurfaceMode === "all" || awaitSurfaceMode === "non-inbox") {
- awaited.push(serverWorker ?? ensureServerWorker(queryClient, state))
- } else {
- void serverWorker?.catch(() => undefined)
- }
- await Promise.all(awaited)
- const snapshot = queryClient.getQueryData<AccountReadStateSnapshot>(
- communityKeys.accountReadStateSnapshot(),
- )
- if (!snapshot) throw new Error("account read-state reconciliation produced no snapshot")
- return snapshot
-}
-
-function getReconciliationState(queryClient: QueryClient) {
- const current = reconciliationStates.get(queryClient)
- if (current) return current
- const created: ReconciliationState = {
- highestPendingTargetRevision: null,
- snapshotRequestedGeneration: 0,
- snapshotCompletedGeneration: 0,
- inboxDmsRequestedGeneration: 0,
- inboxDmsCompletedGeneration: 0,
- serverRequestedGeneration: 0,
- serverCompletedGeneration: 0,
- snapshotWorker: null,
- inboxDmsWorker: null,
- serverWorker: null,
- serverSurfaceWork: null,
- snapshotRetryTimer: null,
- snapshotRetryDelayMs: INITIAL_RETRY_DELAY_MS,
- inboxDmsRetryTimer: null,
- inboxDmsRetryDelayMs: INITIAL_RETRY_DELAY_MS,
- serverRetryTimer: null,
- serverRetryDelayMs: INITIAL_RETRY_DELAY_MS,
- requestController: null,
- epoch: 0,
- disposed: false,
- }
- reconciliationStates.set(queryClient, created)
- return created
-}
-
-function cachedAccountRevision(queryClient: QueryClient) {
- return queryClient.getQueryData<AccountReadStateSnapshot>(
- communityKeys.accountReadStateSnapshot(),
- )?.revision ?? -1
-}
-
-function hasSnapshotWork(state: ReconciliationState, currentRevision: number) {
- return (
- state.snapshotCompletedGeneration < state.snapshotRequestedGeneration
- || (state.highestPendingTargetRevision !== null
- && currentRevision < state.highestPendingTargetRevision)
- )
-}
-
-function hasInboxDmsWork(state: ReconciliationState) {
- return state.inboxDmsCompletedGeneration < state.inboxDmsRequestedGeneration
-}
-
-function hasServerWork(state: ReconciliationState) {
- return state.serverCompletedGeneration < state.serverRequestedGeneration
-}
-
-type RetryFamily = "snapshot" | "inbox-dms" | "non-inbox"
-
-function hasFamilyWork(
- queryClient: QueryClient,
- state: ReconciliationState,
- family: RetryFamily,
-) {
- if (family === "snapshot") {
- return hasSnapshotWork(state, cachedAccountRevision(queryClient))
- }
- return family === "inbox-dms" ? hasInboxDmsWork(state) : hasServerWork(state)
-}
-
-function clearReconciliationRetry(state: ReconciliationState, family: RetryFamily) {
- const timer = family === "snapshot"
- ? state.snapshotRetryTimer
- : family === "inbox-dms"
- ? state.inboxDmsRetryTimer
- : state.serverRetryTimer
- if (timer !== null) clearTimeout(timer)
- if (family === "snapshot") state.snapshotRetryTimer = null
- else if (family === "inbox-dms") state.inboxDmsRetryTimer = null
- else state.serverRetryTimer = null
-}
-
-function scheduleReconciliationRetry(
- queryClient: QueryClient,
- state: ReconciliationState,
- family: RetryFamily,
-) {
- const timer = family === "snapshot"
- ? state.snapshotRetryTimer
- : family === "inbox-dms"
- ? state.inboxDmsRetryTimer
- : state.serverRetryTimer
- if (state.disposed || timer !== null || !hasFamilyWork(queryClient, state, family)) return
- const delay = family === "snapshot"
- ? state.snapshotRetryDelayMs
- : family === "inbox-dms"
- ? state.inboxDmsRetryDelayMs
- : state.serverRetryDelayMs
- if (family === "snapshot") {
- state.snapshotRetryDelayMs = Math.min(delay * 2, MAX_RETRY_DELAY_MS)
- } else if (family === "inbox-dms") {
- state.inboxDmsRetryDelayMs = Math.min(delay * 2, MAX_RETRY_DELAY_MS)
- } else {
- state.serverRetryDelayMs = Math.min(delay * 2, MAX_RETRY_DELAY_MS)
- }
- const callback = () => {
- if (family === "snapshot") state.snapshotRetryTimer = null
- else if (family === "inbox-dms") state.inboxDmsRetryTimer = null
- else state.serverRetryTimer = null
- if (family === "snapshot") {
- void ensureSnapshotWorker(queryClient, state)
- .then(() => kickPendingSurfaceWorkers(queryClient, state))
- .catch(() => undefined)
- } else if (family === "inbox-dms") {
- void ensureInboxDmsWorker(queryClient, state).catch(() => undefined)
- } else {
- void ensureServerWorker(queryClient, state).catch(() => undefined)
- }
- }
- const nextTimer = setTimeout(callback, delay)
- if (family === "snapshot") state.snapshotRetryTimer = nextTimer
- else if (family === "inbox-dms") state.inboxDmsRetryTimer = nextTimer
- else state.serverRetryTimer = nextTimer
-}
-
-function ensureSnapshotWorker(queryClient: QueryClient, state: ReconciliationState) {
- if (state.disposed) return Promise.reject(new Error("account read-state reconciliation disposed"))
- if (state.snapshotWorker) return state.snapshotWorker
- const worker = runSnapshotWorker(queryClient, state).finally(() => {
- if (state.snapshotWorker === worker) state.snapshotWorker = null
- })
- state.snapshotWorker = worker
- return worker
-}
-
-async function runSnapshotWorker(
- queryClient: QueryClient,
- state: ReconciliationState,
-): Promise<AccountReadStateSnapshot> {
- const epoch = state.epoch
- while (hasSnapshotWork(state, cachedAccountRevision(queryClient))) {
- assertReconciliationActive(queryClient, state, epoch)
- const requestGeneration = state.snapshotRequestedGeneration
- let snapshot: AccountReadStateSnapshot
- try {
- const response = await startAccountReadStateRequest(queryClient, state)
- snapshot = response.snapshot
- assertReconciliationActive(queryClient, state, epoch)
- const applied = applyAccountReadStateSnapshot(queryClient, snapshot, {
- token: response.token,
- signal: response.signal,
- requestGeneration,
- currentRequestGeneration: state.snapshotRequestedGeneration,
- targetRevision: state.highestPendingTargetRevision,
+class ReadStateRevisionPendingError extends Error {}
+
+const disposedClients = new WeakSet<QueryClient>()
+
+function targetRevision(queryClient: QueryClient) {
+ const value = queryClient.getQueryCache().find({ queryKey: communityKeys.accountReadStateSnapshot(), exact: true })?.meta?.readStateTargetRevision
+ return typeof value === "number" ? value : -1
+}
+
+function accountReadStateOptions(queryClient: QueryClient, requestedRevision = -1) {
+ const token = getCommunityDbRegistry(queryClient) ? captureCommunityLiveSnapshotToken(queryClient) : null
+ const minimumRevision = Math.max(requestedRevision, targetRevision(queryClient))
+ return queryOptions({
+ queryKey: communityKeys.accountReadStateSnapshot(),
+ meta: { readStateTargetRevision: minimumRevision },
+ staleTime: 0,
+ retry: conversationReadRetryPolicy(queryClient.defaultQueryOptions({ queryKey: communityKeys.accountReadStateSnapshot() }).retry),
+ queryFn: async ({ signal }) => {
+ if (!token || disposedClients.has(queryClient)) throw new DOMException("Read-state owner retired", "AbortError")
+ assertCommunityLiveSnapshotTokenCurrent(queryClient, token, signal)
+ const original = queryClient.getQueryCache().find({ queryKey: communityKeys.accountReadStateSnapshot(), exact: true })
+ const requestToken = beginCommunityCommandRevision(queryClient, token)
+ const snapshot = await apiFetch<AccountReadStateSnapshot>("/api/community/users/me/read-state", communityRequestOptions(queryClient, requestToken, signal))
+ assertCommunityLiveSnapshotTokenCurrent(queryClient, token, signal)
+ if (!original || queryClient.getQueryCache().get(original.queryHash) !== original) throw new DOMException("Read-state query retired", "AbortError")
+ const publication = publishCommunityLiveSnapshot(queryClient, {
+ snapshot: { kind: "read-state", data: snapshot },
+ proof: { kind: "read-state", token: requestToken, signal, requestGeneration: 0, currentRequestGeneration: 0, targetRevision: Math.max(minimumRevision, targetRevision(queryClient)) },
})
- if (applied === "superseded") continue
- } catch (error) {
- scheduleReconciliationRetry(queryClient, state, "snapshot")
- throw error
- }
- assertReconciliationActive(queryClient, state, epoch)
- state.snapshotCompletedGeneration = Math.max(
- state.snapshotCompletedGeneration,
- requestGeneration,
- )
- state.snapshotRetryDelayMs = INITIAL_RETRY_DELAY_MS
- const appliedRevision = cachedAccountRevision(queryClient)
- if (
- state.highestPendingTargetRevision !== null
- && appliedRevision >= state.highestPendingTargetRevision
- ) {
- state.highestPendingTargetRevision = null
- }
- // If this primary read was older than a live target, or another caller
- // arrived while it was in flight, loop immediately and issue a genuinely
- // fresh request. No timer/backoff is needed for a successful stale read.
- }
- const snapshot = queryClient.getQueryData<AccountReadStateSnapshot>(
- communityKeys.accountReadStateSnapshot(),
- )
- if (!snapshot) throw new Error("account read-state reconciliation produced no snapshot")
- return snapshot
-}
-
-function ensureInboxDmsWorker(queryClient: QueryClient, state: ReconciliationState) {
- if (state.disposed) return Promise.reject(new Error("account read-state reconciliation disposed"))
- if (!hasInboxDmsWork(state)) return Promise.resolve()
- if (state.inboxDmsWorker) return state.inboxDmsWorker
- const worker = runInboxDmsWorker(queryClient, state).finally(() => {
- if (state.inboxDmsWorker === worker) state.inboxDmsWorker = null
+ if (publication === "superseded") throw new ReadStateRevisionPendingError("Read-state snapshot has not reached the requested revision")
+ projectReadCoordinatorSnapshot(queryClient, { readStates: [...token.registry!.collections.readStates.values()] })
+ return { revision: token.registry!.collections.readStateClock.get("account")?.revision ?? snapshot.revision }
+ },
})
- state.inboxDmsWorker = worker
- return worker
}
-async function runInboxDmsWorker(queryClient: QueryClient, state: ReconciliationState) {
- const epoch = state.epoch
- while (hasInboxDmsWork(state)) {
- await ensureSnapshotWorker(queryClient, state)
- assertReconciliationActive(queryClient, state, epoch)
- const surfaceGeneration = state.inboxDmsRequestedGeneration
- try {
- await invalidateInboxDmsSurfaces(queryClient)
- } catch {
- scheduleReconciliationRetry(queryClient, state, "inbox-dms")
- throw new Error("read-state surface reconciliation failed")
- }
- assertReconciliationActive(queryClient, state, epoch)
- state.inboxDmsCompletedGeneration = Math.max(
- state.inboxDmsCompletedGeneration,
- surfaceGeneration,
- )
- state.inboxDmsRetryDelayMs = INITIAL_RETRY_DELAY_MS
- }
-}
-
-function ensureServerWorker(queryClient: QueryClient, state: ReconciliationState) {
- if (state.disposed) return Promise.reject(new Error("account read-state reconciliation disposed"))
- if (!hasServerWork(state)) return Promise.resolve()
- if (state.serverWorker) return state.serverWorker
- const worker = runServerWorker(queryClient, state).finally(() => {
- if (state.serverWorker === worker) state.serverWorker = null
+export function useAccountReadState() {
+ const queryClient = useQueryClient()
+ return useQuery({
+ ...accountReadStateOptions(queryClient),
+ refetchInterval: (query) => query.state.status === "error" && !isConversationAccessError(query.state.error) && !isAbortError(query.state.error) ? 5_000 : false,
+ refetchOnWindowFocus: false,
})
- state.serverWorker = worker
- return worker
-}
-
-async function runServerWorker(queryClient: QueryClient, state: ReconciliationState) {
- const epoch = state.epoch
- while (hasServerWork(state)) {
- await ensureSnapshotWorker(queryClient, state)
- assertReconciliationActive(queryClient, state, epoch)
- const surfaceGeneration = state.serverRequestedGeneration
- if (!state.serverSurfaceWork || state.serverSurfaceWork.generation < surfaceGeneration) {
- state.serverSurfaceWork = captureServerSurfaceWork(queryClient, surfaceGeneration)
- }
- const work = state.serverSurfaceWork
- try {
- await invalidateServerSurfaces(queryClient, work)
- } catch (error) {
- assertReconciliationActive(queryClient, state, epoch)
- assertCommunityLiveSnapshotTokenCurrent(queryClient, work.owner, undefined)
- if (surfaceGeneration < state.serverRequestedGeneration) continue
- if (work.targets.some((target) => canRetryServerSurface(queryClient, target))) {
- scheduleReconciliationRetry(queryClient, state, "non-inbox")
- }
- throw error
- }
- assertReconciliationActive(queryClient, state, epoch)
- state.serverCompletedGeneration = Math.max(
- state.serverCompletedGeneration,
- surfaceGeneration,
- )
- state.serverRetryDelayMs = INITIAL_RETRY_DELAY_MS
- state.serverSurfaceWork = null
- }
}
-function kickPendingSurfaceWorkers(queryClient: QueryClient, state: ReconciliationState) {
- if (state.inboxDmsRetryTimer === null && hasInboxDmsWork(state)) {
- void ensureInboxDmsWorker(queryClient, state).catch(() => undefined)
- }
- if (state.serverRetryTimer === null && hasServerWork(state)) {
- void ensureServerWorker(queryClient, state).catch(() => undefined)
- }
-}
-
-function assertReconciliationActive(
- queryClient: QueryClient,
- state: ReconciliationState,
- epoch: number,
-) {
- if (
- state.disposed
- || state.epoch !== epoch
- || reconciliationStates.get(queryClient) !== state
- ) throw new Error("account read-state reconciliation disposed")
-}
-
-function startAccountReadStateRequest(
+export async function reconcileAccountReadState(
queryClient: QueryClient,
- state: ReconciliationState,
+ options: { targetRevision?: number; reconcileAttention?: boolean } = {},
) {
- const controller = new AbortController()
+ if (disposedClients.has(queryClient)) throw new DOMException("Read-state owner retired", "AbortError")
const token = captureCommunityLiveSnapshotToken(queryClient)
- state.requestController = controller
- return apiFetch<AccountReadStateSnapshot>(
- "/api/community/users/me/read-state",
- communityRequestOptions(queryClient, token, controller.signal),
- ).then((snapshot) => ({ snapshot, token, signal: controller.signal })).finally(() => {
- if (state.requestController === controller) state.requestController = null
+ const query = queryClient.getQueryCache().find({ queryKey: communityKeys.accountReadStateSnapshot(), exact: true })
+ if (query && (options.targetRevision ?? -1) > targetRevision(queryClient)) query.setOptions({ ...query.options, meta: { ...query.meta, readStateTargetRevision: options.targetRevision } })
+ const read = async () => {
+ let result = await queryClient.query({ ...accountReadStateOptions(queryClient, options.targetRevision), retry: (failures, error) => error instanceof ReadStateRevisionPendingError && failures < 3, select: undefined })
+ while (result.revision < Math.max(options.targetRevision ?? -1, targetRevision(queryClient))) {
+ assertCommunityLiveSnapshotTokenCurrent(queryClient, token, undefined)
+ result = await queryClient.query({ ...accountReadStateOptions(queryClient, options.targetRevision), retry: (failures, error) => error instanceof ReadStateRevisionPendingError && failures < 3, select: undefined })
+ }
+ assertCommunityLiveSnapshotTokenCurrent(queryClient, token, undefined)
+ return { revision: result.revision, readStates: [...token.registry!.collections.readStates.values()] }
+ }
+ const pending = read()
+ if (options.reconcileAttention === false) return pending
+ const initialAttention = reconcileAccountAttention(token.registry!)
+ const qualifiedRead = pending.then(async snapshot => {
+ assertCommunityLiveSnapshotTokenCurrent(queryClient, token, undefined)
+ if (!accountAttentionMatchesReadState(token.registry!)) await reconcileAccountAttention(token.registry!)
+ return snapshot
})
+ const [snapshot, attention] = await Promise.allSettled([qualifiedRead, initialAttention])
+ assertCommunityLiveSnapshotTokenCurrent(queryClient, token, undefined)
+ if (snapshot.status === "rejected") throw snapshot.reason
+ if (attention.status === "rejected" && !(attention.reason instanceof CancelledError)) throw attention.reason
+ return snapshot.value
}
export function disposeAccountReadStateReconciliation(queryClient: QueryClient) {
- disposedReconciliationClients.add(queryClient)
- const state = reconciliationStates.get(queryClient)
- if (!state || state.disposed) return
- state.disposed = true
- state.epoch += 1
- state.highestPendingTargetRevision = null
- state.snapshotCompletedGeneration = state.snapshotRequestedGeneration
- state.inboxDmsCompletedGeneration = state.inboxDmsRequestedGeneration
- state.serverCompletedGeneration = state.serverRequestedGeneration
- clearReconciliationRetry(state, "snapshot")
- clearReconciliationRetry(state, "inbox-dms")
- clearReconciliationRetry(state, "non-inbox")
- state.requestController?.abort()
- state.requestController = null
- state.serverSurfaceWork = null
+ disposedClients.add(queryClient)
+ void queryClient.cancelQueries({ queryKey: communityKeys.accountReadStateSnapshot(), exact: true })
}
-export function projectReadStateEnvelope(
- queryClient: QueryClient,
- envelope: ReadStateEnvelope,
-) {
- const snapshot = queryClient.getQueryData<AccountReadStateSnapshot>(
- communityKeys.accountReadStateSnapshot(),
- )
- if (!snapshot) return "gap" as const
- const state = reconciliationStates.get(queryClient)
- if (state && hasInboxDmsWork(state) && envelope.revision <= snapshot.revision) {
- return "gap" as const
- }
- if (envelope.revision <= snapshot.revision) return "stale" as const
- return "gap" as const
+export function projectReadStateEnvelope(queryClient: QueryClient, envelope: ReadStateEnvelope) {
+ const clock = getCommunityDbRegistry(queryClient)?.collections.readStateClock.get("account")
+ const query = queryClient.getQueryCache().find({ queryKey: communityKeys.accountReadStateSnapshot(), exact: true })
+ return clock && envelope.revision <= clock.revision && query?.state.status !== "error" ? "stale" as const : "gap" as const
}
diff --git a/src/web/src/hooks/community/community-ws/reconnect.dom.test.ts b/src/web/src/hooks/community/community-ws/reconnect.dom.test.ts
index 0ff39ea13..333ef1025 100644
--- a/src/web/src/hooks/community/community-ws/reconnect.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect.dom.test.ts
@@ -196,7 +196,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
const lateKeys = invalidate.mock.calls.slice(callsAtUnmount).map(
(call) => JSON.stringify(call[0]?.queryKey),
)
- expect(lateKeys).not.toContain(JSON.stringify(communityKeys.inbox()))
+ expect(lateKeys).not.toContain(JSON.stringify(communityKeys.inboxMarked()))
expect(lateKeys).not.toContain(JSON.stringify(communityKeys.dms()))
})
@@ -276,9 +276,9 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
// schedule the single account owner generation.
expect(
invalidatedKeys.some(
- (k) => Array.isArray(k) && k[0] === "community" && k[1] === "inbox",
+ (k) => JSON.stringify(k) === JSON.stringify(communityKeys.inboxMarked()),
),
- ).toBe(false)
+ ).toBe(true)
await vi.waitFor(() => expect(getCommunityApiFetchMock().mock.calls.filter(([path]) => (
path === "/api/community/users/me/attention"
))).toHaveLength(1))
@@ -646,7 +646,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
})
const keys = spy.mock.calls.map(([filters]) => JSON.stringify(filters.queryKey))
- expect(keys).not.toContain(JSON.stringify(communityKeys.inbox()))
+ expect(keys).not.toContain(JSON.stringify(communityKeys.inboxMarked()))
expect(keys).not.toContain(JSON.stringify(communityKeys.dms()))
expect(keys).toContain(JSON.stringify(communityKeys.friends()))
expect(keys).toContain(JSON.stringify(communityKeys.servers()))
@@ -744,12 +744,12 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
const work = reconcileCommunityWsReconnect(capturedQueryClient)
await flushMicrotasks()
expect(started).toContain(JSON.stringify(communityKeys.channelMembers("ch_priority")))
- expect(started).not.toContain(JSON.stringify(communityKeys.inbox()))
+ expect(started).not.toContain(JSON.stringify(communityKeys.inboxMarked()))
releaseMembers()
releaseAddable()
await work
- expect(started).toContain(JSON.stringify(communityKeys.inbox()))
+ expect(started).toContain(JSON.stringify(communityKeys.inboxMarked()))
})
it("limits background reconciliation to three policies at a time", async () => {
@@ -769,7 +769,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
const work = reconcileCommunityWsReconnect(capturedQueryClient)
await flushMicrotasks()
expect(started).toEqual(expect.arrayContaining([
- JSON.stringify(communityKeys.inbox()),
+ JSON.stringify(communityKeys.inboxMarked()),
JSON.stringify(communityKeys.dms()),
JSON.stringify(communityKeys.friends()),
JSON.stringify(communityKeys.servers()),
diff --git a/src/web/src/hooks/community/community-ws/reconnect.ts b/src/web/src/hooks/community/community-ws/reconnect.ts
index 45c071859..2307ec6e5 100644
--- a/src/web/src/hooks/community/community-ws/reconnect.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect.ts
@@ -226,13 +226,13 @@ function policyExecutors(
"inbox-dms": async () => {
const settled = await Promise.allSettled([
queryClient.invalidateQueries({ queryKey: communityKeys.accountAttention(), refetchType: "active" }),
- queryClient.invalidateQueries({ queryKey: communityKeys.inbox(), refetchType: "active" }),
+ queryClient.invalidateQueries({ queryKey: communityKeys.inboxMarked(), exact: true, refetchType: "active" }),
queryClient.invalidateQueries({ queryKey: communityKeys.dms(), refetchType: "active" }),
])
if (settled.some((result) => result.status === "rejected")) throw new Error("inbox reconciliation failed")
},
"cached-read-state": async () => {
- await reconcileAccountReadState(queryClient, { invalidateSurfaces: false })
+ await reconcileAccountReadState(queryClient, { reconcileAttention: false })
},
"server-rail": () => reconcileCommunityServerRail(queryClient),
"all-cached-servers": async () => {
diff --git a/src/web/src/hooks/community/community-ws/registry.test.ts b/src/web/src/hooks/community/community-ws/registry.test.ts
index b32ffd49d..cea64f189 100644
--- a/src/web/src/hooks/community/community-ws/registry.test.ts
+++ b/src/web/src/hooks/community/community-ws/registry.test.ts
@@ -84,7 +84,7 @@ function dispatchContext(queryClient = new QueryClient()): CommunityWsDispatchCo
sub: {},
viewerUserIdRef: { current: null },
matchesFocus: () => false,
- scheduleInboxInvalidate: vi.fn(),
+
}
}
diff --git a/src/web/src/hooks/community/community-ws/server-rail-reconciliation.test.ts b/src/web/src/hooks/community/community-ws/server-rail-reconciliation.test.ts
index d894d5553..901df4639 100644
--- a/src/web/src/hooks/community/community-ws/server-rail-reconciliation.test.ts
+++ b/src/web/src/hooks/community/community-ws/server-rail-reconciliation.test.ts
@@ -30,7 +30,7 @@ it("refreshes only the account rail and reference directory, keeping inactive qu
client.setQueryData(communityKeys.channelRefDirectory(), ["old"])
await dispatchCommunityWsEvent({ type: "community:server_rail.changed" }, {
queryClient: client, communityStore: runtime.ui, wsStore: runtime.ws, sub: {}, deliveryMode: "single",
- viewerUserIdRef: { current: "viewer" }, matchesFocus: () => false, scheduleInboxInvalidate: vi.fn(),
+ viewerUserIdRef: { current: "viewer" }, matchesFocus: () => false,
})
expect(servers.queryFn).toHaveBeenCalledTimes(1)
expect(folders.queryFn).toHaveBeenCalledTimes(1)
diff --git a/src/web/src/hooks/community/community-ws/social-events.dom.test.ts b/src/web/src/hooks/community/community-ws/social-events.dom.test.ts
index 8238ee2c9..0f5e59656 100644
--- a/src/web/src/hooks/community/community-ws/social-events.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/social-events.dom.test.ts
@@ -13,7 +13,6 @@ import {
} from "@alook/shared"
import { getMessageStreamState } from "@/test/community-query-owner"
import { communityKeys } from "@/lib/query-keys"
-import { getActiveAccountUnreadProjection } from "../account-unread-projection"
import { act } from "@/test/react-dom-harness"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import { captureCommunityLiveSnapshotToken, ingestDms, publishCommunityMessages } from "@/lib/community-db/sync"
@@ -94,106 +93,6 @@ describe("useCommunityWs — account unread projection", () => {
}
}
- it("records a viewer bump without mutating raw server resources", async () => {
- await mountHook({ viewerUserId: "u_me" })
- const key = communityKeys.server("srv_open")
- const raw = serverDetailFixture("ch_random")
- capturedQueryClient.setQueryData(key, raw)
-
- capturedOnMessage!(unreadBump("ch_random", "u_me", { serverId: "srv_open" }))
-
- expect(capturedQueryClient.getQueryData(key)).toBe(raw)
- const projection = getActiveAccountUnreadProjection(capturedQueryClient)
- expect(projection.projectServerChannelUnread(
- "srv_open",
- "ch_random",
- [],
- )).toBe(true)
- expect(projection.projectServerUnread("srv_open", [])).toBe(true)
- })
-
- it("keeps a focused bump unread until the visible-row observer submits a read", async () => {
- const { useCommunityStore } = await import("@/stores/community")
- getCapturedRuntime().ui.actions.subscribe({ channelId: "ch_focused" })
- resetHookMemoization()
- await mountHook({ viewerUserId: "u_me" })
-
- capturedOnMessage!(unreadBump("ch_focused", "u_me", { serverId: "srv_open" }))
-
- const projection = getActiveAccountUnreadProjection(capturedQueryClient)
- expect(projection.projectUnread(
- "server-detail:srv_open",
- "ch_focused",
- false,
- )).toBe(true)
- projection.recordRead("ch_focused", 999)
- expect(projection.projectUnread(
- "server-detail:srv_open",
- "ch_focused",
- false,
- )).toBe(true)
- })
-
- it("uses railChannelId only as a parent fallback and leaves raw rows untouched", async () => {
- await mountHook({ viewerUserId: "u_me" })
- const key = communityKeys.server("srv_open")
- const raw = serverDetailFixture("forum_1")
- capturedQueryClient.setQueryData(key, raw)
-
- capturedOnMessage!(unreadBump("post_1", "u_me", {
- serverId: "srv_open",
- railChannelId: "forum_1",
- }))
-
- const projection = getActiveAccountUnreadProjection(capturedQueryClient)
- expect(projection.projectForumParentUnread(
- "srv_open",
- "forum_1",
- false,
- undefined,
- new Set(),
- )).toBe(true)
- expect(capturedQueryClient.getQueryData(key)).toBe(raw)
- })
-
- it("never increments a numeric rail badge from an unsequenced isMention hint", async () => {
- await mountHook({ viewerUserId: "u_me" })
- capturedOnMessage!(unreadBump("ch_a", "u_me", {
- serverId: "srv_x",
- isMention: true,
- }))
- expect(getActiveAccountUnreadProjection(capturedQueryClient)
- .projectServerMentionCount("srv_x", [], 7)).toBe(0)
- })
-
- it("merges a valid WS bump before applying the current policy overlay", async () => {
- await mountHook({ viewerUserId: "u_me" })
- const projection = getActiveAccountUnreadProjection(capturedQueryClient)
- projection.setNotificationPolicy({ server: { srv_x: "nothing" } })
-
- capturedOnMessage!(unreadBump("ch_a", "u_me", { serverId: "srv_x" }))
-
- expect(projection.inspectForTests().sourceCount).toBe(1)
- expect(projection.projectUnread("servers", "ch_a", false)).toBe(false)
- projection.setNotificationPolicy({ server: { srv_x: "all" } })
- expect(projection.projectUnread("servers", "ch_a", false)).toBe(true)
- })
-
- it("ignores bumps addressed to a different account", async () => {
- await mountHook({ viewerUserId: "u_me" })
- capturedOnMessage!(unreadBump("ch_random", "someone_else", { serverId: "srv_open" }))
- expect(getActiveAccountUnreadProjection(capturedQueryClient)
- .projectServerUnread("srv_open", [])).toBe(false)
- })
-
- it("message.create alone syncs content but does not manufacture unread authority", async () => {
- await mountHook({ viewerUserId: "u_me" })
- capturedOnMessage!(messageCreate("ch_random"))
- expect(getActiveAccountUnreadProjection(capturedQueryClient)
- .projectServerUnread("s1", [])).toBe(false)
- expect(notificationMocks.show).not.toHaveBeenCalled()
- })
-
it("notifies only when message.create and the viewer's unread.bump share one bundle", async () => {
await mountHook({ viewerUserId: "u_me" })
const create = messageCreate("dm_1", "message_1")
@@ -424,7 +323,7 @@ describe("useCommunityWs — friend + mention → invalidate", () => {
}
})
- it("mention.create invalidates servers so authoritative source counts refresh", async () => {
+ it("mention.create leaves server structure untouched", async () => {
await mountHook({ viewerUserId: "u_1" })
const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
const event: CommunityMentionCreate = {
@@ -437,41 +336,6 @@ describe("useCommunityWs — friend + mention → invalidate", () => {
expect(spy.mock.calls.filter((call) => {
const key = call[0]?.queryKey as unknown[] | undefined
return key?.length === 2 && key[0] === "community" && key[1] === "servers"
- })).toHaveLength(1)
- })
-
- it("projects a mention-only delivery into its server and parent scope immediately", async () => {
- await mountHook({ viewerUserId: "u_1" })
- const projection = getActiveAccountUnreadProjection(capturedQueryClient)
- projection.setNotificationPolicy({
- server: { srv_1: "mentions" },
- channel: { forum_1: "mentions" },
- })
-
- capturedOnMessage!(await batchFor("m_1", [
- unreadBump("post_1", "u_1", {
- serverId: "srv_1",
- railChannelId: "forum_1",
- isMention: true,
- }),
- {
- type: "community:mention.create",
- userId: "u_1",
- messageId: "m_1",
- channelId: "post_1",
- authorName: "A",
- },
- ]))
-
- expect(projection.projectServerUnread("srv_1", [])).toBe(true)
- expect(projection.projectForumParentUnread(
- "srv_1",
- "forum_1",
- false,
- undefined,
- new Set(),
- )).toBe(true)
- projection.retireAccessScope({ kind: "server", serverId: "srv_1" })
- expect(projection.projectServerUnread("srv_1", [])).toBe(false)
+ })).toHaveLength(0)
})
})
diff --git a/src/web/src/hooks/community/community-ws/social-events.ts b/src/web/src/hooks/community/community-ws/social-events.ts
index 543590016..e3d212b61 100644
--- a/src/web/src/hooks/community/community-ws/social-events.ts
+++ b/src/web/src/hooks/community/community-ws/social-events.ts
@@ -13,13 +13,11 @@ import {
import type { SocialEventContext } from "@/hooks/community/community-ws/handler-context"
import {
invalidateFriends,
- invalidateServersList,
} from "./invalidation-projections"
import {
projectReadStateEnvelope,
reconcileAccountReadState,
} from "./read-state-reconciliation"
-import { getAccountUnreadProjection } from "@/hooks/community/account-unread-projection"
import { removeDmReactionDetails } from "./reaction-details-invalidation"
import { reconcileNotificationSettings } from "@/hooks/community/use-notification-settings"
import { communityKeys } from "@/lib/query-keys"
@@ -36,7 +34,6 @@ export function handleReadStateAdvanced(
context: SocialEventContext,
) {
applyReadStateEnvelope(event, context)
- scheduleAccountAttentionReconcile(context.queryClient)
}
function applyReadStateEnvelope(
@@ -45,9 +42,7 @@ function applyReadStateEnvelope(
) {
const outcome = projectReadStateEnvelope(context.queryClient, event)
if (outcome === "gap") {
- context.scheduleInboxInvalidate({ inbox: true, dms: true })
void reconcileAccountReadState(context.queryClient, {
- surfaceMode: "non-inbox",
targetRevision: event.revision,
}).catch(() => undefined)
}
@@ -58,10 +53,9 @@ export function handleInboxChanged(
context: SocialEventContext,
) {
if (event.reason === "notification_policy") {
- void reconcileNotificationSettings(context.queryClient).catch(() => undefined)
+ void reconcileNotificationSettings(context.queryClient).then(() => scheduleAccountAttentionReconcile(context.queryClient)).catch(() => undefined)
}
applyReadStateEnvelope(event, context)
- scheduleAccountAttentionReconcile(context.queryClient)
}
type CommunityUnreadBump = Extract<
@@ -88,16 +82,6 @@ export function handleUnreadBump(
if (event.userId === viewerId && viewerId) {
const evidence = unreadBumpEvidence?.get(event)
scheduleAccountAttentionReconcile(queryClient, { channelId: event.channelId, messageId: evidence?.messageId })
- getAccountUnreadProjection(queryClient, viewerId).recordArrival({
- channelId: event.channelId,
- railChannelId: event.railChannelId,
- serverId: event.serverId,
- isMention: event.isMention,
- messageId: evidence?.messageId,
- seq: evidence?.seq,
- })
- // Use the existing coalesced owner. This is also the sole authority
- // refresh for legacy/orphan bumps; the ledger itself performs no I/O.
if (evidence && isDesktop()) {
void resolveDesktopSystemNotificationCandidate(
evidence.messageEvent,
@@ -143,32 +127,11 @@ export function handleFriendEvent(
export function handleMentionCreate(
event: CommunityMentionCreate,
{
- projection,
queryClient,
viewerUserIdRef,
- messageEvidenceByChannel,
}: SocialEventContext,
) {
const viewerId = viewerUserIdRef.current
if (!viewerId || event.userId !== viewerId) return
scheduleAccountAttentionReconcile(queryClient, { channelId: event.channelId, messageId: event.messageId })
- if (event.channelId) {
- const candidate = messageEvidenceByChannel?.get(event.channelId)
- const evidence = candidate?.messageId === event.messageId ? candidate : undefined
- getAccountUnreadProjection(queryClient, viewerId).recordMentionArrival({
- channelId: event.channelId,
- messageId: event.messageId,
- seq: evidence?.seq,
- isMention: true,
- })
- }
- // The server rail badge counts unread mentions per server; refresh
- // it on every new mention. `exact: true` is essential: the mention
- // count lives in the `servers()` LIST query, but members/presence/
- // invites/server(id) are all nested UNDER `servers()` in
- // the key hierarchy — a non-exact invalidate prefix-matches and
- // force-refetches that whole subtree (and invalidate overrides the
- // staleTime: Infinity those carry). With an active bot in the server,
- // every mention.create would otherwise storm-refetch all of them.
- invalidateServersList(projection)
}
diff --git a/src/web/src/hooks/community/community-ws/structure-tree-events.dom.test.ts b/src/web/src/hooks/community/community-ws/structure-tree-events.dom.test.ts
index 517c1642e..6896c618a 100644
--- a/src/web/src/hooks/community/community-ws/structure-tree-events.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/structure-tree-events.dom.test.ts
@@ -1,3 +1,5 @@
+import { getCommunityDbRegistry } from "@/lib/community-db/collections"
+import { seedCommunityAttentionScope } from "@/test/community-query-owner"
import { act } from "@/test/react-dom-harness"
import { readCurrentCommunityChannelMeta } from "@/stores/community/runtime"
import { seedCanonicalFocusedChannel } from "./test-harness"
@@ -24,7 +26,6 @@ import type {
} from "@alook/shared"
import { getMessageStreamState } from "@/test/community-query-owner"
import { communityKeys } from "@/lib/query-keys"
-import { getAccountUnreadProjection } from "@/hooks/community/account-unread-projection"
import {
capturedOnMessage,
capturedQueryClient,
@@ -266,8 +267,8 @@ describe("useCommunityWs — channel.delete evicts channel-scoped caches", () =>
it("fences a deleted channel's cached raw Inbox row", async () => {
await mountHook({ viewerUserId: "u_me" })
- const unreadProjection = getAccountUnreadProjection(capturedQueryClient, "u_me")
- unreadProjection.recordArrival({ channelId: "ch_dead", serverId: "srv_1", seq: 1 })
+
+ seedCommunityAttentionScope(capturedQueryClient, { channelId: "ch_dead", serverId: "srv_1", seq: 1 })
capturedOnMessage!({
type: "community:channel.delete",
@@ -275,7 +276,7 @@ describe("useCommunityWs — channel.delete evicts channel-scoped caches", () =>
channelId: "ch_dead",
} satisfies CommunityChannelDelete)
- expect(unreadProjection.projectUnread("inbox-unreads", "ch_dead", true, 1)).toBe(false)
+ expect(Boolean(getCommunityDbRegistry(capturedQueryClient)!.collections.attentionScopes.get("ch_dead")?.ordinaryUnread)).toBe(false)
})
it("removes channelMessages, pins, and threads for the deleted channel", async () => {
@@ -1008,15 +1009,15 @@ describe("useCommunityWs — server.update icon removal", () => {
describe("useCommunityWs — server.delete resets store when focused server dies", () => {
it("fences cached raw Inbox rows from the deleted server", async () => {
await mountHook({ viewerUserId: "u_me" })
- const unreadProjection = getAccountUnreadProjection(capturedQueryClient, "u_me")
- unreadProjection.recordArrival({ channelId: "ch_dead", serverId: "srv_doomed", seq: 1 })
+
+ seedCommunityAttentionScope(capturedQueryClient, { channelId: "ch_dead", serverId: "srv_doomed", seq: 1 })
capturedOnMessage!({
type: "community:server.delete",
serverId: "srv_doomed",
} satisfies CommunityServerDelete)
- expect(unreadProjection.projectUnread("inbox-unreads", "ch_dead", true, 1)).toBe(false)
+ expect(Boolean(getCommunityDbRegistry(capturedQueryClient)!.collections.attentionScopes.get("ch_dead")?.ordinaryUnread)).toBe(false)
})
it("clears currentServerId + currentChannelId if the deleted server is currently focused", async () => {
diff --git a/src/web/src/hooks/community/community-ws/structure-tree-events.ts b/src/web/src/hooks/community/community-ws/structure-tree-events.ts
index 982db1054..25f698afa 100644
--- a/src/web/src/hooks/community/community-ws/structure-tree-events.ts
+++ b/src/web/src/hooks/community/community-ws/structure-tree-events.ts
@@ -25,7 +25,6 @@ import {
isForumSidebarParent,
patchForumSidebarActivityExact,
reconcileForumSidebarArchiveTag,
- removeForumSidebarUnreadChild,
} from "@/hooks/community/use-forum-sidebar-threads"
import type { StructureTreeEventContext } from "@/hooks/community/community-ws/handler-context"
import {
@@ -41,7 +40,6 @@ import {
invalidateServersList,
invalidateThreads,
} from "./invalidation-projections"
-import { getActiveAccountUnreadProjection } from "@/hooks/community/account-unread-projection"
export function handleChildChannelCreate(event: CommunityChildChannelCreate, { queryClient, projection }: StructureTreeEventContext) {
const parent = getCanonicalCommunityChannels(queryClient).find(row => row.id === event.parentChannelId && row.type === "forum")
@@ -71,7 +69,6 @@ export function handleChildChannelUpdate(
isForumSidebarParent(queryClient, sidebarServerId, event.parentChannelId)
) {
if (changes.archived === true || changes.archived === false) {
- removeForumSidebarUnreadChild(queryClient, sidebarServerId, event.channelId)
void reconcileForumSidebarArchiveTag(
queryClient,
sidebarServerId,
@@ -172,10 +169,6 @@ export function handleChannelEvent(
exact: true,
})
} else {
- getActiveAccountUnreadProjection(queryClient).retireAccessScope({
- kind: "channel",
- channelId: event.channelId,
- })
const registry = getCommunityDbRegistry(queryClient)
if (registry) retireCommunityChannelReading(registry, event.channelId, { reason: "resource-deleted", serverId: event.serverId })
}
diff --git a/src/web/src/hooks/community/community-ws/unread-attention.dom.test.ts b/src/web/src/hooks/community/community-ws/unread-attention.dom.test.ts
new file mode 100644
index 000000000..30eb0e1b6
--- /dev/null
+++ b/src/web/src/hooks/community/community-ws/unread-attention.dom.test.ts
@@ -0,0 +1,96 @@
+import { captureCommunityLiveSnapshotToken, publishCommunityConversationReadState } from "@/lib/community-db/sync"
+import { afterEach, beforeEach, expect, it, vi } from "vitest"
+import { act, waitFor } from "@/test/react-dom-harness"
+import { communityKeys } from "@/lib/query-keys"
+import { capturedOnMessage, capturedQueryClient, canonicalRegistry, cleanupCommunityWsHarness, getCommunityApiFetchMock, mountHook, resetCommunityWsHarness, unreadBump } from "./test-harness"
+
+const at = "2026-10-27T00:00:00.000Z"
+function attention(seq: number, kind: "text" | "dm" | "child" = "text") {
+ const parent = { id: "parent", serverId: "s1", name: "Parent", type: "forum", parentChannelId: null, parentMessageId: null, creatorId: "peer", archived: false, lastMessageAt: at }
+ const channel = { ...parent, id: "c1", name: "Channel", type: kind === "child" ? "thread" : "text", parentChannelId: kind === "child" ? "parent" : null, parentMessageId: kind === "child" ? "opener" : null, ...(kind === "child" ? { openerSeq: 1, openerUnread: false } : {}) }
+ return {
+ scopes: [{ scopeId: "c1", channelId: "c1", serverId: kind === "dm" ? null : "s1", parentChannelId: kind === "child" ? "parent" : null, ordinaryUnread: true, lastUnreadSeq: seq, attentionCount: 0, lastAttentionSeq: null, ...(kind === "dm" ? { unreadCount: seq } : {}) }],
+ items: [], limit: 100, truncated: false,
+ included: {
+ servers: kind === "dm" ? [] : [{ id: "s1", name: "Server", discriminator: "0001" }],
+ channels: kind === "dm" ? [] : kind === "child" ? [parent, channel] : [channel],
+ dms: kind === "dm" ? [{ id: "c1", userId: "peer", name: "Peer", discriminator: "0002", avatar: "P", avatarVersion: 0, lastMessageAt: at, lastUnreadSeq: seq }] : [],
+ profiles: [{ userId: "peer", name: "Peer", discriminator: "0002", avatar: "P", avatarVersion: 0 }],
+ messages: kind === "child" ? [{ id: "opener", channelId: "parent", authorId: "peer", type: "chat", content: "Opener", seq: 1, createdAt: at }] : [],
+ },
+ }
+}
+function deferred<T>() { let resolve!: (value: T) => void; const promise = new Promise<T>(done => { resolve = done }); return { promise, resolve } }
+function transport(read: () => Promise<ReturnType<typeof attention>>) {
+ getCommunityApiFetchMock().mockImplementation(async (path: unknown) => {
+ if (path === "/api/community/users/me/attention") return read()
+ if (path === "/api/community/users/me/read-state") return { revision: 0, readStates: [] }
+ if (String(path).includes("/messages")) return { messages: [], hasMore: false }
+ throw new Error(`Unexpected transport ${String(path)}`)
+ })
+}
+beforeEach(resetCommunityWsHarness)
+afterEach(cleanupCommunityWsHarness)
+
+it.each(["text", "dm", "child"] as const)("uses qualified HTTP attention for a %s arrival without writing structural unread", async kind => {
+ await mountHook({ viewerUserId: "u_me" })
+ const gate = deferred<ReturnType<typeof attention>>()
+ transport(() => gate.promise)
+ const original = { categories: [{ channels: [{ id: "c1", unread: true }] }] }
+ capturedQueryClient.setQueryData(communityKeys.server("s1"), original)
+ await act(async () => { await capturedOnMessage!(unreadBump("c1", "u_me", { ...(kind === "dm" ? {} : { serverId: "s1", railChannelId: kind === "child" ? "parent" : "c1" }) })) })
+ expect(canonicalRegistry!.collections.attentionScopes.size).toBe(0)
+ expect(capturedQueryClient.getQueryData(communityKeys.server("s1"))).toBe(original)
+ await act(async () => { gate.resolve(attention(4, kind)) })
+ await waitFor(() => expect(canonicalRegistry!.collections.attentionScopes.get("c1")?.lastUnreadSeq).toBe(4))
+ expect(canonicalRegistry!.collections.channels.get("c1")).not.toHaveProperty("unread")
+ expect([...canonicalRegistry!.collections.servers.values()].every(row => !("unread" in row) && !("mentions" in row))).toBe(true)
+ expect(getCommunityApiFetchMock().mock.calls.filter(([path]) => path === "/api/community/users/me/attention")).toHaveLength(1)
+ expect(getCommunityApiFetchMock().mock.calls.some(([path]) => path === "/api/community/servers" || String(path).endsWith("/unreads"))).toBe(false)
+})
+
+it("rejects an ignored-abort old attention response after a newer arrival", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ const old = deferred<ReturnType<typeof attention>>()
+ let requests = 0
+ transport(() => ++requests === 1 ? old.promise : Promise.resolve(attention(5)))
+ await act(async () => { await capturedOnMessage!(unreadBump("c1", "u_me", { serverId: "s1" })) })
+ await waitFor(() => expect(requests).toBe(1))
+ await act(async () => { await capturedOnMessage!(unreadBump("c1", "u_me", { serverId: "s1" })) })
+ await waitFor(() => expect(canonicalRegistry!.collections.attentionScopes.get("c1")?.lastUnreadSeq).toBe(5))
+ await act(async () => { old.resolve(attention(4)) })
+ expect(canonicalRegistry!.collections.attentionScopes.get("c1")?.lastUnreadSeq).toBe(5)
+ expect(requests).toBe(2)
+})
+
+it("ignores another account's bump without creating unread or issuing attention IO", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ const requests = getCommunityApiFetchMock().mock.calls.length
+ await act(async () => { await capturedOnMessage!(unreadBump("c1", "someone-else", { serverId: "s1" })) })
+ expect(canonicalRegistry!.collections.attentionScopes.size).toBe(0)
+ expect(getCommunityApiFetchMock().mock.calls).toHaveLength(requests)
+})
+
+
+it("rejects a pre-confirmation attention count and retries with the same original account owner", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ vi.useFakeTimers()
+ try {
+ const old = deferred<ReturnType<typeof attention>>()
+ let requests = 0
+ const fresh = attention(5, "dm")
+ fresh.scopes[0]!.unreadCount = 3
+ transport(() => ++requests === 1 ? old.promise : Promise.resolve(fresh))
+ await act(async () => { await capturedOnMessage!(unreadBump("c1", "u_me")) })
+ expect(requests).toBe(1)
+ await act(async () => {
+ publishCommunityConversationReadState(capturedQueryClient, { channelId: "c1", lastReadMessageId: "m2", lastReadAt: at, lastReadSeq: 2 }, 2, { token: captureCommunityLiveSnapshotToken(capturedQueryClient) }, "advance")
+ old.resolve(attention(4, "dm"))
+ await vi.advanceTimersByTimeAsync(0)
+ })
+ expect(canonicalRegistry!.collections.attentionScopes.get("c1")).toBeUndefined()
+ await act(async () => { await vi.advanceTimersByTimeAsync(5_000) })
+ expect(requests).toBe(2)
+ expect(canonicalRegistry!.collections.attentionScopes.get("c1")).toMatchObject({ lastUnreadSeq: 5, unreadCount: 3 })
+ } finally { vi.useRealTimers() }
+})
diff --git a/src/web/src/hooks/community/forum-preview-live-edit.dom.test.ts b/src/web/src/hooks/community/forum-preview-live-edit.dom.test.ts
index b1914615b..7441f4222 100644
--- a/src/web/src/hooks/community/forum-preview-live-edit.dom.test.ts
+++ b/src/web/src/hooks/community/forum-preview-live-edit.dom.test.ts
@@ -59,7 +59,7 @@ async function mount(contractVersion: 2 | 3 = 2, firstSeq = 1) {
const context = { contract: contractVersion, deliveryMode: "single" as const,
queryClient: owner.client, communityStore: owner.runtime.ui, wsStore: owner.runtime.ws,
sub: { channelId: "forum" }, viewerUserIdRef: { current: "viewer" },
- matchesFocus: () => false, scheduleInboxInvalidate: vi.fn() }
+ matchesFocus: () => false }
function edit(channelId: string, messageId: string, content: string, title = false) {
act(() => dispatchCommunityWsEvent({ type: "community:message.edited", serverId: "server",
channelId, messageId, content, ...(title ? { parentChannelId: "forum" } : {}) }, context))
diff --git a/src/web/src/hooks/community/friend-request-action-order.red.dom.test.tsx b/src/web/src/hooks/community/friend-request-action-order.red.dom.test.tsx
index 75750fe91..f23373d3c 100644
--- a/src/web/src/hooks/community/friend-request-action-order.red.dom.test.tsx
+++ b/src/web/src/hooks/community/friend-request-action-order.red.dom.test.tsx
@@ -395,7 +395,7 @@ describe("friend-request action authority RED", () => {
sub: {},
viewerUserIdRef: { current: "viewer" },
projection,
- scheduleInboxInvalidate: vi.fn(),
+
} satisfies SocialEventContext,
)
})
@@ -449,7 +449,7 @@ describe("friend-request action authority RED", () => {
sub: {},
viewerUserIdRef: { current: "viewer" },
projection,
- scheduleInboxInvalidate: vi.fn(),
+
} satisfies SocialEventContext,
)
publishRows(client, ["a"], beforeBlock)
diff --git a/src/web/src/hooks/community/mutations/channels.dom.test.ts b/src/web/src/hooks/community/mutations/channels.dom.test.ts
index 6e733df2d..487d8448e 100644
--- a/src/web/src/hooks/community/mutations/channels.dom.test.ts
+++ b/src/web/src/hooks/community/mutations/channels.dom.test.ts
@@ -1,3 +1,4 @@
+import { seedCommunityAttentionScope } from "@/test/community-query-owner"
import { createElement, type PropsWithChildren } from "react"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { beforeEach, afterEach, describe, expect, it, vi } from "vitest"
@@ -7,7 +8,6 @@ import { CommunityDbProvider, useServerTreeProjection, useChannelRefDirectoryPro
import { captureCommunityLiveSnapshotToken, publishCommunityLiveSnapshot } from "@/lib/community-db/sync"
import { communityKeys } from "@/lib/query-keys"
import { UNCATEGORIZED_CATEGORY_ID } from "@alook/shared"
-import { getActiveAccountUnreadProjection } from "../account-unread-projection"
import * as commands from "./channels"
import { useChannelTree } from "@/components/community/channels/use-channel-tree"
import type { ServerDetail } from "../use-servers"
@@ -209,23 +209,23 @@ describe("canonical category commands and channel deletion", () => {
await waitFor(() => expect(rendered.result.current.tree?.categories.map((row) => row.id)).toEqual(["cat_1", "cat_2"]))
})
it("retires projected unread after a successful DELETE without waiting for self WS", async () => {
- seed(); const projection = getActiveAccountUnreadProjection(client)
- projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })
+ seed()
+ seedCommunityAttentionScope(client, { channelId: "c1", serverId: "s1", seq: 1 })
api.mockResolvedValueOnce(undefined)
const rendered = mount(commands.useDeleteChannel)
await act(async () => { await rendered.result.current.command.mutateAsync({ serverId: "s1", channelId: "c1" }) })
- expect(projection.projectUnread("servers", "c1", false)).toBe(false)
- expect(projection.projectUnread("inbox-unreads", "c1", true, 1)).toBe(false)
+ expect(Boolean(registry.collections.attentionScopes.get("c1")?.ordinaryUnread)).toBe(false)
+ expect(Boolean(registry.collections.attentionScopes.get("c1")?.ordinaryUnread)).toBe(false)
expect(registry.collections.channels.has("c1")).toBe(false)
})
it("keeps projected unread when DELETE fails", async () => {
- seed(); const projection = getActiveAccountUnreadProjection(client)
- projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })
+ seed()
+ seedCommunityAttentionScope(client, { channelId: "c1", serverId: "s1", seq: 1 })
api.mockRejectedValueOnce(new Error("500"))
const rendered = mount(commands.useDeleteChannel)
await act(async () => { await expect(rendered.result.current.command.mutateAsync({ serverId: "s1", channelId: "c1" })).rejects.toThrow("500") })
- expect(projection.projectUnread("servers", "c1", false)).toBe(true)
- expect(projection.projectUnread("inbox-unreads", "c1", true, 1)).toBe(true)
+ expect(Boolean(registry.collections.attentionScopes.get("c1")?.ordinaryUnread)).toBe(true)
+ expect(Boolean(registry.collections.attentionScopes.get("c1")?.ordinaryUnread)).toBe(true)
expect(registry.collections.channels.has("c1")).toBe(true)
})
it("removes a category optimistically", async () => {
diff --git a/src/web/src/hooks/community/mutations/channels.ts b/src/web/src/hooks/community/mutations/channels.ts
index 79f4ebe98..b86ffd657 100644
--- a/src/web/src/hooks/community/mutations/channels.ts
+++ b/src/web/src/hooks/community/mutations/channels.ts
@@ -16,7 +16,6 @@ import { communityKeys } from "@/lib/query-keys"
import { isAbortError } from "@/lib/errors"
import type { ChannelRow, CategoryRow } from "@/lib/community-db/schema"
import { UNCATEGORIZED_CATEGORY_ID, type ChannelCategoryMove, type ChannelType } from "@alook/shared"
-import { getActiveAccountUnreadProjection } from "@/hooks/community/account-unread-projection"
// Prefix marks an optimistic row so every consumer can tell it from a real
// `ch_…` id without a separate flag, and guarantees it never collides with one.
@@ -103,7 +102,7 @@ export function useCreateChannel() {
const position = Math.max(-1, ...rows.map((row) => row.position)) + 1
pending = { id, serverId: args.serverId, categoryId, name: args.name.trim(), type: args.type, resourceComplete: false,
parentChannelId: null, parentMessageId: null, creatorId: db.accountId,
- position, archived: false, muted: false, unread: false, tags: [], pending: true, lastMessageAt: null }
+ position, archived: false, muted: false, tags: [], pending: true, lastMessageAt: null }
db.collections.channels.insert(pending)
}, async (proof, options) => {
const result = await apiFetch<CreateChannelResult>("/api/community/channels", { method: "POST", body: JSON.stringify({ type: args.type, serverId: args.serverId, categoryId, name: args.name }), ...options })
@@ -183,7 +182,6 @@ export function useDeleteChannel() {
}, async (proof, options) => {
await apiFetch(`/api/community/channels/${args.channelId}`, { method: "DELETE", ...options })
origin.assert(proof.token)
- getActiveAccountUnreadProjection(queryClient).retireAccessScope({ kind: "channel", channelId: args.channelId })
retireCommunityChannelReading(origin.registry!, args.channelId, { reason: "resource-deleted", serverId: args.serverId })
}),
onSettled: (_data, error, args) => settleTree(origin, queryClient, args, error),
diff --git a/src/web/src/hooks/community/mutations/forum-commands.dom.test.ts b/src/web/src/hooks/community/mutations/forum-commands.dom.test.ts
index 1950c3a89..f87c4c32f 100644
--- a/src/web/src/hooks/community/mutations/forum-commands.dom.test.ts
+++ b/src/web/src/hooks/community/mutations/forum-commands.dom.test.ts
@@ -1,3 +1,4 @@
+import { seedCommunityAttentionScope } from "@/test/community-query-owner"
import { createElement, useLayoutEffect, type PropsWithChildren } from "react"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { skipToken, useQuery, type InfiniteData } from "@tanstack/react-query"
@@ -12,7 +13,6 @@ import { mapForumFeedPages } from "../use-forum-feed"
import { useForumTags } from "../use-channel-panels"
import { normalizeThreadResources, forumFeedWindow, forumFeedMatchesTags, type ForumFeedPage, type ForumFeedTransportPage } from "../forum-feed-window"
import { getForumSidebarBase } from "../use-forum-sidebar-threads"
-import { getAccountUnreadProjection } from "../account-unread-projection"
import { applyForumPostUnitClientEffects } from "../community-ws/channel-scope-projection"
import { useCreateForumThread, useUpdatePostTags, useDeleteForumThread } from "./forum"
@@ -269,10 +269,10 @@ describe("Native forum tag transactions", () => {
describe("Native forum post deletion", () => {
it("clears local stream, unread and active route once without requiring a self WS frame", async () => {
- const view = await setup(), projection = getAccountUnreadProjection(view.client, view.registry.accountId!)
+ const view = await setup()
const disk = vi.spyOn(view.registry, "retireReadingDisk").mockResolvedValue(undefined)
act(() => {
- projection.recordArrival({ channelId: "p2", serverId: "server_1", seq: 1 })
+ seedCommunityAttentionScope(view.client, { channelId: "p2", serverId: "server_1", seq: 1 })
view.runtime.ui.actions.setCurrentServerId("server_1"); view.runtime.ui.actions.setCurrentChannelId("p2")
view.runtime.ui.actions.registerUiHandlers({ replacePath: view.navigate })
const message = { id: "opener_p2", seq: 1, type: "chat" as const, authorId: "u1", authorName: "Alice", content: "Post" }
@@ -288,8 +288,8 @@ describe("Native forum post deletion", () => {
expect(mocks.clearLastChannel).toHaveBeenCalledOnce()
expect(view.navigate).toHaveBeenCalledOnce()
expect(view.navigate).toHaveBeenCalledWith("/c/channels/server_1/forum_1")
- expect(projection.projectUnread("servers", "p2", false)).toBe(false)
- expect(projection.projectUnread("inbox-unreads", "p2", true, 1)).toBe(false)
+ expect(Boolean(view.registry.collections.attentionScopes.get("p2")?.ordinaryUnread)).toBe(false)
+ expect(Boolean(view.registry.collections.attentionScopes.get("p2")?.ordinaryUnread)).toBe(false)
act(() => applyForumPostUnitClientEffects(view.client, { serverId: "server_1", forumChannelId: "forum_1", childChannelId: "p2", openerMessageId: "opener_p2" }))
expect(mocks.clearLastChannel).toHaveBeenCalledOnce(); expect(view.navigate).toHaveBeenCalledOnce()
expect(disk).toHaveBeenCalledOnce()
@@ -306,8 +306,8 @@ describe("Native forum post deletion", () => {
expect(view.client.getQueryState(communityKeys.forumFeed("forum_1", null))?.isInvalidated).toBe(true)
})
it("restores canonical post/sidebar and exact original ID windows on DELETE failure", async () => {
- const view = await setup(), projection = getAccountUnreadProjection(view.client, view.registry.accountId!)
- projection.recordArrival({ channelId: "p2", serverId: "server_1", seq: 1 })
+ const view = await setup()
+ seedCommunityAttentionScope(view.client, { channelId: "p2", serverId: "server_1", seq: 1 })
view.client.setQueryData(communityKeys.channelMeta("server_1", "p2"), { id: "p2" })
const keys = [communityKeys.channelMessages("forum_1"), communityKeys.forumFeed("forum_1", null), communityKeys.forumSidebarThreads("server_1"), communityKeys.channelMeta("server_1", "p2")], before = keys.map((key) => view.client.getQueryData(key)), sidebar = getForumSidebarBase(view.client, "server_1")
const { held, request } = await begin(view, "remove")
@@ -316,8 +316,8 @@ describe("Native forum post deletion", () => {
await waitFor(() => expect(view.view.result.current.all.map(({ id }) => id)).toEqual(["before", "p2", "after"]))
keys.forEach((key, index) => expect(view.client.getQueryData(key)).toEqual(before[index]))
expect(getForumSidebarBase(view.client, "server_1")).toEqual(sidebar)
- expect(projection.projectUnread("servers", "p2", false)).toBe(true)
- expect(projection.projectUnread("inbox-unreads", "p2", true, 1)).toBe(true)
+ expect(Boolean(view.registry.collections.attentionScopes.get("p2")?.ordinaryUnread)).toBe(true)
+ expect(Boolean(view.registry.collections.attentionScopes.get("p2")?.ordinaryUnread)).toBe(true)
})
})
diff --git a/src/web/src/hooks/community/mutations/forum-post-owner.dom.test.tsx b/src/web/src/hooks/community/mutations/forum-post-owner.dom.test.tsx
index 9269f353c..b4b1f49f3 100644
--- a/src/web/src/hooks/community/mutations/forum-post-owner.dom.test.tsx
+++ b/src/web/src/hooks/community/mutations/forum-post-owner.dom.test.tsx
@@ -56,7 +56,7 @@ async function mount() {
const args = { serverId: "server", forumChannelId: "forum", threadId: "child", openerMessageId: "opener" }
function command() { return remove.mutateAsync(args).catch((error) => error) }
async function pending() { await waitFor(() => expect(api.mock.calls.some(([, options]) => options.method === "DELETE")).toBe(true)) }
-function wsDelete(qc: QueryClient) { const runtime = getCommunityRuntime(qc); dispatchCommunityWsEvent({ type: "community:channel.delete", serverId: "server", channelId: "child", parentChannelId: "forum", parentMessageId: "opener" }, { deliveryMode: "single", queryClient: qc, communityStore: runtime.ui, wsStore: runtime.ws, sub: {}, viewerUserIdRef: { current: sdk.id }, matchesFocus: () => false, scheduleInboxInvalidate: vi.fn() }) }
+function wsDelete(qc: QueryClient) { const runtime = getCommunityRuntime(qc); dispatchCommunityWsEvent({ type: "community:channel.delete", serverId: "server", channelId: "child", parentChannelId: "forum", parentMessageId: "opener" }, { deliveryMode: "single", queryClient: qc, communityStore: runtime.ui, wsStore: runtime.ws, sub: {}, viewerUserIdRef: { current: sdk.id }, matchesFocus: () => false }) }
beforeEach(async () => { await clearAllPersistedCaches(); api.mockReset(); sdk.id = "A"; navigate.mockClear(); client = undefined as unknown as QueryClient })
describe("actual native forum post-unit deletion", () => {
it("hides both canonical identities optimistically and restores them on ordinary failure", async () => {
diff --git a/src/web/src/hooks/community/mutations/forum.ts b/src/web/src/hooks/community/mutations/forum.ts
index 11333e042..686cea84c 100644
--- a/src/web/src/hooks/community/mutations/forum.ts
+++ b/src/web/src/hooks/community/mutations/forum.ts
@@ -68,7 +68,7 @@ export function useCreateForumThread() {
const parent = origin.registry!.collections.channels.get(channelId)
if (parent && structure.message) {
publishCommunityMessages(queryClient, { channelId, messages: [projectPostedMessage(structure.message, `${nonce}:opener`, channelId)], proof: { token, signal: assertActive?.signal } })
- publishCommunityCreatedChannel(queryClient, { id: structure.threadId, serverId: parent.serverId, categoryId: null, name, type: "thread", parentChannelId: channelId, parentMessageId: structure.message.id, creatorId: structure.message.authorId, position: 0, archived: false, muted: false, unread: false, tags: [], pending: false, resourceComplete: false }, { token, signal: assertActive?.signal })
+ publishCommunityCreatedChannel(queryClient, { id: structure.threadId, serverId: parent.serverId, categoryId: null, name, type: "thread", parentChannelId: channelId, parentMessageId: structure.message.id, creatorId: structure.message.authorId, position: 0, archived: false, muted: false, tags: [], pending: false, resourceComplete: false }, { token, signal: assertActive?.signal })
}
assert()
const reply = await origin.request<{ message: PostedMessage }>(token, `/api/community/channels/${structure.threadId}/messages`, {
diff --git a/src/web/src/hooks/community/mutations/message-field-owner.dom.test.tsx b/src/web/src/hooks/community/mutations/message-field-owner.dom.test.tsx
index 119ff53ef..670ab0adf 100644
--- a/src/web/src/hooks/community/mutations/message-field-owner.dom.test.tsx
+++ b/src/web/src/hooks/community/mutations/message-field-owner.dom.test.tsx
@@ -67,7 +67,7 @@ describe("actual canonical message field command", () => {
act(() => dispatchCommunityWsEvent(kind === "edit"
? { type: "community:message.edited", messageId: "m1", channelId: "c1", content: "newer-ws" }
: { type: "community:reaction.add", messageId: "m1", channelId: "c1", emoji: "👍", userId: "peer" },
- { deliveryMode: "single", queryClient: original, communityStore: runtime.ui, wsStore: runtime.ws, sub: {}, viewerUserIdRef: { current: "A" }, matchesFocus: () => false, scheduleInboxInvalidate: vi.fn() }))
+ { deliveryMode: "single", queryClient: original, communityStore: runtime.ui, wsStore: runtime.ws, sub: {}, viewerUserIdRef: { current: "A" }, matchesFocus: () => false }))
expect(original.getQueryData(communityKeys.message("m1"))).toBe("m1")
if (kind === "edit") expect(screen.getByTestId("exact").textContent).toBe("newer-ws")
else expect(getCommunityDbRegistry(original)!.collections.messages.get("m1")?.reactions).toMatchObject([{ emoji: "👍", userIds: ["peer"] }])
diff --git a/src/web/src/hooks/community/mutations/messages.dom.test.ts b/src/web/src/hooks/community/mutations/messages.dom.test.ts
index 61540b16a..2cb7a0a4a 100644
--- a/src/web/src/hooks/community/mutations/messages.dom.test.ts
+++ b/src/web/src/hooks/community/mutations/messages.dom.test.ts
@@ -293,7 +293,7 @@ describe("useSendMessage — happy path", () => {
attachments: [{ ...attachment, url: remoteAttachment.url }],
} }, { deliveryMode: "single", queryClient: capturedQc, communityStore: runtime.ui, wsStore: runtime.ws,
sub: { channelId: scope.id }, viewerUserIdRef: { current: "u_me" },
- matchesFocus: event => event.channelId === scope.id, scheduleInboxInvalidate: vi.fn() }) })
+ matchesFocus: event => event.channelId === scope.id }) })
} else if (stage === "matchingBase") {
const { channelMessagesQueryFn } = await import("@/hooks/community/use-messages")
const { decodeCommunityReadResponse } = await import("@/lib/community/read-response")
@@ -1200,21 +1200,6 @@ describe("useDeleteMention — rollback", () => {
limit: 100,
truncated: false,
})
- const { getActiveAccountUnreadProjection } = await import(
- "@/hooks/community/account-unread-projection"
- )
- const projection = getActiveAccountUnreadProjection(capturedQc)
- projection.setNotificationPolicy({})
- for (const attentionId of [reply.id, mention.id]) {
- projection.recordArrival({
- channelId: "ch_1",
- serverId: "srv_1",
- messageId: "msg_1",
- attentionId,
- seq: 4,
- isMention: true,
- })
- }
mountHook(() => mod.useDeleteMention())
let fail!: (error: Error) => void
apiFetchMock.mockImplementation((path: string) => path === "/api/community/users/me/attention"
@@ -1234,13 +1219,6 @@ describe("useDeleteMention — rollback", () => {
expect(canonicalRegistry!.collections.attentionItems.get("mention:mention-1")).toBeDefined()
expect(canonicalRegistry!.collections.attentionScopes.get("ch_1")?.attentionCount).toBe(1)
})
- expect(projection.projectUnread(
- "inbox-mentions", "ch_1", true, 4, "mentions", null, true, mention.id,
- )).toBe(true)
- expect(projection.projectServerMentionCount("srv_1", [{
- channelId: "ch_1", count: 1, lastSeq: 4,
- }])).toBe(1)
-
await act(async () => { fail(new Error("retry direct")); await replyPending })
expect(cachedAttentionItems().map((item) => item.id).sort()).toEqual([
"mention:mention-1", "mention:reply-1",
@@ -1255,12 +1233,6 @@ describe("useDeleteMention — rollback", () => {
expect(canonicalRegistry!.collections.attentionItems.get("mention:reply-1")).toBeDefined()
expect(canonicalRegistry!.collections.attentionScopes.get("ch_1")?.attentionCount).toBe(1)
})
- expect(projection.projectUnread(
- "inbox-mentions", "ch_1", true, 4, "mentions", null, true, reply.id,
- )).toBe(true)
- expect(projection.projectServerMentionCount("srv_1", [{
- channelId: "ch_1", count: 1, lastSeq: 4,
- }])).toBe(0)
await act(async () => { fail(new Error("cleanup")); await mentionPending })
expect(cachedAttentionItems().map((item) => item.id).sort()).toEqual([
"mention:mention-1", "mention:reply-1",
@@ -1294,18 +1266,6 @@ describe("useDeleteMention — rollback", () => {
limit: 100,
truncated: false,
})
- const { getActiveAccountUnreadProjection } = await import(
- "@/hooks/community/account-unread-projection"
- )
- const projection = getActiveAccountUnreadProjection(capturedQc)
- projection.recordArrival({
- channelId: "ch_1",
- serverId: "srv_1",
- messageId: "msg_1",
- attentionId: "men_1",
- seq: 4,
- isMention: true,
- })
mountHook(() => mod.useDeleteMention())
let fail!: (error: Error) => void
apiFetchMock.mockImplementation((path: string) => path === "/api/community/users/me/attention"
@@ -1318,13 +1278,10 @@ describe("useDeleteMention — rollback", () => {
ordinaryUnread: true,
attentionCount: 0,
})
- expect(projection.projectUnread("inbox-unreads", "ch_1", false)).toBe(true)
- expect(projection.projectUnread("inbox-mentions", "ch_1", false)).toBe(false)
await act(async () => { fail(new Error("boom")); await pending })
expect(canonicalRegistry!.collections.attentionItems.get("mention:men_1")).toBeDefined()
expect(canonicalRegistry!.collections.attentionScopes.get("ch_1")?.attentionCount).toBe(1)
- expect(projection.projectUnread("inbox-mentions", "ch_1", false)).toBe(true)
})
it("restores mention on failure", async () => {
@@ -1352,7 +1309,7 @@ describe("useDeleteMention — rollback", () => {
expect(toastMock).toHaveBeenCalledWith("boom")
})
- it("invalidates communityKeys.servers() on success so the rail badge decrements", async () => {
+ it("keeps server structure unchanged after a native mention dismissal", async () => {
capturedQc.setQueryData(communityKeys.inboxMentions(), {
mentions: [{ id: "men_1" }],
})
@@ -1365,7 +1322,7 @@ describe("useDeleteMention — rollback", () => {
const key = c[0]?.queryKey as unknown[] | undefined
return Array.isArray(key) && key.length === 2 && key[0] === "community" && key[1] === "servers"
})
- expect(serversInvalidates).toHaveLength(1)
+ expect(serversInvalidates).toHaveLength(0)
})
})
@@ -1386,7 +1343,7 @@ describe("confirmed send failures", () => {
dispatchCommunityWsEvent({ type: "community:message.create", serverId: scope.serverId, channelId: scope.id,
message: { ...confirmed, authorName: "Me", authorAvatar: "M", authorAvatarVersion: 0, createdAt: "2026-08-07T10:00:00.000Z" } }, {
deliveryMode: "single", queryClient: capturedQc, communityStore: canonicalRegistry.runtime.ui, wsStore: canonicalRegistry.runtime.ws,
- sub: { channelId: scope.id }, viewerUserIdRef: { current: "u_me" }, matchesFocus: event => event.channelId === scope.id, scheduleInboxInvalidate: vi.fn(),
+ sub: { channelId: scope.id }, viewerUserIdRef: { current: "u_me" }, matchesFocus: event => event.channelId === scope.id,
})
} else {
ingestMessages(canonicalRegistry, scope.id, [confirmed])
diff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.ts
index beb05b4e1..e5cd50855 100644
--- a/src/web/src/hooks/community/mutations/messages.ts
+++ b/src/web/src/hooks/community/mutations/messages.ts
@@ -40,12 +40,6 @@ import {
patchForumSidebarActivityExact,
} from "@/hooks/community/use-forum-sidebar-threads"
import { isBlocked, type MentionType, type CommunityResourceProfile } from "@alook/shared"
-import {
- getActiveAccountUnreadProjection,
- type AccountUnreadDomain,
- type AccountUnreadDismissToken,
- type MarkAllToken,
-} from "@/hooks/community/account-unread-projection"
import { reconcileAccountReadState } from "@/hooks/community/community-ws/read-state-reconciliation"
import { reconcileAccountAttention } from "@/hooks/community/use-account-attention"
@@ -53,11 +47,11 @@ import {
clearAttentionOptimistically,
commitAttentionOptimisticSnapshot,
commitAttentionItemsOptimisticSnapshot,
- getCanonicalCommunityMessages,
removeAttentionItemsOptimistically,
restoreAttentionOptimisticDomains,
restoreAttentionOptimisticSnapshot,
restoreAttentionItemsOptimisticSnapshot,
+ type AttentionDomain,
type AttentionIntent,
} from "@/lib/community-db/sync"
@@ -350,7 +344,7 @@ export function useCreateThread() {
await Promise.all([origin.registry!.collections.channels.preload(), origin.registry!.collections.messages.preload()])
origin.assert(token); args.assertActive?.()
const data = await origin.request<CreateThreadResult>(token, "/api/community/channels", { method: "POST", signal: args.assertActive?.signal, assertActive: args.assertActive, body: JSON.stringify({ type: "thread", messageId: args.messageId, name: args.name }) })
- publishCommunityCreatedChannel(queryClient, { id: data.id, serverId: args.serverId, categoryId: null, name: args.name, type: "thread", parentChannelId: args.channelId, parentMessageId: args.messageId, creatorId: origin.registry!.accountId, position: 0, archived: false, muted: false, unread: false, tags: [], pending: false, messageCount: 0 }, { token, signal: args.assertActive?.signal })
+ publishCommunityCreatedChannel(queryClient, { id: data.id, serverId: args.serverId, categoryId: null, name: args.name, type: "thread", parentChannelId: args.channelId, parentMessageId: args.messageId, creatorId: origin.registry!.accountId, position: 0, archived: false, muted: false, tags: [], pending: false, messageCount: 0 }, { token, signal: args.assertActive?.signal })
if (args.resource && queryClient.getQueryCache().find({ queryKey: communityKeys.threads(args.channelId), exact: true }) === args.resource) void queryClient.invalidateQueries({ queryKey: communityKeys.threads(args.channelId), exact: true }, { cancelRefetch: false }).catch(() => undefined)
return data
},
@@ -365,14 +359,12 @@ export function useCreateThread() {
export function useMarkAllInboxRead() {
const origin = useCommunityMutationOrigin()
const queryClient = useQueryClient()
- const unreadProjection = getActiveAccountUnreadProjection(queryClient)
type ReadAllResponse = { revision: number }
type DomainResult = {
- domain: AccountUnreadDomain
+ domain: AttentionDomain
result: PromiseSettledResult<ReadAllResponse>
}
type MarkAllContext = {
- tokens: Map<AccountUnreadDomain, MarkAllToken>
snapshot?: AttentionIntent
}
type Original = ReturnType<typeof origin.begin>["token"]
@@ -407,11 +399,6 @@ export function useMarkAllInboxRead() {
await Promise.all([registry!.collections.attentionScopes.preload(), registry!.collections.attentionItems.preload()])
origin.assert(token)
return {
- tokens: new Map<AccountUnreadDomain, MarkAllToken>([
- ["channels", unreadProjection.beginMarkAll("channels")],
- ["dms", unreadProjection.beginMarkAll("dms")],
- ["mentions", unreadProjection.beginMarkAll("mentions")],
- ]),
snapshot: registry ? clearAttentionOptimistically(registry) : undefined,
}
},
@@ -419,15 +406,11 @@ export function useMarkAllInboxRead() {
origin.assert(original)
let targetRevision = 0
let firstFailure: unknown
- const failedDomains = new Set<AccountUnreadDomain>()
+ const failedDomains = new Set<AttentionDomain>()
for (const { domain, result } of results) {
- const token = context.tokens.get(domain)
- if (!token) continue
if (result.status === "fulfilled") {
targetRevision = Math.max(targetRevision, result.value?.revision ?? 0)
- unreadProjection.commitMarkAll(token, result.value?.revision ?? 0)
} else {
- unreadProjection.rollbackMarkAll(token)
failedDomains.add(domain)
firstFailure ??= result.reason
}
@@ -441,17 +424,12 @@ export function useMarkAllInboxRead() {
}
}
origin.assert(original)
- if (registry) void reconcileAccountAttention(registry).catch(() => undefined)
if (firstFailure) toastApiError(firstFailure, "Some inbox items could not be marked read")
void reconcileAccountReadState(queryClient, {
- surfaceMode: "all",
targetRevision,
}).catch(() => undefined)
},
onError: (e, original, context) => {
- for (const token of context?.tokens.values() ?? []) {
- unreadProjection.rollbackMarkAll(token)
- }
const registry = origin.registry
if (registry && context?.snapshot) {
restoreAttentionOptimisticSnapshot(registry, context.snapshot)
@@ -460,8 +438,6 @@ export function useMarkAllInboxRead() {
if (isAbortError(e)) return
if (registry) void reconcileAccountAttention(registry).catch(() => undefined)
toastApiError(e, "Failed to mark inbox read")
- void queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })
- void queryClient.invalidateQueries({ queryKey: communityKeys.servers() })
},
})
return {
@@ -475,15 +451,12 @@ export type DeleteMentionArgs = { mentionId: string }
export function useDeleteMention() {
const origin = useCommunityMutationOrigin()
- const queryClient = useQueryClient()
- const unreadProjection = getActiveAccountUnreadProjection(queryClient)
type Original = ReturnType<typeof origin.begin>["token"]
const mutation = useMutation<
{ revision: number },
Error,
{ input: DeleteMentionArgs; original: Original },
{
- token?: AccountUnreadDismissToken
attentionSnapshot?: AttentionIntent
}
>({ meta: { observabilityAction: "mention.dismiss" },
@@ -500,7 +473,6 @@ export function useDeleteMention() {
origin.assert(original)
await Promise.all([registry!.collections.attentionScopes.preload(), registry!.collections.attentionItems.preload()])
origin.assert(original)
- const removed = Array.from(registry!.collections.attentionItems.values()).find((item) => item.sourceId === args.mentionId && (item.kind === "mention" || item.kind === "reply"))
const attentionSnapshot = registry
? removeAttentionItemsOptimistically(
registry,
@@ -510,35 +482,19 @@ export function useDeleteMention() {
),
)
: undefined
- const message = removed?.messageId
- ? getCanonicalCommunityMessages(queryClient)
- .find((candidate) => candidate.id === removed.messageId)
- : undefined
- const token = removed?.scopeId && message?.seq !== undefined
- ? unreadProjection.beginDismissMention({
- mentionId: args.mentionId,
- channelId: removed.scopeId,
- seq: message.seq,
- countsServerMention: removed.kind === "mention",
- })
- : undefined
- return { token, attentionSnapshot }
+ return { attentionSnapshot }
},
onSuccess: async (result, { original }, context) => {
origin.assert(original)
- if (context.token) unreadProjection.commitDismissMention(context.token, result?.revision)
const registry = origin.registry
if (registry && context.attentionSnapshot) {
await commitAttentionItemsOptimisticSnapshot(registry, context.attentionSnapshot)
origin.assert(original)
void reconcileAccountAttention(registry).catch(() => undefined)
}
- // Deleting a mention row removes it from the unread-mention aggregate
- // that feeds the server rail badge — refresh so the count drops.
- void queryClient.invalidateQueries({ queryKey: communityKeys.servers() })
+
},
onError: (err, { original }, ctx) => {
- if (ctx?.token) unreadProjection.rollbackDismissMention(ctx.token)
const registry = origin.registry
if (registry && ctx?.attentionSnapshot) {
restoreAttentionItemsOptimisticSnapshot(registry, ctx.attentionSnapshot)
diff --git a/src/web/src/hooks/community/mutations/notifications.dom.test.ts b/src/web/src/hooks/community/mutations/notifications.dom.test.ts
index a906934d0..ec1a5d82d 100644
--- a/src/web/src/hooks/community/mutations/notifications.dom.test.ts
+++ b/src/web/src/hooks/community/mutations/notifications.dom.test.ts
@@ -1,3 +1,4 @@
+import { seedCommunityAttentionScope } from "@/test/community-query-owner"
import { createElement, type PropsWithChildren } from "react"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { USE_SERVER_DEFAULT } from "@alook/shared"
@@ -8,7 +9,6 @@ import { communityKeys } from "@/lib/query-keys"
import type { CommunityDbRegistry } from "@/lib/community-db/collections"
import { notificationSettingKey } from "@/lib/community-db/schema"
import { captureCommunityLiveSnapshotToken, publishCommunityNotificationSetting } from "@/lib/community-db/sync"
-import { getActiveAccountUnreadProjection } from "../account-unread-projection"
import { useNotificationSettings } from "../use-notification-settings"
import { useSetChannelNotif, useSetServerNotifLevel } from "./notifications"
@@ -50,23 +50,23 @@ beforeEach(() => { apiFetch.mockReset() })
describe("notification mutation cache refresh", () => {
it("changes only reversible eligibility and restores it on failure", async () => {
const view = await setup("server", [serverSetting()])
- const projection = getActiveAccountUnreadProjection(view.client)
- projection.recordArrival({ channelId: "channel_1", serverId: "server_1", seq: 2 })
- const before = projection.inspectForTests(), held = deferred()
+
+ seedCommunityAttentionScope(view.client, { channelId: "channel_1", serverId: "server_1", seq: 2 })
+ const before = [...view.registry.collections.readStates.values()], held = deferred()
holdWrites(held, view.registry)
let request!: Promise<unknown>
act(() => { request = view.rendered.result.current.command.mutateAsync({ serverId: "server_1", level: "Nothing" }).catch((error) => error) })
- await waitFor(() => expect(projection.projectUnread("servers", "channel_1", false)).toBe(false))
- expect(projection.inspectForTests().sourceCount).toBe(before.sourceCount)
- expect(projection.inspectForTests().readState).toEqual(before.readState)
+ await waitFor(() => expect([...view.registry.collections.notificationSettings.values()].find(row => row.serverId === "server_1")?.level).toBe("nothing"))
+ expect(view.registry.collections.attentionScopes.get("channel_1")?.ordinaryUnread).toBe(true)
+ expect([...view.registry.collections.readStates.values()]).toEqual(before)
await act(async () => { held.reject(new Error("failed")); await request })
- await waitFor(() => expect(projection.projectUnread("servers", "channel_1", false)).toBe(true))
+ await waitFor(() => expect(Boolean(view.registry.collections.attentionScopes.get("channel_1")?.ordinaryUnread)).toBe(true))
})
it("keeps absent canonical settings absent after a reversible server overlay fails", async () => {
const view = await setup(), held = deferred()
- const projection = getActiveAccountUnreadProjection(view.client)
- projection.recordArrival({ channelId: "channel_1", serverId: "server_1", seq: 2 })
+
+ seedCommunityAttentionScope(view.client, { channelId: "channel_1", serverId: "server_1", seq: 2 })
view.client.removeQueries({ queryKey: communityKeys.notificationSettings(), exact: true })
holdWrites(held, view.registry)
let request!: Promise<unknown>
@@ -75,7 +75,7 @@ describe("notification mutation cache refresh", () => {
expect(view.registry.collections.notificationSettings.size).toBe(1)
await act(async () => { held.reject(new Error("failed")); await request })
await waitFor(() => expect(view.registry.collections.notificationSettings.size).toBe(0))
- expect(projection.projectUnread("servers", "channel_1", false)).toBe(true)
+ expect(Boolean(view.registry.collections.attentionScopes.get("channel_1")?.ordinaryUnread)).toBe(true)
})
it("rolls back one server field without clobbering a concurrent success", async () => {
@@ -89,17 +89,17 @@ describe("notification mutation cache refresh", () => {
await waitFor(() => expect(view.rendered.result.current.settings.server).toMatchObject({ server_1: "All Messages", server_2: "Nothing" }))
})
- it("refreshes settings, inbox, and the account read-state resource after a server change", async () => {
+ it("refreshes only canonical account attention after a server policy change", async () => {
const view = await setup()
- const keys = [communityKeys.inbox(), communityKeys.servers(), communityKeys.accountReadStateSnapshot()]
+ const keys = [communityKeys.accountAttention()]
for (const key of keys) view.client.setQueryData(key, { ids: [] })
await act(async () => { await view.rendered.result.current.command.mutateAsync({ serverId: "server_1", level: "Nothing" }) })
for (const key of keys) expect(view.client.getQueryState(key)?.isInvalidated).toBe(true)
})
- it("refreshes the account read-state resource after a parent channel change", async () => {
+ it("refreshes only canonical account attention after a parent policy change", async () => {
const view = await setup("channel")
- const keys = [communityKeys.inbox(), communityKeys.servers(), communityKeys.accountReadStateSnapshot()]
+ const keys = [communityKeys.accountAttention()]
const unrelated = ["application", "unrelated"]
for (const key of [...keys, unrelated]) view.client.setQueryData(key, { ids: [] })
await act(async () => { await view.rendered.result.current.command.mutateAsync({ channelId: "parent_1", level: "Nothing" }) })
diff --git a/src/web/src/hooks/community/mutations/notifications.ts b/src/web/src/hooks/community/mutations/notifications.ts
index 8d0c28d2e..05af143e3 100644
--- a/src/web/src/hooks/community/mutations/notifications.ts
+++ b/src/web/src/hooks/community/mutations/notifications.ts
@@ -61,7 +61,7 @@ function useNotificationCommand(kind: "server" | "channel") {
input.assertActive?.()
const view = source.capture(); view()
const id = "serverId" in input ? input.serverId : input.channelId
- return { input, id, original: origin.begin().token, view, resources: client.getQueryCache().findAll({ predicate: (query) => [communityKeys.notificationSettings(), communityKeys.inbox(), communityKeys.servers()].some((key) => key.length <= query.queryKey.length && key.every((part, i) => Object.is(part, query.queryKey[i]))) || query.queryKey.includes("read-state-snapshot") }) }
+ return { input, id, original: origin.begin().token, view, resources: client.getQueryCache().findAll({ predicate: (query) => [communityKeys.notificationSettings(), communityKeys.accountAttention()].some((key) => key.length <= query.queryKey.length && key.every((part, i) => Object.is(part, query.queryKey[i]))) }) }
}, [origin, client, source])
const assertCurrent = useCallback((args: Intent) => { origin.assert(args.original); args.view(); args.input.assertActive?.() }, [origin])
return useNativeMutationFacade(native, capture, assertCurrent)
diff --git a/src/web/src/hooks/community/mutations/server-commands.dom.test.ts b/src/web/src/hooks/community/mutations/server-commands.dom.test.ts
index 61a783a09..67a7521ec 100644
--- a/src/web/src/hooks/community/mutations/server-commands.dom.test.ts
+++ b/src/web/src/hooks/community/mutations/server-commands.dom.test.ts
@@ -1,3 +1,4 @@
+import { seedCommunityAttentionScope } from "@/test/community-query-owner"
import { createElement, type PropsWithChildren } from "react"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { act, renderHook, waitFor } from "@/test/react-dom-harness"
@@ -5,7 +6,6 @@ import { CommunityTestProvider } from "@/test/community-owner-fixture"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
import { communityKeys } from "@/lib/query-keys"
import { ingestServers, ingestServerDetail, captureCommunityLiveSnapshotToken, publishCommunityCreatedChannel } from "@/lib/community-db/sync"
-import { getActiveAccountUnreadProjection } from "../account-unread-projection"
import { useServer, useServers } from "../use-servers"
import { createOwnerServerDeleteRouteToken, observeOwnerServerDeleteRouteCommit, claimOwnerServerDeleteNavigation, claimOwnerServerDeleteScopeFlush, isOwnerServerDeleteRouteProtected } from "@/lib/community/eject-server"
import { flushOwnerServerDeleteRouteCommit } from "../community-ws/scope-eviction"
@@ -65,14 +65,14 @@ function seedPrivateScope(view: View) {
describe("Native server membership commands", () => {
it("fences every unread source in the departing scope and rolls back atomically", async () => {
- const view = await setup(), projection = getActiveAccountUnreadProjection(view.client)
- projection.recordArrival({ channelId: "c1", serverId: "srv_1", seq: 1 })
- projection.recordArrival({ channelId: "c2", serverId: "srv_2", seq: 1 })
+ const view = await setup()
+ seedCommunityAttentionScope(view.client, { channelId: "c1", serverId: "srv_1", seq: 1 })
+ seedCommunityAttentionScope(view.client, { channelId: "c2", serverId: "srv_2", seq: 1 })
const { request } = await begin(view, "leave")
- expect(projection.projectUnread("servers", "c1", false)).toBe(false)
- expect(projection.projectUnread("servers", "c2", false)).toBe(true)
+ expect(view.view.result.current.rail.servers.some(server => server.id === "srv_1")).toBe(false)
+ expect(view.view.result.current.rail.servers.some(server => server.id === "srv_2" && server.unread)).toBe(true)
await act(async () => { view.held.reject(new Error("failed")); await request })
- expect(projection.projectUnread("servers", "c1", false)).toBe(true)
+ expect(view.view.result.current.rail.servers.some(server => server.id === "srv_1" && server.unread)).toBe(true)
})
it.each(["leave", "remove"] as const)("%s hides the rail row optimistically and restores it on failure", async (operation) => {
const view = await setup(), { request } = await begin(view, operation)
@@ -158,7 +158,7 @@ describe("Native server field commands", () => {
expect(view.registry.collections.servers.get("srv_2")).toBe(untouched)
await act(async () => { view.held.resolve(); await request })
await waitFor(() => expect(view.view.result.current.detail.server).toMatchObject({ name: "new", description: "new description" }))
- expect(view.registry.collections.servers.get("srv_2")).toMatchObject({ name: "untouched", description: "unchanged description", mentions: 4 })
+ expect(view.registry.collections.servers.get("srv_2")).toMatchObject({ name: "untouched", description: "unchanged description" })
})
it("invalidates the original channel-ref directory after settling", async () => {
const view = await setup(); let request!: Promise<unknown>
diff --git a/src/web/src/hooks/community/mutations/server-tree-owner.dom.test.tsx b/src/web/src/hooks/community/mutations/server-tree-owner.dom.test.tsx
index 644fc8054..38dbef6e4 100644
--- a/src/web/src/hooks/community/mutations/server-tree-owner.dom.test.tsx
+++ b/src/web/src/hooks/community/mutations/server-tree-owner.dom.test.tsx
@@ -1,3 +1,4 @@
+import { seedCommunityAttentionScope } from "@/test/community-query-owner"
import { useLayoutEffect } from "react"
import "fake-indexeddb/auto"
import React, { useMemo } from "react"
@@ -16,7 +17,6 @@ import { flushOwnerServerDeleteRouteCommit } from "../community-ws/scope-evictio
import { dispatchCommunityWsEvent } from "../community-ws/registry"
import { getCommunityRuntime } from "@/stores/community/runtime"
import { useCreateChannel, useCreateCategory, useDeleteCategory, useReorderChannels, useUpdateCategory, useReorderCategories, useDeleteChannel } from "./channels"
-import { getActiveAccountUnreadProjection } from "../account-unread-projection"
const api = vi.hoisted(() => vi.fn())
const sdk = vi.hoisted(() => ({ id: "A" }))
vi.mock("@/lib/api/client", () => ({ apiFetch: api }))
@@ -281,7 +281,7 @@ describe("actual canonical server and tree command owner", () => {
let result!: Promise<unknown>; act(() => { result = remove.mutateAsync({ serverId: "s1" }).catch((error) => error) })
await waitFor(() => expect(api.mock.calls.some(([, o]) => o.method === "DELETE")).toBe(true))
const runtime = getCommunityRuntime(original)
- act(() => dispatchCommunityWsEvent({ type: "community:server.delete", serverId: "s1" }, { queryClient: original, deliveryMode: "single", communityStore: runtime.ui, wsStore: runtime.ws, sub: {}, viewerUserIdRef: { current: "A" }, matchesFocus: () => false, scheduleInboxInvalidate: vi.fn() }))
+ act(() => dispatchCommunityWsEvent({ type: "community:server.delete", serverId: "s1" }, { queryClient: original, deliveryMode: "single", communityStore: runtime.ui, wsStore: runtime.ws, sub: {}, viewerUserIdRef: { current: "A" }, matchesFocus: () => false }))
expect(getCommunityDbRegistry(original)!.collections.channels.has("c1")).toBe(true)
expect(screen.getByTestId("server-detail").textContent).toBe("original|before")
await act(async () => { resolve(undefined); expect(await result).toBeUndefined() })
@@ -355,14 +355,14 @@ describe("actual canonical server and tree command owner", () => {
})
it.each(["success", "failure"] as const)("native channel DELETE %s retires unread only after confirmed success", async (outcome) => {
const { resolve, reject, original } = await mount()
- const projection = getActiveAccountUnreadProjection(original)
- act(() => projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 }))
+
+ act(() => seedCommunityAttentionScope(original, { channelId: "c1", serverId: "s1", seq: 1 }))
let result!: Promise<unknown>; act(() => { result = deleteChannel.mutateAsync({ serverId: "s1", channelId: "c1" }).catch((error) => error) })
await waitFor(() => expect(screen.getByTestId("tree").textContent).not.toContain("c1=general"))
- expect(projection.projectUnread("servers", "c1", false)).toBe(true)
+ expect(Boolean(getCommunityDbRegistry(original)!.collections.attentionScopes.get("c1")?.ordinaryUnread)).toBe(true)
await act(async () => { if (outcome === "success") resolve(undefined); else reject(new Error("denied")); await result })
expect(getCommunityDbRegistry(original)!.collections.channels.has("c1")).toBe(outcome === "failure")
- expect(projection.projectUnread("servers", "c1", false)).toBe(outcome === "failure")
+ expect(Boolean(getCommunityDbRegistry(original)!.collections.attentionScopes.get("c1")?.ordinaryUnread)).toBe(outcome === "failure")
})
it("publishes the canonical versioned native icon through the original qualified FormData request", async () => {
const { resolve, original } = await mount()
@@ -386,7 +386,7 @@ describe("actual canonical server and tree command owner", () => {
await waitFor(() => expect(screen.getByTestId("server-detail").textContent).toBe("original|before"))
const current = client, runtime = getCommunityRuntime(current)
if (delivery === "ws") {
- act(() => dispatchCommunityWsEvent({ type: "community:server.delete", serverId: "s1" }, { queryClient: current, deliveryMode: "single", communityStore: runtime.ui, wsStore: runtime.ws, sub: {}, viewerUserIdRef: { current: "B" }, matchesFocus: () => false, scheduleInboxInvalidate: vi.fn() }))
+ act(() => dispatchCommunityWsEvent({ type: "community:server.delete", serverId: "s1" }, { queryClient: current, deliveryMode: "single", communityStore: runtime.ui, wsStore: runtime.ws, sub: {}, viewerUserIdRef: { current: "B" }, matchesFocus: () => false }))
} else {
const previous = api.getMockImplementation()!
api.mockImplementation((path: string, options: unknown) => path === "/api/community/servers" ? Promise.resolve({ servers: [] }) : previous(path, options))
diff --git a/src/web/src/hooks/community/mutations/servers.ts b/src/web/src/hooks/community/mutations/servers.ts
index a9e994142..fcbbad47c 100644
--- a/src/web/src/hooks/community/mutations/servers.ts
+++ b/src/web/src/hooks/community/mutations/servers.ts
@@ -4,16 +4,13 @@ import { communityCommandInput, useCommunityCommandMutation, type CommunityComma
import { useCallback } from "react"
import { beginCommunityCommandRevision } from "@/lib/community-db/sync"
import { useCommunityMutationOrigin } from "../community-origin"
+import { communityServerRetirementKey } from "@/lib/community-db/message-access-scope"
import { useQueryClient } from "@tanstack/react-query"
import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import { isAbortError } from "@/lib/errors"
import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle"
import { publishCommunityServerFields, publishCommunityServerMembershipRemoval, type CommunityLiveSnapshotToken } from "@/lib/community-db/sync"
-import {
- getActiveAccountUnreadProjection,
- type AccountUnreadScopeToken,
-} from "@/hooks/community/account-unread-projection"
import {
evictServerChannelScopes,
flushOwnerServerDeleteAfterSuccess,
@@ -99,15 +96,15 @@ function mutateViewerMembership(registry: NonNullable<ReturnType<typeof useCommu
export function useLeaveServer() {
const origin = useCommunityMutationOrigin(), queryClient = useQueryClient()
- const unreadProjection = getActiveAccountUnreadProjection(queryClient)
const assertLeaveSuccess = useCallback((args: CommunityCommandArgs<LeaveServerArgs>) => origin.assertOwner(args.original), [origin])
- return useCommunityCommandMutation<void, Error, LeaveServerArgs, { token: AccountUnreadScopeToken; proof: CommunityLiveSnapshotToken }>(origin, { meta: { observabilityAction: "server.leave" },
+ return useCommunityCommandMutation<void, Error, LeaveServerArgs, { proof: CommunityLiveSnapshotToken }>(origin, { meta: { observabilityAction: "server.leave" },
scope: { id: "community-server-membership" },
+ mutationKey: [...communityServerRetirementKey, "leave"],
onMutate: async (args) => {
const token = args.original
await origin.registry?.ready
origin.assert(token)
- return { proof: token, token: unreadProjection.beginScopeRetirement({ kind: "server", serverId: args.serverId }) }
+ return { proof: token }
},
mutationFn: async (args) => {
const original = args.original, registry = origin.registry!
@@ -125,14 +122,8 @@ export function useLeaveServer() {
transaction.mutate(() => mutateViewerMembership(registry, args.serverId))
try { await transaction.when("settled") } catch (error) { origin.assert(token); throw error }
},
- onError: (_error, _args, context) => {
- if (!context) return
- try { origin.assert(context.proof) } catch { return }
- unreadProjection.rollbackScopeRetirement(context.token)
- },
onSuccess: (_data, args, context) => {
origin.assert(context.proof)
- unreadProjection.commitScopeRetirement(context.token)
evictServerChannelScopes(queryClient, args.serverId)
void queryClient.invalidateQueries({ queryKey: communityKeys.channelRefDirectory(), exact: true, predicate: (query) => args.resources.includes(query) })
},
@@ -141,9 +132,9 @@ export function useLeaveServer() {
export function useDeleteServer(callbacks: DeleteServerCallbacks) {
const origin = useCommunityMutationOrigin(), queryClient = useQueryClient()
- const unreadProjection = getActiveAccountUnreadProjection(queryClient)
- return useCommunityCommandMutation<void, Error, DeleteServerArgs, { token: AccountUnreadScopeToken; proof: CommunityLiveSnapshotToken } & DeleteServerCallbacks & { routeToken: OwnerServerDeleteRouteToken }>(origin, { meta: { observabilityAction: "server.delete" },
+ return useCommunityCommandMutation<void, Error, DeleteServerArgs, { proof: CommunityLiveSnapshotToken } & DeleteServerCallbacks & { routeToken: OwnerServerDeleteRouteToken }>(origin, { meta: { observabilityAction: "server.delete" },
scope: { id: "community-server-membership" },
+ mutationKey: [...communityServerRetirementKey, "delete"],
onMutate: async (args) => {
const token = args.original
await origin.registry?.ready
@@ -151,7 +142,7 @@ export function useDeleteServer(callbacks: DeleteServerCallbacks) {
const routeToken = callbacks.routeToken
if (!routeToken) throw new DOMException("Missing committed server route", "AbortError")
beginOwnerServerDelete(queryClient, args.serverId, routeToken)
- return { ...callbacks, routeToken, proof: token, token: unreadProjection.beginScopeRetirement({ kind: "server", serverId: args.serverId }) }
+ return { ...callbacks, routeToken, proof: token }
},
mutationFn: async (args) => {
const original = args.original, registry = origin.registry!
@@ -173,13 +164,11 @@ export function useDeleteServer(callbacks: DeleteServerCallbacks) {
if (!context) return
cancelOwnerServerDelete(queryClient, args.serverId, context.routeToken)
try { origin.assert(context.proof) } catch { return }
- unreadProjection.rollbackScopeRetirement(context.token)
context.onError?.(error, communityCommandInput(args))
},
onSuccess: (_data, args, context) => {
origin.assert(context.proof)
const ready = commitOwnerServerDelete(queryClient, args.serverId, context.routeToken)
- unreadProjection.commitScopeRetirement(context.token)
if (ready) flushOwnerServerDeleteAfterSuccess(queryClient, args.serverId)
void queryClient.invalidateQueries({ queryKey: communityKeys.channelRefDirectory(), exact: true, predicate: (query) => args.resources.includes(query) })
if (origin.registry?.authenticationView.get().active) context.onSuccess?.(communityCommandInput(args), { needsNavigation: !ready })
diff --git a/src/web/src/hooks/community/read-coordinator.test.ts b/src/web/src/hooks/community/read-coordinator.test.ts
index 787d696c9..4ef6a9e0a 100644
--- a/src/web/src/hooks/community/read-coordinator.test.ts
+++ b/src/web/src/hooks/community/read-coordinator.test.ts
@@ -61,7 +61,6 @@ import {
settleInboxReadReservationGeneration,
type InboxRowTarget,
} from "./inbox-read-reservation"
-import { getAccountUnreadProjection } from "./account-unread-projection"
const ownedClients = new Set<QueryClient>()
function createOwnedClient() {
@@ -75,19 +74,24 @@ afterEach(async () => {
ownedClients.clear()
})
+const leaseClients = new WeakMap<object, QueryClient>()
function timelineLease(queryClient: QueryClient, confirmedSeq = 0) {
- return registerReadSurface(
+ const lease = registerReadSurface(
queryClient,
"user-1",
{ kind: "timeline", channelId: "channel-1" },
confirmedSeq,
)
+ leaseClients.set(lease, queryClient)
+ return lease
}
function submitTimeline(
lease: ReturnType<typeof timelineLease>,
seq: number,
) {
+ const registry = getCommunityDbRegistry(leaseClients.get(lease)!)
+ if (registry) ingestMessages(registry, "channel-1", [{ id: `message-${seq}`, type: "chat", authorId: "peer", seq, createdAt: new Date(seq * 1000).toISOString(), content: "Message" }])
return submitReadIntent(lease, {
kind: "timeline",
channelId: "channel-1",
@@ -100,7 +104,7 @@ describe("read coordinator", () => {
beforeEach(() => {
vi.useFakeTimers()
apiFetch.mockReset()
- reconcileAccountReadState.mockReset().mockResolvedValue(undefined)
+ reconcileAccountReadState.mockReset().mockImplementation(async (client) => { const registry = getCommunityDbRegistry(client); if (registry) await reconcileAccountAttention(registry) })
reconcileAccountAttention.mockReset().mockResolvedValue(undefined)
})
@@ -197,37 +201,13 @@ describe("read coordinator", () => {
}),
)
expect(reconcileAccountReadState).toHaveBeenCalledWith(queryClient, {
- awaitSurfaceMode: "inbox-dms",
- surfaceMode: "all",
+
+
targetRevision: 9,
})
expect(submitTimeline(lease, 7)).toBe(false)
})
- it("settles a queued optimistic generation when a higher target supersedes it", () => {
- const queryClient = createOwnedClient()
- const lease = timelineLease(queryClient)
- const projection = getAccountUnreadProjection(queryClient, "user-1")
- projection.recordArrival({ channelId: "channel-1", serverId: "server-1", seq: 4 })
- const first = submitReadIntentGeneration(lease, {
- kind: "timeline",
- channelId: "channel-1",
- messageId: "message-4",
- seq: 4,
- })!
- projection.recordOptimisticRead("channel-1", 4, first)
- const second = submitReadIntentGeneration(lease, {
- kind: "timeline",
- channelId: "channel-1",
- messageId: "message-5",
- seq: 5,
- })!
- projection.recordOptimisticRead("channel-1", 5, second)
-
- projection.settleOptimisticRead(second, false)
- expect(projection.projectUnread("servers", "channel-1", false)).toBe(true)
- })
-
it("rejects hidden submissions without accepting a target", async () => {
const queryClient = createOwnedClient()
const lease = timelineLease(queryClient)
@@ -248,25 +228,6 @@ describe("read coordinator", () => {
expect(apiFetch).toHaveBeenCalledTimes(1)
})
- it("rolls back the matching optimistic projection on a terminal PUT failure", async () => {
- const queryClient = createOwnedClient()
- const lease = timelineLease(queryClient)
- const projection = getAccountUnreadProjection(queryClient, "user-1")
- projection.recordArrival({ channelId: "channel-1", serverId: "server-1", seq: 4 })
- const generation = submitReadIntentGeneration(lease, {
- kind: "timeline",
- channelId: "channel-1",
- messageId: "message-4",
- seq: 4,
- })!
- projection.recordOptimisticRead("channel-1", 4, generation)
- apiFetch.mockRejectedValue(new ApiError("forbidden", 403))
-
- expect(projection.projectUnread("servers", "channel-1", false)).toBe(false)
- await vi.advanceTimersByTimeAsync(READ_COORDINATOR_DEBOUNCE_MS)
- expect(projection.projectUnread("servers", "channel-1", false)).toBe(true)
- })
-
it("clears canonical attention while the read PUT is pending and restores it on failure", async () => {
const queryClient = createOwnedClient()
const registry = createCommunityDbRegistry(queryClient, "user-1")
@@ -850,26 +811,6 @@ describe("read coordinator", () => {
await registry.cleanup()
})
- it("rolls back the matching optimistic projection while a transient retry waits", async () => {
- const queryClient = createOwnedClient()
- const lease = timelineLease(queryClient)
- const projection = getAccountUnreadProjection(queryClient, "user-1")
- projection.recordArrival({ channelId: "channel-1", serverId: "server-1", seq: 4 })
- const generation = submitReadIntentGeneration(lease, {
- kind: "timeline",
- channelId: "channel-1",
- messageId: "message-4",
- seq: 4,
- })!
- projection.recordOptimisticRead("channel-1", 4, generation)
- apiFetch.mockRejectedValue(new ApiError("busy", 503))
-
- expect(projection.projectUnread("servers", "channel-1", false)).toBe(false)
- await vi.advanceTimersByTimeAsync(READ_COORDINATOR_DEBOUNCE_MS)
- expect(apiFetch).toHaveBeenCalledOnce()
- expect(projection.projectUnread("servers", "channel-1", false)).toBe(true)
- })
-
it("keeps canonical attention restored while a transient retry waits", async () => {
const queryClient = createOwnedClient()
const registry = createCommunityDbRegistry(queryClient, "user-1")
@@ -930,8 +871,8 @@ describe("read coordinator", () => {
await vi.runAllTimersAsync()
expect(apiFetch).toHaveBeenCalledTimes(5)
expect(reconcileAccountReadState).toHaveBeenCalledWith(queryClient, {
- awaitSurfaceMode: "inbox-dms",
- surfaceMode: "all",
+
+
targetRevision: 11,
})
})
@@ -1257,7 +1198,7 @@ describe("read coordinator", () => {
await expect(flushPendingReadIntents(queryClient)).resolves.toMatchObject({ consumed: false, cutoff: 1 })
releaseReadSurface(lease)
await vi.advanceTimersByTimeAsync(1)
- expect(db.collections.readStates.get("channel-1")).toBeUndefined()
+ expect(db.collections.readStates.get("channel-1")?.lastReadSeq).toBe(committed ? 4 : undefined)
expect(publishAccountAttentionSnapshot(queryClient, { snapshot: snapshot(4), proof: { token, signal: undefined } })).toBe("published")
if (committed) {
expect(db.collections.attentionScopes.get("channel-1")).toBeUndefined()
@@ -1283,8 +1224,8 @@ describe("read coordinator", () => {
expect(apiFetch).toHaveBeenCalledOnce()
expect(reconcileAccountReadState).toHaveBeenCalledWith(queryClient, {
- awaitSurfaceMode: "inbox-dms",
- surfaceMode: "all",
+
+
targetRevision: 14,
})
})
@@ -1315,8 +1256,8 @@ describe("read coordinator", () => {
await expect(work).resolves.toEqual({ consumed: true, cutoff: 1 })
expect(apiFetch).toHaveBeenCalledOnce()
expect(reconcileAccountReadState).toHaveBeenCalledWith(queryClient, {
- awaitSurfaceMode: "inbox-dms",
- surfaceMode: "all",
+
+
targetRevision: 15,
})
})
@@ -1369,8 +1310,8 @@ describe("read coordinator", () => {
deferred: true,
})
expect(reconcileAccountReadState).toHaveBeenCalledWith(queryClient, {
- awaitSurfaceMode: "none",
- surfaceMode: "non-inbox",
+
+
targetRevision: 18,
})
expect(apiFetch).toHaveBeenCalledTimes(1)
@@ -1399,8 +1340,8 @@ describe("read coordinator", () => {
deferred: true,
})
expect(reconcileAccountReadState).toHaveBeenCalledWith(queryClient, {
- awaitSurfaceMode: "none",
- surfaceMode: "non-inbox",
+
+
targetRevision: 20,
})
})
@@ -1644,7 +1585,7 @@ describe("read coordinator", () => {
}
await run("deferred")
apiFetch.mockReset()
- reconcileAccountReadState.mockReset().mockResolvedValue(undefined)
+ reconcileAccountReadState.mockReset().mockImplementation(async (client) => { const registry = getCommunityDbRegistry(client); if (registry) await reconcileAccountAttention(registry) })
await run("error")
})
})
diff --git a/src/web/src/hooks/community/read-coordinator.ts b/src/web/src/hooks/community/read-coordinator.ts
index 3cf02ef44..2b176b621 100644
--- a/src/web/src/hooks/community/read-coordinator.ts
+++ b/src/web/src/hooks/community/read-coordinator.ts
@@ -20,7 +20,6 @@ import {
publishInboxProjectionGenerationTerminal,
settleInboxReadReservationGeneration,
} from "./inbox-read-reservation"
-import { getAccountUnreadProjection } from "./account-unread-projection"
import { getCommunityDbRegistry, type CommunityDbRegistry } from "@/lib/community-db/collections"
import type { ReadStateRow } from "@/lib/community-db/schema"
import {
@@ -28,7 +27,7 @@ import {
captureCommunityLiveSnapshotToken,
commitAttentionScopeOptimisticSnapshot,
hasAttentionScopeOptimisticFence,
- projectConfirmedAttention,
+ publishCommunityConversationReadState,
restoreAttentionScopeOptimisticSnapshot,
type AttentionScopeOptimisticSnapshot,
} from "@/lib/community-db/sync"
@@ -51,6 +50,8 @@ type QueuedReadIntent = {
dueAt: number
ownerToken: symbol
request: ReturnType<typeof communityRequestOptions>
+ proof: ReturnType<typeof captureCommunityLiveSnapshotToken>
+ messageCreatedAt?: string
}
export type PendingReadFlushOutcome = {
@@ -82,6 +83,7 @@ type SurfaceLease = {
type ScopeState = {
surface: ReadSurface
authority: ReturnType<typeof communityRequestOptions>
+ proof: ReturnType<typeof captureCommunityLiveSnapshotToken>
localPosition: QueuedReadIntent | null
epoch: number
leases: Set<symbol>
@@ -170,9 +172,10 @@ class ReadCoordinator {
if (previous.attentionOptimistic) commitAttentionScopeOptimisticSnapshot(previous.attentionOptimistic.registry, previous.attentionOptimistic.snapshot)
}
if (current?.releaseTimer !== null && current?.releaseTimer !== undefined) clearTimeout(current.releaseTimer)
+ const proof = current?.proof ?? captureCommunityLiveSnapshotToken(this.queryClient, surface.channelId)
const state: ScopeState = current
? { ...current, confirmedSeq: Math.max(current.confirmedSeq, confirmedSeq), releaseTimer: null, leases: new Set([...current.leases, token]) }
- : { surface: { ...surface }, authority: communityRequestOptions(this.queryClient, captureCommunityLiveSnapshotToken(this.queryClient, surface.channelId)), localPosition: null,
+ : { surface: { ...surface }, proof, authority: communityRequestOptions(this.queryClient, proof), localPosition: null,
epoch: (previous?.epoch ?? -1) + 1, leases: new Set([token]), releaseTimer: null, timer: null, accepted: null, dirty: null, inFlight: null, attemptEpoch: (previous?.attemptEpoch ?? -1) + 1, confirmedSeq, attentionOptimistic: null }
this.state.setState((owner) => ({ ...owner, scopes: new Map(owner.scopes).set(key, state) }))
if ([state.accepted, state.dirty, state.inFlight?.target].some(target => target && target.intent.seq <= state.confirmedSeq)) this.cancelConfirmedWork(key)
@@ -202,7 +205,6 @@ class ReadCoordinator {
this.update(lease.key, (scope) => ({ ...scope, timer: null }))
}
for (const generation of canceled) {
- getAccountUnreadProjection(this.queryClient, this.ownerUserId).settleOptimisticRead(generation, false)
void settleInboxReadReservationGeneration(this.queryClient, generation, false, state.surface.channelId).catch(() => undefined)
}
if (!remaining.accepted && !remaining.dirty && !remaining.inFlight) this.rollbackAttentionOptimisticRead(lease.key)
@@ -225,15 +227,14 @@ class ReadCoordinator {
if (!state || state.surface.channelId !== intent.channelId || state.confirmedSeq >= intent.seq) return null
if (typeof document !== "undefined" && document.visibilityState !== "visible") return null
if (Math.max(state.accepted?.intent.seq ?? 0, state.dirty?.intent.seq ?? 0, state.inFlight?.target.intent.seq ?? 0) >= intent.seq) return null
- const superseded = [state.accepted, state.dirty].filter((pending) => pending && pending.intent.seq < intent.seq && pending.generation !== state.inFlight?.target.generation)
const generation = this.latestIntentGeneration + 1
- const queued: QueuedReadIntent = { intent: { ...intent }, generation, dueAt: Date.now() + READ_COORDINATOR_DEBOUNCE_MS, ownerToken: lease.token, request: state.authority }
+ const message = getCommunityDbRegistry(this.queryClient)?.collections.messages.get(intent.messageId)
+ const queued: QueuedReadIntent = { messageCreatedAt: message?.channelId === intent.channelId && message.seq === intent.seq ? message.createdAt : undefined, intent: { ...intent }, generation, dueAt: Date.now() + READ_COORDINATOR_DEBOUNCE_MS, ownerToken: lease.token, request: state.authority, proof: state.proof }
queued.request.assertActive()
this.state.setState((owner) => ({ ...owner, latestIntentGeneration: generation }))
this.update(lease.key, (scope) => ({ ...scope, accepted: laterIntent(scope.accepted, queued), dirty: laterIntent(scope.dirty, queued),
localPosition: lease.releasePolicy === "flush" ? laterIntent(scope.localPosition, queued) : scope.localPosition }))
this.beginAttentionOptimisticRead(lease.key)
- for (const pending of superseded) getAccountUnreadProjection(this.queryClient, this.ownerUserId).settleOptimisticRead(pending!.generation, false)
this.schedule(lease.key, READ_COORDINATOR_DEBOUNCE_MS)
return generation
}
@@ -372,7 +373,6 @@ class ReadCoordinator {
return response
} catch (error) {
assertActive()
- getAccountUnreadProjection(this.queryClient, this.ownerUserId).settleOptimisticRead(target.generation, false)
const current = this.scope(key)!
if (![current.accepted, current.dirty].some((pending) => pending && pending.generation > target.generation)) this.rollbackAttentionOptimisticRead(key)
await settleInboxReadReservationGeneration(this.queryClient, target.generation, false, target.intent.channelId)
@@ -411,7 +411,6 @@ class ReadCoordinator {
if (!this.attemptActive(key, attemptEpoch, identityEpoch)) return { committed: false, reconciled: false }
await settleInboxReadReservationGeneration(this.queryClient, target.generation, false, target.intent.channelId)
if (!this.attemptActive(key, attemptEpoch, identityEpoch)) return { committed: false, reconciled: false }
- getAccountUnreadProjection(this.queryClient, this.ownerUserId).settleOptimisticRead(target.generation, false)
const current = this.scope(key)!
if (![current.accepted, current.dirty].some((pending) => pending && pending.generation > target.generation)) this.rollbackAttentionOptimisticRead(key)
if (!retryable(error)) this.update(key, (scope) => ({ ...scope, dirty: scope.dirty && sameIntent(scope.dirty, target) ? null : scope.dirty }))
@@ -419,22 +418,20 @@ class ReadCoordinator {
return { committed: false, reconciled: false }
}
if (!this.attemptActive(key, attemptEpoch, identityEpoch)) return { committed: false, reconciled: false }
- const unreadProjection = getAccountUnreadProjection(this.queryClient, this.ownerUserId)
- unreadProjection.recordRead(target.intent.channelId, response.targetSeq)
- const registry = getCommunityDbRegistry(this.queryClient)
- if (registry) projectConfirmedAttention(registry)
+ if (target.intent.seq === response.targetSeq && target.messageCreatedAt) publishCommunityConversationReadState(this.queryClient, {
+ channelId: target.intent.channelId,
+ lastReadMessageId: target.intent.messageId,
+ lastReadAt: target.messageCreatedAt,
+ lastReadSeq: response.targetSeq,
+ }, response.revision, { token: target.proof, signal: target.request.signal ?? undefined }, "advance")
await settleInboxReadReservationGeneration(this.queryClient, target.generation, true, target.intent.channelId)
if (!this.attemptActive(key, attemptEpoch, identityEpoch)) return { committed: false, reconciled: false }
this.update(key, (scope) => ({ ...scope, confirmedSeq: Math.max(scope.confirmedSeq, response.targetSeq), dirty: sameIntent(scope.dirty ?? target, target) ? null : scope.dirty, inFlight: scope.inFlight ? { ...scope.inFlight, phase: "reconciling" } : null }))
- getAccountUnreadProjection(this.queryClient, this.ownerUserId).settleOptimisticRead(target.generation, true, response.targetSeq)
const current = this.scope(key)!, active = current.inFlight!
const defer = active.deferInboxDms?.() === true || active.drainCutoff !== undefined && current.accepted !== null && current.accepted.generation > active.drainCutoff
try {
target.request.assertActive()
- await Promise.all([
- reconcileAccountReadState(this.queryClient, { surfaceMode: defer ? "non-inbox" : "all", awaitSurfaceMode: defer ? "none" : "inbox-dms", targetRevision: response.revision }),
- registry ? reconcileAccountAttention(registry).catch(() => undefined) : Promise.resolve(),
- ])
+ await reconcileAccountReadState(this.queryClient, { targetRevision: response.revision })
if (!this.attemptActive(key, attemptEpoch, identityEpoch)) return { committed: true, reconciled: false }
target.request.assertActive()
publishInboxProjectionGenerationTerminal(this.queryClient, target.generation, defer ? "deferred" : "success")
@@ -471,7 +468,7 @@ class ReadCoordinator {
if (canceled) scope.inFlight!.controller.abort()
const latest = this.scope(key)!
if (accepted && !latest.inFlight) this.schedule(key, Math.max(0, accepted.dueAt - Date.now()))
- if (!accepted && !dirty && !latest.inFlight) {
+ if (!accepted && !dirty && !latest.inFlight && scope.attentionOptimistic) {
this.commitAttentionOptimisticRead(key)
const registry = getCommunityDbRegistry(this.queryClient)
if (registry) void reconcileAccountAttention(registry).catch(() => undefined)
diff --git a/src/web/src/hooks/community/use-account-attention.dom.test.ts b/src/web/src/hooks/community/use-account-attention.dom.test.ts
index 36533986b..41203a46a 100644
--- a/src/web/src/hooks/community/use-account-attention.dom.test.ts
+++ b/src/web/src/hooks/community/use-account-attention.dom.test.ts
@@ -2,10 +2,12 @@ import { createElement, type PropsWithChildren } from "react"
import { QueryClientProvider } from "@tanstack/react-query"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { COMMUNITY_CONTRACT_HEADER, type AccountAttentionSnapshot } from "@alook/shared"
-import { renderHook, waitFor } from "@/test/react-dom-harness"
+import { act, renderHook, waitFor } from "@/test/react-dom-harness"
import { CommunityDbProvider } from "@/lib/community-db/projections"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
-import { scheduleAccountAttentionReconcile, useAccountAttention } from "./use-account-attention"
+import { accountAttentionMatchesReadState, scheduleAccountAttentionReconcile, useAccountAttention, useAccountAttentionProjection } from "./use-account-attention"
+import { reconcileAccountReadState } from "./community-ws/read-state-reconciliation"
+import { communityKeys } from "@/lib/query-keys"
const apiFetchMock = vi.fn()
vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => apiFetchMock(...args) }))
@@ -38,12 +40,147 @@ async function mountOwner(value: AccountAttentionSnapshot) {
const hook = renderHook(() => useAccountAttention(), { wrapper: Wrapper })
await waitFor(() => {
if (hook.result.current.error) throw hook.result.current.error
- expect(hook.result.current.data).toEqual({ loaded: true })
+ expect(hook.result.current.data).toEqual({ loaded: true, readRevision: -1 })
})
return { ...owner, hook }
}
describe("closed-Inbox account attention message hydration", () => {
+ it("lets the native shell retry a stale D1 response even when transport retries are disabled", async () => {
+ const owner = await createCommunityQueryOwner()
+ apiFetchMock.mockResolvedValueOnce({ ...snapshot(), stale: true }).mockResolvedValue(snapshot())
+ function Wrapper({ children }: PropsWithChildren) {
+ return createElement(QueryClientProvider, { client: owner.client }, createElement(CommunityDbProvider, { registry: owner.registry }, children))
+ }
+ vi.useFakeTimers()
+ const hook = renderHook(useAccountAttention, { wrapper: Wrapper })
+ try {
+ await act(async () => { await vi.advanceTimersByTimeAsync(0) })
+ expect(apiFetchMock).toHaveBeenCalledOnce()
+ expect(owner.registry.collections.attentionScopes.size).toBe(0)
+ await act(async () => { await vi.advanceTimersByTimeAsync(1_000) })
+ expect(apiFetchMock).toHaveBeenCalledTimes(2)
+ expect(owner.client.getQueryData(communityKeys.accountAttention())).toEqual({ loaded: true, readRevision: -1 })
+ expect(owner.registry.collections.attentionScopes.get("channel")?.lastUnreadSeq).toBe(4)
+ } finally {
+ hook.unmount()
+ await owner.client.cancelQueries()
+ vi.useRealTimers()
+ await owner.registry.cleanup()
+ owner.client.clear()
+ }
+ })
+
+ it("retains the configured transport retry policy and recovers through the same native owner", async () => {
+ const owner = await createCommunityQueryOwner()
+ apiFetchMock.mockRejectedValueOnce(new Error("offline")).mockResolvedValue(snapshot())
+ function Wrapper({ children }: PropsWithChildren) {
+ return createElement(QueryClientProvider, { client: owner.client }, createElement(CommunityDbProvider, { registry: owner.registry }, children))
+ }
+ const hook = renderHook(useAccountAttention, { wrapper: Wrapper })
+ try {
+ await waitFor(() => expect(hook.result.current.error?.message).toBe("offline"))
+ expect(apiFetchMock).toHaveBeenCalledOnce()
+ await act(async () => { await hook.result.current.refetch() })
+ expect(owner.client.getQueryData(communityKeys.accountAttention())).toEqual({ loaded: true, readRevision: -1 })
+ expect(apiFetchMock).toHaveBeenCalledTimes(2)
+ } finally {
+ hook.unmount()
+ await owner.client.cancelQueries()
+ await owner.registry.cleanup()
+ owner.client.clear()
+ }
+ })
+
+ it("finishes the newer exact read while the cancelled old HTTP remains physically held", async () => {
+ const owner = await createCommunityQueryOwner()
+ let releaseAttention: ((value: AccountAttentionSnapshot) => void) | undefined
+ let oldReleased = false
+ const signals: AbortSignal[] = []
+ let revision = 0
+ apiFetchMock.mockImplementation(async (path: string, options: { signal: AbortSignal }) => {
+ if (path.endsWith("/read-state")) return { revision, readStates: [] }
+ signals.push(options.signal)
+ if (signals.length === 1) return new Promise<AccountAttentionSnapshot>(resolve => {
+ releaseAttention = value => { oldReleased = true; resolve(value) }
+ })
+ const value = snapshot(3)
+ value.scopes[0].unreadCount = 3
+ return value
+ })
+ await reconcileAccountReadState(owner.client, { reconcileAttention: false })
+ function Wrapper({ children }: PropsWithChildren) {
+ return createElement(QueryClientProvider, { client: owner.client }, createElement(CommunityDbProvider, { registry: owner.registry }, children))
+ }
+ const hook = renderHook(() => ({ shell: useAccountAttention(), consumer: useAccountAttentionProjection() }), { wrapper: Wrapper })
+ let settled: Promise<unknown> | undefined
+ try {
+ await waitFor(() => expect(releaseAttention).toBeTypeOf("function"))
+ const original = owner.client.getQueryCache().find({ queryKey: communityKeys.accountAttention(), exact: true })
+ hook.rerender()
+ revision = 1
+ settled = Promise.all([reconcileAccountReadState(owner.client), reconcileAccountReadState(owner.client)]).then(() => null, error => error)
+ await waitFor(() => expect(owner.registry.collections.attentionScopes.get("channel")?.unreadCount).toBe(3))
+ expect(await settled).toBeNull()
+ expect(oldReleased).toBe(false)
+ expect(signals).toHaveLength(2)
+ expect(signals[0].aborted).toBe(true)
+ expect(owner.client.getQueryCache().find({ queryKey: communityKeys.accountAttention(), exact: true })).toBe(original)
+ await act(async () => { releaseAttention!(snapshot(5)); await Promise.resolve() })
+ expect(owner.client.getQueryData(communityKeys.accountAttention())).toEqual({ loaded: true, readRevision: 1 })
+ expect(owner.registry.collections.attentionScopes.get("channel")).toMatchObject({ lastUnreadSeq: 3, unreadCount: 3 })
+ expect(accountAttentionMatchesReadState(owner.registry)).toBe(true)
+ } finally {
+ releaseAttention?.(snapshot())
+ hook.unmount()
+ await owner.client.cancelQueries()
+ await settled
+ await owner.registry.cleanup()
+ owner.client.clear()
+ }
+ })
+
+ it("keeps the original shell read qualified across read-only consumer renders and auth settlement", async () => {
+ const owner = await createCommunityQueryOwner()
+ let releaseRead: (() => void) | undefined
+ apiFetchMock.mockImplementation(async (path: string) => {
+ if (path.endsWith("/read-state")) return { revision: 0, readStates: [] }
+ return snapshot()
+ })
+ await reconcileAccountReadState(owner.client, { reconcileAttention: false })
+ function Wrapper({ children }: PropsWithChildren) {
+ return createElement(QueryClientProvider, { client: owner.client }, createElement(CommunityDbProvider, { registry: owner.registry }, children))
+ }
+ const hook = renderHook(() => ({ shell: useAccountAttention(), consumer: useAccountAttentionProjection() }), { wrapper: Wrapper })
+ try {
+ await waitFor(() => expect(hook.result.current.shell.isSuccess).toBe(true))
+ const original = owner.client.getQueryCache().find({ queryKey: communityKeys.accountAttention(), exact: true })
+ apiFetchMock.mockClear()
+ apiFetchMock.mockImplementation(async (path: string) => {
+ if (path.endsWith("/read-state")) {
+ await new Promise<void>(resolve => { releaseRead = resolve })
+ return { revision: 0, readStates: [] }
+ }
+ return snapshot()
+ })
+ const settled = reconcileAccountReadState(owner.client).then(() => null, error => error)
+ await waitFor(() => expect(releaseRead).toBeTypeOf("function"))
+ await waitFor(() => expect(hook.result.current.consumer.isFetching).toBe(false))
+ hook.rerender()
+ await act(async () => { releaseRead!(); expect(await settled).toBeNull() })
+ expect(owner.client.getQueryCache().find({ queryKey: communityKeys.accountAttention(), exact: true })).toBe(original)
+ expect(accountAttentionMatchesReadState(owner.registry)).toBe(true)
+ expect(apiFetchMock.mock.calls.map(([path]) => path)).toEqual(["/api/community/users/me/read-state", "/api/community/users/me/attention"])
+ expect(owner.registry.collections.attentionScopes.get("channel")?.ordinaryUnread).toBe(true)
+ } finally {
+ releaseRead?.()
+ hook.unmount()
+ await owner.client.cancelQueries()
+ await owner.registry.cleanup()
+ owner.client.clear()
+ }
+ })
+
it("hydrates an ID-bearing mention without any Inbox component or message window", async () => {
const owner = await mountOwner(snapshot())
const attentionCall = apiFetchMock.mock.calls.find(([path]) => path.endsWith("/attention"))!
diff --git a/src/web/src/hooks/community/use-account-attention.ts b/src/web/src/hooks/community/use-account-attention.ts
index f5afa4c51..84645cc9f 100644
--- a/src/web/src/hooks/community/use-account-attention.ts
+++ b/src/web/src/hooks/community/use-account-attention.ts
@@ -8,6 +8,8 @@ import {
COMMUNITY_RESOURCE_CONTRACT_VERSION,
type AccountAttentionSnapshot,
} from "@alook/shared"
+import { isAbortError } from "@/lib/errors"
+import { conversationReadRetryPolicy } from "@/lib/community/conversation-read"
import { apiFetch, type ApiRequestOptions } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import {
@@ -15,6 +17,7 @@ import {
useAttentionScopes,
} from "@/lib/community-db/projections"
import {
+ beginCommunityCommandRevision,
captureCommunityLiveSnapshotToken,
assertCommunityLiveSnapshotTokenCurrent,
publishAccountAttentionSnapshot,
@@ -43,26 +46,55 @@ async function fetchAccountAttention(options: ApiRequestOptions): Promise<Accoun
return AccountAttentionSnapshotSchema.parse(response)
}
-const accountAttentionQueryFn = (queryClient: QueryClient) =>
- async ({ signal }: { signal?: AbortSignal } = {}) => {
- const token = captureCommunityLiveSnapshotToken(queryClient)
- const snapshot = await fetchAccountAttention(communityRequestOptions(queryClient, token, signal))
- publishAccountAttentionSnapshot(queryClient, {
- snapshot,
- proof: { token, signal },
- })
- return { loaded: true }
+function currentReadRevision(registry: CommunityDbRegistry | null) {
+ let revision = registry?.collections.readStateClock.get("account")?.revision ?? -1
+ for (const row of registry?.collections.readStates.values() ?? []) revision = Math.max(revision, row.observedRevision ?? -1)
+ return revision
+}
+
+export function accountAttentionMatchesReadState(registry: CommunityDbRegistry) {
+ const query = registry.queryClient.getQueryCache().find<{ loaded: boolean; readRevision: number }>({ queryKey: communityKeys.accountAttention(), exact: true })
+ return query?.state.status === "success" && query.state.fetchStatus === "idle"
+ && query.state.data?.readRevision === currentReadRevision(registry)
+}
+
+const accountAttentionQueryFn = (queryClient: QueryClient) => {
+ const token = getCommunityDbRegistry(queryClient) ? captureCommunityLiveSnapshotToken(queryClient) : null
+ return async ({ signal, meta }: { signal?: AbortSignal; meta?: Record<string, unknown> } = {}) => {
+ if (!token) throw new DOMException("Attention owner retired", "AbortError")
+ assertCommunityLiveSnapshotTokenCurrent(queryClient, token, signal)
+ const requestToken = beginCommunityCommandRevision(queryClient, token)
+ const readRevision = currentReadRevision(token.registry)
+ const query = queryClient.getQueryCache().find({ queryKey: communityKeys.accountAttention(), exact: true })
+ if (meta) meta.attentionReadRevision = readRevision
+ const snapshot = await fetchAccountAttention(communityRequestOptions(queryClient, requestToken, signal))
+ assertCommunityLiveSnapshotTokenCurrent(queryClient, token, signal)
+ if (!query || queryClient.getQueryCache().get(query.queryHash) !== query) throw new DOMException("Attention query retired", "AbortError")
+ if (currentReadRevision(token.registry) !== readRevision) throw new StaleAttentionReadError()
+ publishAccountAttentionSnapshot(queryClient, { snapshot, proof: { token: requestToken, signal } })
+ return { loaded: true, readRevision }
}
+}
+
+function accountAttentionOptions(queryClient: QueryClient) {
+ const meta = queryClient.getQueryCache().find({ queryKey: communityKeys.accountAttention(), exact: true })?.meta ?? {}
+ return {
+ queryKey: communityKeys.accountAttention(),
+ queryFn: accountAttentionQueryFn(queryClient),
+ meta,
+ retry: attentionReadRetryPolicy(queryClient),
+ staleTime: 0,
+ }
+}
export function useAccountAttention() {
const queryClient = useQueryClient()
const scopes = useAttentionScopes()
const items = useAttentionItems()
const query = useQuery({
- queryKey: communityKeys.accountAttention(),
- queryFn: accountAttentionQueryFn(queryClient),
- staleTime: 0,
+ ...accountAttentionOptions(queryClient),
refetchOnMount: "always",
+ refetchInterval: query => query.state.status === "error" && !isAbortError(query.state.error) ? 5_000 : false,
})
return { ...query, scopes, items }
}
@@ -76,8 +108,7 @@ export function useAccountAttentionProjection() {
const scopes = useAttentionScopes()
const items = useAttentionItems()
const query = useQuery({
- queryKey: communityKeys.accountAttention(),
- queryFn: accountAttentionQueryFn(queryClient),
+ ...accountAttentionOptions(queryClient),
enabled: false,
})
return { ...query, scopes, items }
@@ -86,15 +117,27 @@ export function useAccountAttentionProjection() {
export async function reconcileAccountAttention(
registry: CommunityDbRegistry,
) {
+ const client = registry.queryClient, token = captureCommunityLiveSnapshotToken(client)
+ const query = client.getQueryCache().find({ queryKey: communityKeys.accountAttention(), exact: true })
+ if (query?.state.fetchStatus === "fetching" && query.meta?.attentionReadRevision !== currentReadRevision(registry)) {
+ await client.cancelQueries({ queryKey: communityKeys.accountAttention(), exact: true })
+ assertCommunityLiveSnapshotTokenCurrent(client, token, undefined)
+ const completed = client.getQueryState<{ loaded: boolean; readRevision: number }>(communityKeys.accountAttention())
+ if (completed && !completed.isInvalidated && accountAttentionMatchesReadState(registry)) return completed.data!
+ }
const snapshot = await registry.queryClient.query({
- queryKey: communityKeys.accountAttention(),
- queryFn: accountAttentionQueryFn(registry.queryClient),
- staleTime: 0,
+ ...accountAttentionOptions(registry.queryClient),
+ retry: (failures, error) => error instanceof StaleAttentionReadError && failures < 3,
select: undefined,
})
return snapshot
}
+function attentionReadRetryPolicy(queryClient: QueryClient) {
+ const retry = conversationReadRetryPolicy(queryClient.defaultQueryOptions({ queryKey: communityKeys.accountAttention() }).retry)
+ return (failures: number, error: Error) => error instanceof StaleAttentionReadError ? failures < 3 : retry(failures, error)
+}
+
export function scheduleAccountAttentionReconcile(queryClient: QueryClient, message?: { channelId?: string; messageId?: string }) {
const registry = getCommunityDbRegistry(queryClient)
if (!registry?.runtime.lifecycle.get().active) return
diff --git a/src/web/src/hooks/community/use-channel-message-feed.dom.test.ts b/src/web/src/hooks/community/use-channel-message-feed.dom.test.ts
index 0b3afc1ca..04bd1ab23 100644
--- a/src/web/src/hooks/community/use-channel-message-feed.dom.test.ts
+++ b/src/web/src/hooks/community/use-channel-message-feed.dom.test.ts
@@ -1,6 +1,8 @@
import React from "react"
import { beforeEach, describe, expect, it, vi } from "vitest"
import { renderHook } from "@/test/react-dom-harness"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { CommunityTestProvider } from "@/test/community-owner-fixture"
import { useChannelMessageFeed } from "./use-channel-message-feed"
import { ConversationActivityContext } from "@/contexts/community/conversation-activity"
@@ -17,7 +19,10 @@ vi.mock("./use-messages", () => ({ useMessages: (...args: unknown[]) => { mocks.
vi.mock("./use-channel-watermark", () => ({ useChannelWatermark: (...args: unknown[]) => mocks.watermark(...args) }))
vi.mock("./use-channel-panels", () => ({ useThreads: () => ({ threads: [], isLoading: true }), usePins: () => ({ pins: [], isLoading: true }) }))
const target = { channelId: "c1", serverId: "s1", viewerUserId: "viewer", isChildChannel: false, anchorMessageId: null }
-beforeEach(() => {
+let owner: Awaited<ReturnType<typeof createCommunityQueryOwner>>
+function Owner({ children }: { children: React.ReactNode }) { return React.createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry }, children) }
+beforeEach(async () => {
+ owner = await createCommunityQueryOwner("viewer")
mocks.useMessages.mockClear(); mocks.watermark.mockClear(); mocks.messages.retryInitialLoad.mockClear()
Object.assign(mocks.messages, { readSnapshot: { channelId: "c1", lastReadMessageId: "read", lastReadSeq: 1, lastReadAt: null }, readSnapshotFetching: false,
entryDenied: false, initialLoadError: null, isPending: false, isError: false, anchorReconciled: true, initialPositionKnown: true })
@@ -26,7 +31,7 @@ beforeEach(() => {
describe("message feed consumes the entry snapshot", () => {
it("keeps the canonical feed visible while retiring the background watermark scope", () => {
function Wrapper({ children }: { children: React.ReactNode }) {
- return React.createElement(ConversationActivityContext, { value: false }, children)
+ return React.createElement(Owner, null, React.createElement(ConversationActivityContext, { value: false }, children))
}
const hook = renderHook(() => useChannelMessageFeed(target), { wrapper: Wrapper })
expect(hook.result.current.messages).toBe(mocks.messages.messages)
@@ -34,7 +39,7 @@ describe("message feed consumes the entry snapshot", () => {
expect(mocks.watermark).toHaveBeenLastCalledWith(expect.objectContaining({ channelId: null }))
})
it("projects NEW and unread count independently of secondary pins and threads", () => {
- const hook = renderHook(() => useChannelMessageFeed(target))
+ const hook = renderHook(() => useChannelMessageFeed(target), { wrapper: Owner })
expect(hook.result.current.newDividerBefore).toBe("peer")
expect(hook.result.current.unreadCount).toBe(1)
expect(hook.result.current.anchorInCache).toBe(true)
@@ -45,7 +50,7 @@ describe("message feed consumes the entry snapshot", () => {
it("keeps an unresolved entry pointer pending without a second leaf-read gate", () => {
mocks.messages.readSnapshot = null; mocks.messages.readSnapshotFetching = true; mocks.messages.initialPositionKnown = false
- const hook = renderHook(() => useChannelMessageFeed({ ...target, anchorMessageId: "deep" }))
+ const hook = renderHook(() => useChannelMessageFeed({ ...target, anchorMessageId: "deep" }), { wrapper: Owner })
expect(hook.result.current.newDividerBefore).toBeUndefined()
expect(mocks.watermark).toHaveBeenLastCalledWith(expect.objectContaining({ snapshotStatus: "pending" }))
expect(mocks.useMessages).toHaveBeenLastCalledWith("c1", { serverId: "s1", viewerUserId: "viewer", anchorMessageId: "deep" })
@@ -55,7 +60,7 @@ describe("message feed consumes the entry snapshot", () => {
it("stops watermark writes on denial and exposes the unified retry", () => {
const error = Object.assign(new Error("denied"), { status: 403 })
Object.assign(mocks.messages, { entryDenied: true, initialLoadError: error, isError: true })
- const hook = renderHook(() => useChannelMessageFeed(target))
+ const hook = renderHook(() => useChannelMessageFeed(target), { wrapper: Owner })
expect(mocks.watermark).toHaveBeenLastCalledWith(expect.objectContaining({ snapshotStatus: "error", feedStatus: "error" }))
hook.result.current.retryInitialLoad()
expect(mocks.messages.retryInitialLoad).toHaveBeenCalledOnce()
diff --git a/src/web/src/hooks/community/use-channel-message-feed.ts b/src/web/src/hooks/community/use-channel-message-feed.ts
index 8d7d50212..aee97a1c9 100644
--- a/src/web/src/hooks/community/use-channel-message-feed.ts
+++ b/src/web/src/hooks/community/use-channel-message-feed.ts
@@ -4,6 +4,7 @@ import { useConversationActivity } from "@/contexts/community/conversation-activ
import { useAtom, useCreateAtom } from "@tanstack/react-store";
import { useMemo } from "react"
import { isConversationAccessError } from "@/lib/community/conversation-read"
+import { useMessageUnreadCount } from "./use-message-unread-count"
import { useChannelWatermark } from "./use-channel-watermark"
import { useMessages } from "./use-messages"
import { usePins, useThreads } from "./use-channel-panels"
@@ -60,10 +61,11 @@ export function useChannelMessageFeed({
confirmedSeq: readSnapshot?.lastReadSeq ?? 0,
catchUp: () => messagesQuery.refetch(),
})
- const unreadCount = useMemo(() => {
- const difference = messagesQuery.latestSeq - (readSnapshot?.lastReadSeq ?? 0)
- return Math.max(0, difference)
- }, [messagesQuery.latestSeq, readSnapshot])
+ const unreadCount = useMessageUnreadCount({ channelId, viewerUserId, messages: messagesQuery.messages,
+ entryReadSeq: readSnapshot?.lastReadSeq, latestSeq: messagesQuery.latestSeq,
+ historyStartKnown: messagesQuery.historyStartKnown, hasMoreNewer: messagesQuery.hasMoreNewer,
+ ready: !!readSnapshot && !messagesQuery.readSnapshotFetching && !messagesQuery.isPending && !messagesQuery.isError,
+ })
const threadsQuery = useThreads(channelId)
const pinsQuery = usePins(channelId)
return {
diff --git a/src/web/src/hooks/community/use-community-ws-foreground.dom.test.ts b/src/web/src/hooks/community/use-community-ws-foreground.dom.test.ts
index 748d63e5b..655abbec5 100644
--- a/src/web/src/hooks/community/use-community-ws-foreground.dom.test.ts
+++ b/src/web/src/hooks/community/use-community-ws-foreground.dom.test.ts
@@ -166,8 +166,10 @@ describe("community foreground message reconciliation", () => {
await mountHook()
flushEffects()
const old = capturedUseUserWsOptions!.onForeground!
+ const authenticate = capturedUseUserWsOptions!.onAuthenticated!
+ const reconnect = capturedOnReconnect!
unmountHook()
- await old()
+ await Promise.all([old(), authenticate(), reconnect({ reconnectDurationMs: 1_000 })])
expect(getCommunityApiFetchMock()).not.toHaveBeenCalled()
})
})
diff --git a/src/web/src/hooks/community/use-community-ws-read-state-lifecycle.dom.test.ts b/src/web/src/hooks/community/use-community-ws-read-state-lifecycle.dom.test.ts
index 6cf22a60c..c66d883ea 100644
--- a/src/web/src/hooks/community/use-community-ws-read-state-lifecycle.dom.test.ts
+++ b/src/web/src/hooks/community/use-community-ws-read-state-lifecycle.dom.test.ts
@@ -1,7 +1,9 @@
import { getCapturedRuntime } from "./community-ws/test-harness"
+import { act } from "@/test/react-dom-harness"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { communityKeys } from "@/lib/query-keys"
import {
+ canonicalRegistry,
capturedOnMessage,
capturedQueryClient,
capturedUseUserWsOptions,
@@ -12,149 +14,104 @@ import {
resetCommunityWsHarness,
unmountHook,
} from "./community-ws/test-harness"
-import { useCommunityStore } from "@/stores/community"
-import { useCommunityWsStore } from "@/stores/community/ws"
-import {
- registerReadSurface,
- releaseReadSurface,
- submitReadIntent,
-} from "./read-coordinator"
+import { seedCommunityAttentionScope } from "@/test/community-query-owner"
+import { registerReadSurface, releaseReadSurface, submitReadIntent } from "./read-coordinator"
+const emptyAttention = { scopes: [], items: [], limit: 50, truncated: false, included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } }
+const attentionCalls = () => getCommunityApiFetchMock().mock.calls.filter(([path]) => path === "/api/community/users/me/attention")
beforeEach(async () => {
vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible")
await resetCommunityWsHarness()
})
-
-afterEach(async () => {
- await cleanupCommunityWsHarness()
- vi.unstubAllGlobals()
-})
+afterEach(async () => { await cleanupCommunityWsHarness(); vi.unstubAllGlobals() })
describe("community read-state lifecycle reconciliation", () => {
- it("fences owner fallback after cleanup during an active read barrier", async () => {
+ it("settles admitted reading through its account owner after the WS hook unmounts without old structural fallback", async () => {
vi.useFakeTimers()
getCapturedRuntime().ui.actions.subscribe({ channelId: "ch-1" })
await mountHook({ viewerUserId: "viewer-1" })
flushEffects()
+ seedCommunityAttentionScope(capturedQueryClient, { channelId: "ch-1", serverId: "s1", seq: 1 })
let releaseRead!: () => void
- const readGate = new Promise<void>((resolve) => {
- releaseRead = resolve
- })
+ const readGate = new Promise<void>(resolve => { releaseRead = resolve })
getCommunityApiFetchMock().mockImplementation(async (url: unknown) => {
- if (typeof url === "string" && url.endsWith("/read")) {
- await readGate
- return { changed: true, revision: 1, targetSeq: 1 }
- }
+ if (typeof url === "string" && url.endsWith("/read")) { await readGate; return { changed: true, revision: 1, targetSeq: 1 } }
if (url === "/api/community/users/me/read-state") {
- return {
- revision: 1,
- readStates: [{
- channelId: "ch-1",
- lastReadMessageId: "message-1",
- lastReadAt: "2026-08-27T00:00:00.000Z",
- lastReadSeq: 1,
- }],
- }
+ expect(canonicalRegistry!.collections.readStates.get("ch-1")).toMatchObject({ lastReadMessageId: "message-1", lastReadSeq: 1, observedRevision: 1 })
+ return { revision: 1, readStates: [{ channelId: "ch-1", lastReadMessageId: "message-1", lastReadAt: "2026-08-27T00:00:00.000Z", lastReadSeq: 1 }] }
}
+ if (url === "/api/community/users/me/attention") return emptyAttention
throw new Error(`unexpected API fetch: ${String(url)}`)
})
const invalidate = vi.spyOn(capturedQueryClient, "invalidateQueries")
- const lease = registerReadSurface(
- capturedQueryClient,
- "viewer-1",
- { kind: "timeline", channelId: "ch-1" },
- )
-
- capturedOnMessage!({
- type: "community:message.create",
- channelId: "ch-1",
- message: {
- id: "message-1",
- seq: 1,
- authorId: "author-1",
- authorName: "Alice",
- content: "hello",
- type: "chat",
- createdAt: "2026-08-27T00:00:00.000Z",
- },
- })
- expect(submitReadIntent(lease, {
- kind: "timeline",
- channelId: "ch-1",
- messageId: "message-1",
- seq: 1,
- })).toBe(true)
- await vi.advanceTimersByTimeAsync(500)
- await vi.waitFor(() => expect(getCommunityApiFetchMock()).toHaveBeenCalledWith(
- "/api/community/channels/ch-1/read",
- expect.anything(),
- ))
-
- unmountHook()
- releaseRead()
- await vi.waitFor(() => {
- expect(invalidate.mock.calls.filter(([filters]) => (
- JSON.stringify(filters.queryKey) === JSON.stringify(communityKeys.inbox())
- ))).toHaveLength(1)
- })
- await vi.runAllTimersAsync()
- expect(invalidate.mock.calls.filter(([filters]) => (
- JSON.stringify(filters.queryKey) === JSON.stringify(communityKeys.dms())
- ))).toHaveLength(1)
- releaseReadSurface(lease)
+ const lease = registerReadSurface(capturedQueryClient, "viewer-1", { kind: "timeline", channelId: "ch-1" })
+ try {
+ await act(async () => { await capturedOnMessage!({ type: "community:message.create", channelId: "ch-1", message: { id: "message-1", seq: 1, authorId: "author-1", authorName: "Alice", authorAvatarVersion: 0, content: "hello", type: "chat", createdAt: "2026-08-27T00:00:00.000Z" } }) })
+ expect(canonicalRegistry!.collections.messages.get("message-1")?.createdAt).toBe("2026-08-27T00:00:00.000Z")
+ await act(async () => {
+ expect(submitReadIntent(lease, { kind: "timeline", channelId: "ch-1", messageId: "message-1", seq: 1 })).toBe(true)
+ await vi.advanceTimersByTimeAsync(500)
+ })
+ expect(getCommunityApiFetchMock()).toHaveBeenCalledWith("/api/community/channels/ch-1/read", expect.anything())
+ unmountHook()
+ await act(async () => { releaseRead(); await vi.advanceTimersByTimeAsync(0) })
+ await vi.waitFor(() => expect(canonicalRegistry!.collections.readStates.get("ch-1")?.lastReadSeq).toBe(1))
+ await vi.waitFor(() => expect(attentionCalls()).toHaveLength(1))
+ expect(canonicalRegistry!.collections.attentionScopes.get("ch-1")).toBeUndefined()
+ expect(capturedQueryClient.getQueryData(communityKeys.accountReadStateSnapshot())).toEqual({ revision: 1 })
+ expect(invalidate.mock.calls.some(([filters]) => [communityKeys.inbox(), communityKeys.dms()].some(key => JSON.stringify(filters.queryKey) === JSON.stringify(key)))).toBe(false)
+ } finally { releaseRead(); releaseReadSurface(lease); await vi.runAllTimersAsync() }
})
it("schedules the first-auth attention owner before read-state reconciliation completes", async () => {
vi.useFakeTimers()
await mountHook({ viewerUserId: "viewer-1" })
- getCapturedRuntime().ws.actions.setPresence("viewer-1", "offline")
+ act(() => getCapturedRuntime().ws.actions.setPresence("viewer-1", "offline"))
let releaseSnapshot!: (value: unknown) => void
- getCommunityApiFetchMock().mockReturnValueOnce(new Promise((resolve) => {
- releaseSnapshot = resolve
- }))
- const authentication = capturedUseUserWsOptions?.onAuthenticated?.()
-
- expect(getCommunityApiFetchMock()).toHaveBeenCalledOnce()
- expect(getCapturedRuntime().ws.get().presenceByUserId.get("viewer-1"))
- .toBe("online")
- await vi.waitFor(() => expect(getCommunityApiFetchMock().mock.calls.filter(([path]) => (
- path === "/api/community/users/me/attention"
- ))).toHaveLength(1))
-
- releaseSnapshot({ revision: 0, readStates: [] })
- await authentication
- expect(capturedQueryClient.getQueryData(
- communityKeys.accountReadStateSnapshot(),
- )).toEqual({ revision: 0, readStates: [] })
+ getCommunityApiFetchMock().mockImplementationOnce(() => new Promise(resolve => { releaseSnapshot = resolve }))
+ let outcome!: Promise<unknown>
+ act(() => { outcome = Promise.resolve(capturedUseUserWsOptions!.onAuthenticated!()).then(() => null, error => error) })
+ try {
+ expect(getCommunityApiFetchMock().mock.calls.filter(([path]) => path === "/api/community/users/me/read-state")).toHaveLength(1)
+ expect(getCapturedRuntime().ws.get().presenceByUserId.get("viewer-1")).toBe("online")
+ await vi.waitFor(() => expect(attentionCalls()).toHaveLength(1))
+ expect(capturedQueryClient.getQueryState(communityKeys.accountReadStateSnapshot())?.fetchStatus).toBe("fetching")
+ } finally {
+ releaseSnapshot({ revision: 0, readStates: [] })
+ await act(async () => { await vi.advanceTimersByTimeAsync(0) })
+ expect(await outcome).toBeNull()
+ }
+ expect(capturedQueryClient.getQueryData(communityKeys.accountReadStateSnapshot())).toEqual({ revision: 0 })
+ expect(canonicalRegistry!.collections.readStateClock.get("account")?.revision).toBe(0)
+ expect(canonicalRegistry!.collections.readStates.size).toBe(0)
})
- it.each(["visibilitychange", "pageshow"] as const)(
- "schedules the connected owner and reconciles non-Inbox state on %s",
- async (eventType) => {
- vi.useFakeTimers()
- await mountHook()
- flushEffects()
+ it.each(["visibilitychange", "pageshow"] as const)("schedules the connected canonical owner on %s", async eventType => {
+ vi.useFakeTimers()
+ await mountHook()
+ flushEffects()
+ await act(async () => {
if (eventType === "visibilitychange") document.dispatchEvent(new Event(eventType))
else window.dispatchEvent(new PageTransitionEvent(eventType, { persisted: false }))
- await vi.waitFor(() => expect(capturedQueryClient.getQueryData(
- communityKeys.accountReadStateSnapshot(),
- )).toEqual({ revision: 0, readStates: [] }))
- await vi.waitFor(() => expect(getCommunityApiFetchMock().mock.calls.filter(([path]) => (
- path === "/api/community/users/me/attention"
- ))).toHaveLength(1))
- },
- )
+ await vi.advanceTimersByTimeAsync(1_000)
+ })
+ await vi.waitFor(() => expect(capturedQueryClient.getQueryData(communityKeys.accountReadStateSnapshot())).toEqual({ revision: 0 }))
+ await vi.waitFor(() => expect(capturedQueryClient.getQueryState(communityKeys.accountAttention())?.status).toBe("success"))
+ expect(attentionCalls().length).toBeGreaterThan(0)
+ expect(getCommunityApiFetchMock().mock.calls.filter(([path]) => path === "/api/community/users/me/read-state")).toHaveLength(1)
+ expect(canonicalRegistry!.collections.readStateClock.get("account")?.revision).toBe(0)
+ })
- it("contains a visible lifecycle reconciliation failure while attention still reconciles", async () => {
+ it("contains a visible read-state failure while healthy attention still converges", async () => {
vi.useFakeTimers()
await mountHook()
flushEffects()
+ seedCommunityAttentionScope(capturedQueryClient, { channelId: "c1", seq: 4 })
getCommunityApiFetchMock().mockRejectedValueOnce(new Error("snapshot unavailable"))
-
- document.dispatchEvent(new Event("visibilitychange"))
- await vi.waitFor(() => expect(getCommunityApiFetchMock()).toHaveBeenCalledOnce())
- await vi.waitFor(() => expect(getCommunityApiFetchMock().mock.calls.some(([path]) => (
- path === "/api/community/users/me/attention"
- ))).toBe(true))
+ await act(async () => { document.dispatchEvent(new Event("visibilitychange")); await vi.advanceTimersByTimeAsync(0) })
+ await vi.waitFor(() => expect(capturedQueryClient.getQueryState(communityKeys.accountReadStateSnapshot())?.error).toMatchObject({ message: "snapshot unavailable" }))
+ await vi.waitFor(() => expect(attentionCalls()).toHaveLength(1))
+ expect(canonicalRegistry!.collections.attentionScopes.size).toBe(0)
+ expect(capturedQueryClient.getQueryState(communityKeys.accountAttention())?.status).toBe("success")
})
})
diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.ts
index 7e30050d6..6aac56787 100644
--- a/src/web/src/hooks/community/use-community-ws.ts
+++ b/src/web/src/hooks/community/use-community-ws.ts
@@ -1,9 +1,9 @@
"use client"
import { captureCommunityLiveSnapshotToken, assertCommunityLiveSnapshotTokenCurrent } from "@/lib/community-db/sync"
-import { useCommunityRuntime, type CommunityRuntime } from "@/stores/community/runtime"
+import { bindCommunityTransport, useCommunityRuntime, type CommunityRuntime } from "@/stores/community/runtime"
-import { useCallback, useEffect, useRef } from "react"
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from "react"
import { useQueryClient } from "@tanstack/react-query"
import { cancelMessageRepairs } from "@/hooks/community/community-ws/reconnect-messages"
import {
@@ -11,7 +11,6 @@ import {
type UserWsConnectionPhase,
} from "@/lib/use-user-ws"
-import { SEEN_DELIVERY_OPERATION_MAX, SEEN_DELIVERY_OPERATION_TRIM_TO } from "@/stores/community/ws"
import {
reconcileCommunityWsReconnect,
reconcileFocusedCommunityMessages,
@@ -21,20 +20,11 @@ import {
dispatchCommunityWsEvents,
} from "@/hooks/community/community-ws/registry"
import { reconcileAccountReadState } from "@/hooks/community/community-ws/read-state-reconciliation"
-import { scheduleAccountAttentionReconcile } from "@/hooks/community/use-account-attention"
-import { getAccountUnreadProjection } from "@/hooks/community/account-unread-projection"
-import { runCommunityWsProjectionTransaction } from "@/hooks/community/community-ws/projection-transaction"
-import {
- invalidateDms,
- invalidateInbox,
-} from "@/hooks/community/community-ws/invalidation-projections"
import type {
- CommunityInboxRefreshRequest,
CommunityWsDispatchContext,
Subscription,
UseCommunityWsOptions,
} from "@/hooks/community/community-ws/handler-context"
-import { flushPendingReadIntents } from "@/hooks/community/read-coordinator"
import {
decodeCommunityBrowserEvent,
communityBrowserEventBatchType,
@@ -82,83 +72,12 @@ export type {
// ── Constants ─────────────────────────────────────────────────────────────
-// Debounce inbox invalidation so a busy channel doesn't fire one refetch per
-// message. 500ms matches the mark-channel-read debounce so both fire once per
-// message burst.
-const INBOX_INVALIDATE_DEBOUNCE_MS = 500
-
-type InboxRefreshGeneration = CommunityInboxRefreshRequest & {
- id: number
- dueAt: number
-}
-
-type InboxRefreshOwner = {
- current: InboxRefreshGeneration | null
- next: InboxRefreshGeneration | null
- timer: ReturnType<typeof setTimeout> | null
- running: boolean
- nextGenerationId: number
- epoch: number
- claimedOperationKeys: Set<string>
- claimedOperationOrder: string[]
- disposed: boolean
-}
-
-function mergeInboxRefresh(
- target: CommunityInboxRefreshRequest,
- incoming: CommunityInboxRefreshRequest,
-) {
- target.dms ||= incoming.dms
-}
-
-function deliveryInboxRefresh(
- events: readonly CommunityWsEvent[],
- viewerId: string | null,
-): CommunityInboxRefreshRequest | null {
- let inbox = false
- let dms = false
- for (const event of events) {
- if (event.type === "community:unread.bump" && event.userId === viewerId) {
- inbox = true
- dms ||= !event.serverId
- }
- if (event.type === "community:mention.create" && event.userId === viewerId) inbox = true
- }
- return inbox ? { inbox: true, dms } : null
-}
-
function hasCommunityFunnelTrigger(events: readonly CommunityWsEvent[]) {
return events.some((event) => event.type === "community:machine.status"
|| event.type === "community:message.create"
|| event.type === "community:member.join")
}
-function claimInboxRefreshOperation(owner: InboxRefreshOwner, key: string) {
- if (owner.claimedOperationKeys.has(key)) return false
- owner.claimedOperationKeys.add(key)
- owner.claimedOperationOrder.push(key)
- if (owner.claimedOperationOrder.length > SEEN_DELIVERY_OPERATION_MAX) {
- const retained = owner.claimedOperationOrder.slice(-SEEN_DELIVERY_OPERATION_TRIM_TO)
- owner.claimedOperationOrder = retained
- owner.claimedOperationKeys = new Set(retained)
- }
- return true
-}
-
-function armInboxRefreshGeneration(
- owner: InboxRefreshOwner,
- generation: InboxRefreshGeneration,
- run: (generation: InboxRefreshGeneration, epoch: number) => Promise<void>,
-) {
- if (owner.disposed) return
- owner.timer = setTimeout(() => {
- if (owner.disposed) return
- owner.timer = null
- owner.running = true
- void run(generation, owner.epoch)
- }, Math.max(0, generation.dueAt - Date.now()))
-}
-
// ── Public hook ────────────────────────────────────────────────────────────
// Module-level slot for the currently-active WS `send`. The root-mounted
@@ -251,118 +170,24 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
return () => { unsubscribe(); void cancelMessageRepairs(queryClient) }
}, [queryClient])
const viewerUserIdRef = useRef<string | null>(options?.viewerUserId ?? null)
- const hasAuthenticatedRef = useRef(false)
const viewerUserId = options?.viewerUserId ?? null
- if (viewerUserId) getAccountUnreadProjection(queryClient, viewerUserId)
- viewerUserIdRef.current = viewerUserId
+ const viewToken = useMemo(() => ({ queryClient, runtime, viewerUserId }), [queryClient, runtime, viewerUserId])
+ const activeViewRef = useRef<typeof viewToken | null>(null)
+
+ useLayoutEffect(() => {
+ viewerUserIdRef.current = viewerUserId
+ activeViewRef.current = viewToken
+ return () => { if (activeViewRef.current === viewToken) activeViewRef.current = null }
+ }, [viewerUserId, viewToken])
useEffect(() => {
if (!viewerUserId) return
runtime.ws.actions.setPresence(viewerUserId, "online")
}, [runtime.ws.actions, viewerUserId])
- const inboxRefreshOwner = useRef<InboxRefreshOwner | null>(null)
- if (inboxRefreshOwner.current === null) {
- inboxRefreshOwner.current = {
- current: null,
- next: null,
- timer: null,
- running: false,
- nextGenerationId: 0,
- epoch: 0,
- claimedOperationKeys: new Set(),
- claimedOperationOrder: [],
- disposed: false,
- }
- }
- const runInboxGeneration = useCallback(async function runInboxGeneration(
- generation: InboxRefreshGeneration,
- epoch: number,
- ) {
- const owner = inboxRefreshOwner.current
- if (
- !owner
- || owner.disposed
- || owner.epoch !== epoch
- || owner.current?.id !== generation.id
- ) {
- /* istanbul ignore next -- the sole timer caller validates and enters synchronously */
- return
- }
- let consumed = false
- let deferred = false
- try {
- const outcome = await flushPendingReadIntents(queryClient, {
- deferInboxDms: () => {
- const latest = inboxRefreshOwner.current
- return latest?.epoch === epoch
- && latest.current?.id === generation.id
- && latest.next !== null
- },
- })
- consumed = outcome.consumed
- deferred = outcome.deferred === true
- } catch {
- /* istanbul ignore next -- the coordinator normalizes every real failure into an outcome */
- consumed = false
- /* istanbul ignore next -- the coordinator normalizes every real failure into an outcome */
- deferred = false
- }
- const current = inboxRefreshOwner.current
- if (
- !current
- || current.disposed
- || current.epoch !== epoch
- || current.current?.id !== generation.id
- ) return
- if (deferred && current.next) mergeInboxRefresh(current.next, generation)
- if (!consumed && !deferred) {
- runCommunityWsProjectionTransaction(queryClient, (projection) => {
- if (generation.inbox) invalidateInbox(projection)
- if (generation.dms) invalidateDms(projection)
- })
- }
- current.current = current.next
- current.next = null
- current.running = false
- if (current.current) {
- armInboxRefreshGeneration(current, current.current, runInboxGeneration)
- }
- }, [queryClient])
- const scheduleInboxInvalidate = useCallback((
- request: CommunityInboxRefreshRequest,
- operationKey?: string,
- ) => {
- const owner = inboxRefreshOwner.current
- if (!owner || owner.disposed) return
- if (operationKey && !claimInboxRefreshOperation(owner, operationKey)) return
- if (owner.current === null) {
- owner.current = {
- ...request,
- id: ++owner.nextGenerationId,
- dueAt: Date.now() + INBOX_INVALIDATE_DEBOUNCE_MS,
- }
- armInboxRefreshGeneration(owner, owner.current, runInboxGeneration)
- return
- }
- if (!owner.running) {
- mergeInboxRefresh(owner.current, request)
- return
- }
- if (owner.next === null) {
- owner.next = {
- ...request,
- id: ++owner.nextGenerationId,
- dueAt: Date.now() + INBOX_INVALIDATE_DEBOUNCE_MS,
- }
- return
- }
- mergeInboxRefresh(owner.next, request)
- }, [runInboxGeneration])
-
const handleMessage = useCallback(
async (msg: { type: string;[key: string]: unknown }, assertAdmissionCurrent?: () => void, contract: CommunityContract = 2) => {
if (!msg.type.startsWith("community:")) return
- if (!runtime.lifecycle.get().active) return
+ if (activeViewRef.current !== viewToken || !runtime.lifecycle.get().active) return
const communityStore = runtime.ui
const sub = communityStore.get().subscription
const wsStore = runtime.ws
@@ -380,7 +205,6 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
}
const context = (
deliveryMode: "single" | "batch",
- requestInboxRefresh = scheduleInboxInvalidate,
): CommunityWsDispatchContext => ({
contract,
deliveryMode,
@@ -390,16 +214,13 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
sub,
viewerUserIdRef,
matchesFocus,
- scheduleInboxInvalidate: requestInboxRefresh,
})
const reconcileAfterBatchFailure = (
reason: "digest-conflict" | "projection-failed",
- inboxOwned: boolean,
) => {
void reconcileCommunityWsReconnect(
queryClient,
0,
- inboxOwned ? { excludePolicies: ["inbox-dms"] } : undefined,
).catch(() => {
console.warn("[ws] batch reconciliation failed", {
event: "community_ws_batch_reconciliation_failed",
@@ -418,7 +239,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
const admission = admitCommunityBrowserEventBatch(msg)
const decoded = admission instanceof Promise ? await admission : admission
try { assertAdmissionCurrent?.(); assertCommunityLiveSnapshotTokenCurrent(queryClient, token, undefined) } catch { return }
- if (!runtime.lifecycle.get().active) return
+ if (activeViewRef.current !== viewToken || !runtime.lifecycle.get().active) return
if (!decoded.ok) {
const reason = decoded.reason === "oversized" ? "oversized" : "invalid-payload"
const metadata = {
@@ -437,11 +258,6 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
decoded.batch.operationId,
decoded.batch.operationDigest,
)
- const batchRefresh = deliveryInboxRefresh(
- decoded.events,
- viewerUserIdRef.current,
- )
- const operationKey = `delivery:${decoded.batch.operationId}:${decoded.batch.operationDigest}`
if (operationStatus === "duplicate") return
if (operationStatus === "conflict") {
console.warn("[ws] delivery operation digest conflict", {
@@ -450,27 +266,13 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
operationDigest: decoded.batch.operationDigest,
eventCount: decoded.events.length,
})
- if (batchRefresh) {
- scheduleInboxInvalidate(
- batchRefresh,
- `conflict:${decoded.batch.operationId}:${decoded.batch.operationDigest}`,
- )
- }
- reconcileAfterBatchFailure("digest-conflict", batchRefresh !== null)
+ reconcileAfterBatchFailure("digest-conflict")
return
}
- let collectedRefresh: CommunityInboxRefreshRequest | null = null
- const collectInboxRefresh = (request: CommunityInboxRefreshRequest) => {
- if (collectedRefresh === null) {
- collectedRefresh = { ...request }
- } else {
- mergeInboxRefresh(collectedRefresh, request)
- }
- }
try {
const publication = dispatchCommunityWsEvents(
decoded.events,
- context("batch", collectInboxRefresh),
+ context("batch"),
)
if (publication) await publication
} catch {
@@ -480,8 +282,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
operationDigest: decoded.batch.operationDigest,
eventCount: decoded.events.length,
})
- if (batchRefresh) scheduleInboxInvalidate(batchRefresh, operationKey)
- reconcileAfterBatchFailure("projection-failed", batchRefresh !== null)
+ reconcileAfterBatchFailure("projection-failed")
return
}
// Complete dedup only after every child projected successfully. The
@@ -493,7 +294,6 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
// Keeping the failed operation locked but incomplete lets the
// identical bundle retry, so idempotent child projections can finish
// converging even when authoritative reconnect reconciliation fails.
- if (collectedRefresh) scheduleInboxInvalidate(collectedRefresh, operationKey)
runtime.ws.actions.completeDeliveryOperation(
decoded.batch.operationId,
decoded.batch.operationDigest,
@@ -524,39 +324,29 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
void drainInvitedHumanJoined(runtime.lifecycle)
}
},
- [queryClient, runtime.lifecycle, runtime.ui, runtime.ws, scheduleInboxInvalidate],
+ [queryClient, runtime.lifecycle, runtime.ui, runtime.ws, viewToken],
)
const handleReconnect = useCallback(async ({ reconnectDurationMs }: { reconnectDurationMs: number }) => {
- try {
- await reconcileCommunityWsReconnect(queryClient, reconnectDurationMs, {
- excludePolicies: ["inbox-dms"],
- viewerUserId: viewerUserIdRef.current,
- })
- } finally {
- scheduleAccountAttentionReconcile(queryClient)
- }
- }, [queryClient])
+ if (activeViewRef.current !== viewToken || !runtime.lifecycle.get().active) return
+ await reconcileCommunityWsReconnect(queryClient, reconnectDurationMs, { viewerUserId: viewerUserIdRef.current })
+ }, [queryClient, runtime.lifecycle, viewToken])
const handleAuthenticated = useCallback(async () => {
+ if (activeViewRef.current !== viewToken || !runtime.lifecycle.get().active) return
void drainInvitedHumanJoined(runtime.lifecycle)
runtime.ws.actions.markAccessConnected()
const viewerId = viewerUserIdRef.current
if (viewerId) {
runtime.ws.actions.setPresence(viewerId, "online")
}
- const firstAuthentication = !hasAuthenticatedRef.current
- hasAuthenticatedRef.current = true
- if (firstAuthentication) {
- scheduleAccountAttentionReconcile(queryClient)
- }
- await reconcileAccountReadState(queryClient, { surfaceMode: "non-inbox" })
- }, [queryClient, runtime.ws.actions, runtime.lifecycle])
+ await reconcileAccountReadState(queryClient)
+ }, [queryClient, runtime.ws.actions, runtime.lifecycle, viewToken])
const handleForeground = useCallback(() => {
- if (inboxRefreshOwner.current?.disposed
+ if (activeViewRef.current !== viewToken || !runtime.lifecycle.get().active
|| viewerUserIdRef.current !== viewerUserId
|| (viewerUserId !== null && runtime.ws.get().profileViewerId !== viewerUserId)) return
return reconcileFocusedCommunityMessages(queryClient)
- }, [queryClient, runtime.ws, viewerUserId])
+ }, [queryClient, runtime.ws, runtime.lifecycle, viewerUserId, viewToken])
const { send, reconnectNow } = useUserWs(handleMessage, {
viewerUserId,
communityContract: options?.communityContract,
@@ -580,13 +370,8 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
useEffect(() => {
if (typeof document === "undefined" || typeof window === "undefined") return
const reconcileVisible = () => {
- if (document.visibilityState !== "visible") return
- if (runtime.ws.get().accessConnected) {
- scheduleAccountAttentionReconcile(queryClient)
- }
- void reconcileAccountReadState(queryClient, {
- surfaceMode: "non-inbox",
- }).catch(() => undefined)
+ if (activeViewRef.current !== viewToken || !runtime.lifecycle.get().active || document.visibilityState !== "visible") return
+ void reconcileAccountReadState(queryClient).catch(() => undefined)
}
document.addEventListener("visibilitychange", reconcileVisible)
window.addEventListener("pageshow", reconcileVisible)
@@ -594,19 +379,9 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
document.removeEventListener("visibilitychange", reconcileVisible)
window.removeEventListener("pageshow", reconcileVisible)
}
- }, [queryClient, runtime.ws])
+ }, [queryClient, runtime.lifecycle, viewToken])
- useEffect(() => {
- if (runtime.transport.send !== null && runtime.transport.send !== send) {
- console.warn(
- "[useCommunityWs] Multiple instances detected — mount this hook once at the tree root.",
- )
- }
- runtime.transport.send = send
- return () => {
- if (runtime.transport.send === send) runtime.transport.send = null
- }
- }, [send, runtime])
+ useEffect(() => bindCommunityTransport(runtime, send), [send, runtime])
useEffect(() => {
const controller = getConnectionController()
@@ -624,19 +399,4 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
}
}, [getConnectionController, runtime.ws, runtime.ws.actions])
- useEffect(() => {
- const owner = inboxRefreshOwner.current
- if (owner) owner.disposed = false
- return () => {
- const current = inboxRefreshOwner.current
- if (!current) return
- current.disposed = true
- current.epoch += 1
- if (current.timer !== null) clearTimeout(current.timer)
- current.timer = null
- current.current = null
- current.next = null
- current.running = false
- }
- }, [])
}
diff --git a/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx b/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx
index 00da1f557..5f46f921c 100644
--- a/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx
+++ b/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx
@@ -23,7 +23,6 @@ import type { FlatItem } from "@/lib/community/message-list-items"
import { renderMessageListRow } from "@/components/community/messages/message-list-row"
import { confirmReadSurface, disposeReadCoordinator, getReadCoordinator, registerReadSurface, releaseReadSurface, submitReadIntentGeneration } from "./read-coordinator"
import { disposeAccountReadStateReconciliation } from "./community-ws/read-state-reconciliation"
-import { getAccountUnreadProjection } from "./account-unread-projection"
const load = vi.hoisted(() => vi.fn())
vi.mock("@/lib/api/client", async (original) => ({ ...await original<typeof import("@/lib/api/client")>(), apiFetch: (...args: unknown[]) => load(...args) }))
@@ -426,7 +425,7 @@ describe("conversation entry return during accepted reading", () => {
}
})
- it.each(["before PUT confirmation", "after PUT before canonical publication", "after ACK and failed canonical readback"] as const)(
+ it.each(["before PUT confirmation", "after ACK before canonical readback", "after ACK and failed canonical readback"] as const)(
"keeps accepted local reading in the returned viewport %s without confirming the entry snapshot", async boundary => {
const owner = await readingOwner()
const first = mountReadingEntry(owner)
@@ -440,7 +439,6 @@ describe("conversation entry return during accepted reading", () => {
const generation = submitReadIntentGeneration(owner.lease, { kind: "timeline", channelId: "c1", messageId: "m42", seq: 42 })
expect(generation).not.toBeNull()
expect(owner.scope().accepted?.intent).toEqual({ kind: "timeline", channelId: "c1", messageId: "m42", seq: 42 })
- getAccountUnreadProjection(owner.client, "viewer").recordOptimisticRead("c1", 42, generation!)
expect(submitReadIntentGeneration(owner.lease, { kind: "timeline", channelId: "c1", messageId: "m31", seq: 31 })).toBeNull()
first.view.unmount()
releaseReadSurface(owner.lease)
@@ -464,11 +462,11 @@ describe("conversation entry return during accepted reading", () => {
expect(owner.scope().confirmedSeq).toBe(30)
expect(load.mock.calls.some(([url]) => url === "/api/community/users/me/read-state")).toBe(false)
}
- expect(currentConversationReadState(owner.client, "c1")?.lastReadSeq).toBe(30)
+ expect(currentConversationReadState(owner.client, "c1")?.lastReadSeq).toBe(boundary === "before PUT confirmation" ? 30 : 42)
returned = mountReadingEntry(owner)
expect(returned.latest.feed.messages).toHaveLength(42)
- expect(returned.latest.feed.readSnapshot?.lastReadSeq).toBe(30)
- expect(returned.latest.newDividerBefore).toBe("m31")
+ expect(returned.latest.feed.readSnapshot?.lastReadSeq).toBe(boundary === "before PUT confirmation" ? 30 : 42)
+ expect(returned.latest.newDividerBefore).toBe(boundary === "before PUT confirmation" ? "m31" : undefined)
expect(returned.latest.controller.readPositionReady).toBe(true)
expect(returned.visible("m42")).toBe(true)
const offset = returned.root.scrollTop, captured = returned.latest.feed.readSnapshot
diff --git a/src/web/src/hooks/community/use-dms.dom.test.ts b/src/web/src/hooks/community/use-dms.dom.test.ts
index f736a66f3..2bb37c12b 100644
--- a/src/web/src/hooks/community/use-dms.dom.test.ts
+++ b/src/web/src/hooks/community/use-dms.dom.test.ts
@@ -4,7 +4,6 @@ import { act, render } from "@/test/react-dom-harness"
import { QueryClient, QueryClientProvider as BareQueryClientProvider } from "@tanstack/react-query"
import { CommunityTestProvider as QueryClientProvider } from "@/test/community-owner-fixture"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
-import { getActiveAccountUnreadProjection } from "./account-unread-projection"
import { dmsProjectedQueryFn } from "./use-dms"
import { communityKeys } from "@/lib/query-keys"
import { useCommunityWsStore } from "@/stores/community/ws"
@@ -59,7 +58,7 @@ describe("useDms / dmsQueryFn", () => {
]
apiFetchMock.mockResolvedValueOnce({ conversations })
const { client: qc, registry } = await createCommunityQueryOwner()
- const data = await qc.query({ queryKey: communityKeys.dms(), queryFn: dmsProjectedQueryFn(getActiveAccountUnreadProjection(qc), qc) })
+ const data = await qc.query({ queryKey: communityKeys.dms(), queryFn: dmsProjectedQueryFn(qc) })
expect(apiFetchMock).toHaveBeenCalledWith("/api/community/users/me/dms", expect.objectContaining({ signal: expect.any(AbortSignal), authenticationAccount: "viewer" }))
expect(data).toEqual({ ids: ["dm_1"] })
expect(registry.collections.channels.get("dm_1")?.type).toBe("dm")
@@ -70,7 +69,7 @@ describe("useDms / dmsQueryFn", () => {
apiFetchMock.mockResolvedValueOnce({ conversations: [] })
const { client: qc } = await createCommunityQueryOwner()
const key = communityKeys.dms()
- await qc.query({ queryKey: key, queryFn: dmsProjectedQueryFn(getActiveAccountUnreadProjection(qc), qc) })
+ await qc.query({ queryKey: key, queryFn: dmsProjectedQueryFn(qc) })
expect(apiFetchMock).toHaveBeenCalledWith(
"/api/community/users/me/dms",
expect.objectContaining({ signal: expect.any(AbortSignal) }),
@@ -78,20 +77,6 @@ describe("useDms / dmsQueryFn", () => {
expect(qc.getQueryData(key)).toEqual({ ids: [] })
})
- it("uses a complete DM list as authoritative negative evidence", async () => {
- apiFetchMock.mockResolvedValueOnce({ conversations: [] })
- const { dmsProjectedQueryFn } = await import("./use-dms")
- const { AccountUnreadProjection } = await import("./account-unread-projection")
- const projection = new AccountUnreadProjection("u1")
- projection.setNotificationPolicy({})
- projection.recordArrival({ channelId: "dm_1", seq: 3 })
- const { client: queryClient } = await createCommunityQueryOwner()
-
- await queryClient.query({ queryKey: communityKeys.dms(), queryFn: dmsProjectedQueryFn(projection, queryClient) })
-
- expect(projection.projectUnread("dms", "dm_1", false)).toBe(false)
- })
-
it.each(["cancel", "account", "access"] as const)(
"rejects a %s-superseded DM list before destructive publication",
async (race) => {
@@ -104,11 +89,9 @@ describe("useDms / dmsQueryFn", () => {
const request = deferred<{ conversations: DM[] }>()
apiFetchMock.mockReturnValueOnce(request.promise)
const { dmsProjectedQueryFn } = await import("./use-dms")
- const { AccountUnreadProjection } = await import("./account-unread-projection")
- const projection = new AccountUnreadProjection("viewer")
const controller = new AbortController()
- const pending = dmsProjectedQueryFn(projection, queryClient)({
+ const pending = dmsProjectedQueryFn(queryClient)({
client: queryClient, signal: controller.signal,
} as never)
await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledWith(
@@ -122,7 +105,6 @@ describe("useDms / dmsQueryFn", () => {
await expect(pending).rejects.toMatchObject({ name: "AbortError" })
expect(registry.collections.channels.get("dm-current")).toBeDefined()
- expect(projection.inspectForTests().pendingSnapshots).toBe(0)
unregister()
await disposeRegistry()
},
@@ -137,27 +119,14 @@ describe("useDms / dmsQueryFn", () => {
ingestDms(registry, { conversations: [dm("dm-current")] })
apiFetchMock.mockResolvedValueOnce({ conversations: [] })
const { dmsProjectedQueryFn } = await import("./use-dms")
- const { AccountUnreadProjection } = await import("./account-unread-projection")
- await queryClient.query({ queryKey: communityKeys.dms(), queryFn: dmsProjectedQueryFn(new AccountUnreadProjection("viewer"), queryClient) })
+ await queryClient.query({ queryKey: communityKeys.dms(), queryFn: dmsProjectedQueryFn(queryClient) })
expect(registry.collections.channels.get("dm-current")).toBeUndefined()
unregister()
await disposeRegistry()
})
- it("cancels DM snapshot coverage when the transport fails", async () => {
- apiFetchMock.mockRejectedValueOnce(new Error("offline"))
- const { dmsProjectedQueryFn } = await import("./use-dms")
- const { AccountUnreadProjection } = await import("./account-unread-projection")
- const projection = new AccountUnreadProjection("u1")
-
- const { client: qc } = await createCommunityQueryOwner()
- await expect(qc.query({ queryKey: communityKeys.dms(), queryFn: dmsProjectedQueryFn(projection, qc) })).rejects.toThrow("offline")
-
- expect(projection.inspectForTests().pendingSnapshots).toBe(0)
- })
-
it("reuses a projected DM across layout mounts without refetching the canonical list", async () => {
const conversations = [{
id: "dm_projected",
@@ -329,10 +298,8 @@ describe("useDms / dmsQueryFn", () => {
] as DM[]
apiFetchMock.mockResolvedValue({ conversations })
const { useDms } = await import("./use-dms")
- const { getActiveAccountUnreadProjection } = await import("./account-unread-projection")
const { client: qc } = await createCommunityQueryOwner()
seedDms(qc, { conversations })
- getActiveAccountUnreadProjection(qc).recordArrival({ channelId: "dm_1", seq: 2 })
let latest: ReturnType<typeof useDms> | undefined
function Harness() {
diff --git a/src/web/src/hooks/community/use-dms.ts b/src/web/src/hooks/community/use-dms.ts
index b5c3c5e7b..2f2f4b184 100644
--- a/src/web/src/hooks/community/use-dms.ts
+++ b/src/web/src/hooks/community/use-dms.ts
@@ -15,17 +15,11 @@ import {
} from "@/lib/community/profile-seed"
import { communityKeys } from "@/lib/query-keys"
import type { DM } from "@/lib/community/models/people"
-import { useEffect, useMemo } from "react"
+import { useMemo } from "react"
import {
- useAttentionScopes,
useCanonicalProfilesByUserId,
} from "@/lib/community-db/projections"
import { readCommunityProfile } from "@/lib/community/profile-read"
-import {
- getActiveAccountUnreadProjection,
- type AccountUnreadProjection,
- type AccountUnreadSource,
-} from "./account-unread-projection"
import { useDmProjection } from "@/lib/community-db/projections"
import {
assertCommunityLiveSnapshotTokenCurrent,
@@ -56,45 +50,29 @@ const loadDms = (
context.signal ? { signal: context.signal } : undefined, getCommunityDbRegistry(context.client),
)
-function dmUnreadSources(data: readonly DM[]): AccountUnreadSource[] {
- return data.flatMap((dm) => dm.lastUnreadSeq === undefined ? [] : [{
- channelId: dm.id,
- lastUnreadSeq: dm.lastUnreadSeq,
- }])
-}
-
export const dmsProjectedQueryFn = (
- projection: AccountUnreadProjection,
queryClient: QueryClient,
) => async (context: QueryFunctionContext) => {
const publicationToken = captureCommunityLiveSnapshotToken(queryClient)
- const token = projection.beginSnapshot("dms", "dms")
try {
const data = await loadDms(context)
assertCommunityLiveSnapshotTokenCurrent(queryClient, publicationToken, context.signal)
- projection.absorbSnapshot(token, dmUnreadSources(data.conversations))
publishCommunityLiveSnapshot(queryClient, {
snapshot: { kind: "dms", data },
proof: { kind: "structural", token: publicationToken, signal: context.signal },
})
return { ids: data.conversations.map((dm) => dm.id) }
} catch (error) {
- projection.cancelSnapshot(token)
throw error
}
}
export function useDms(enabled = true): UseQueryResult<{ ids: string[] }> & { dms: DM[] } {
- const attentionScopes = useAttentionScopes()
const dbDms = useDmProjection()
const queryClient = useQueryClient()
- const unreadProjection = useMemo(
- () => getActiveAccountUnreadProjection(queryClient),
- [queryClient],
- )
const queryFn = useMemo(
- () => dmsProjectedQueryFn(unreadProjection, queryClient),
- [queryClient, unreadProjection],
+ () => dmsProjectedQueryFn(queryClient),
+ [queryClient],
)
const query = useQuery({
queryKey: communityKeys.dms(),
@@ -108,31 +86,12 @@ export function useDms(enabled = true): UseQueryResult<{ ids: string[] }> & { dm
staleTime: 30_000,
})
const profilesByUserId = useCanonicalProfilesByUserId()
- useEffect(() => {
- if (!dbDms) return
- unreadProjection.mergeSources(
- "dms",
- dmUnreadSources(dbDms),
- "dms",
- )
- unreadProjection.recordLegacySnapshot(
- dbDms,
- dbDms.flatMap((dm) => (
- dm.unread && dm.lastUnreadSeq === undefined
- ? [{ family: "dms" as const, channelId: dm.id }]
- : []
- )),
- )
- }, [dbDms, unreadProjection])
const dms = useMemo(() => {
const source = dbDms ?? EMPTY_DMS
if (source.length === 0) return EMPTY_DMS as DM[]
return sortDmsByActivity(source.map((dm) => {
const liveProfile = profilesByUserId.get(dm.userId)
const profile = readCommunityProfile(liveProfile, dm.userId)
- const unread = attentionScopes.some((scope) => (
- !scope.serverId && scope.channelId === dm.id && scope.ordinaryUnread
- ))
return {
...dm,
name: liveProfile?.name ?? dm.name,
@@ -140,10 +99,9 @@ export function useDms(enabled = true): UseQueryResult<{ ids: string[] }> & { dm
avatar: liveProfile?.avatar ?? dm.avatar,
avatarVersion: liveProfile?.avatarVersion ?? dm.avatarVersion,
status: liveProfile ? profile.presence : "offline",
- unread,
}
}))
- }, [attentionScopes, dbDms, profilesByUserId])
+ }, [dbDms, profilesByUserId])
return {
...query,
dms,
diff --git a/src/web/src/hooks/community/use-forum-opener-hint.dom.test.ts b/src/web/src/hooks/community/use-forum-opener-hint.dom.test.ts
index 5bcc38f07..65bd1504e 100644
--- a/src/web/src/hooks/community/use-forum-opener-hint.dom.test.ts
+++ b/src/web/src/hooks/community/use-forum-opener-hint.dom.test.ts
@@ -23,12 +23,6 @@ vi.mock("@/lib/api/client", () => ({
apiFetch: (...args: unknown[]) => apiFetchMock(...args),
}))
-function wrapperFor(queryClient: QueryClient) {
- return function QueryWrapper({ children }: PropsWithChildren) {
- return createElement(QueryClientProvider, { client: queryClient }, children)
- }
-}
-
const cleanups: Array<() => void | Promise<void>> = []
beforeEach(() => {
@@ -91,13 +85,15 @@ describe("useForumOpenerHint", () => {
rendered.unmount()
})
- it("does not fetch or authorize content before the route metadata is verified", () => {
- const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ it("does not fetch or authorize content before the route metadata is verified", async () => {
+ const { queryClient, wrapper } = await canonicalSetup()
renderHook(() => useForumOpenerHint("server-1", "opener-1", false), {
- wrapper: wrapperFor(queryClient),
+ wrapper,
})
expect(apiFetchMock).not.toHaveBeenCalled()
+ expect(queryClient.getQueryCache().find({ queryKey: communityKeys.message("opener-1"), exact: true })).toBeUndefined()
+ expect(getCanonicalCommunityMessages(queryClient)).toEqual([])
})
it("refetches a legacy seeded hint that lacks the opener seq", async () => {
diff --git a/src/web/src/hooks/community/use-forum-sidebar-threads.dom.test.ts b/src/web/src/hooks/community/use-forum-sidebar-threads.dom.test.ts
index f2fa14a02..eb1ce5e82 100644
--- a/src/web/src/hooks/community/use-forum-sidebar-threads.dom.test.ts
+++ b/src/web/src/hooks/community/use-forum-sidebar-threads.dom.test.ts
@@ -1,3 +1,4 @@
+import { seedCommunityAttentionScope } from "@/test/community-query-owner"
import { conversationEntryFromChannel } from "@/test/conversation-entry-fixtures"
import { conversationEntryOptions } from "@/lib/community/conversation-entry"
import "fake-indexeddb/auto"
@@ -319,8 +320,8 @@ describe("forum sidebar canonical projection", () => {
name: "Readable archived post", archived: false, pending: false, tags: ["archived"],
parentChannelId: "forum-1", parentMessageId: "opener-1",
})
- expect(registry.collections.channelMemberships.get("post-1:viewer:notify")).toBeDefined()
- expect(registry.collections.channelMemberships.get("post-1:viewer:access")).toBeDefined()
+ expect(registry.collections.channelMemberships.get("post-1:viewer:notify")).toBeUndefined()
+ expect(registry.runtime.ws.actions.isChannelAccessRevoked("post-1", "server-1")).toBe(false)
expect(rendered.result.current.metadata.isVerified).toBe(true)
expect(apiFetchMock).toHaveBeenCalledTimes(2)
rendered.unmount()
@@ -501,11 +502,12 @@ describe("forum sidebar canonical projection", () => {
const expired = new Date(Date.now() - 73 * 60 * 60 * 1000).toISOString()
Object.assign(response.channels[5]!, { activityAt: expired, lastMessageAt: expired, expiresAt: new Date(Date.now() - 60 * 60 * 1000).toISOString(), unread: true })
publish(queryClient, response)
+ seedCommunityAttentionScope(queryClient, { channelId: "post-6", serverId: "server-1", parentChannelId: "forum-1" })
const rendered = renderHook(() => useForumSidebarProjection("server-1", "post-6", Date.now()), { wrapper })
await waitFor(() => expect(rendered.result.current?.threads).toHaveLength(5))
expect(rendered.result.current).toMatchObject({
threads: expect.arrayContaining([expect.objectContaining({ id: "post-6", unread: true })]),
- parentUnread: { "forum-1": false },
+ parentUnread: { "forum-1": true },
})
rendered.rerender()
rendered.unmount()
@@ -530,7 +532,7 @@ describe("forum sidebar canonical projection", () => {
const result = await reconcileForumSidebarNotifyMemberships(queryClient, "server-1")
expect(result.removedIds).toEqual([])
expect(registry.collections.channelMemberships.get("post-1:other:notify")).toBeDefined()
- expect(registry.collections.channels.get("post-1")?.unread).toBe(true)
+ expect(registry.collections.channels.get("post-1")).not.toHaveProperty("unread")
rendered.unmount()
})
@@ -916,10 +918,11 @@ describe("forum sidebar canonical projection", () => {
it("keeps normalized child unread and parent ownership in the canonical view", async () => {
const { queryClient, wrapper } = await setup()
publish(queryClient, envelope())
+ seedCommunityAttentionScope(queryClient, { channelId: "post-1", serverId: "server-1", parentChannelId: "forum-1" })
const rendered = renderHook(() => useForumSidebarProjection("server-1", null, Date.now()), { wrapper })
await waitFor(() => expect(rendered.result.current).toEqual({
threads: [expect.objectContaining({ id: "post-1", unread: true })],
- parentUnread: { "forum-1": false },
+ parentUnread: { "forum-1": true },
}))
rendered.unmount()
})
@@ -1250,7 +1253,7 @@ describe("forum sidebar canonical projection", () => {
threads: [],
parentUnread: {},
}))
- expect(registry.collections.channels.get("post-1")).toMatchObject({ unread: false })
+ expect(registry.collections.channels.get("post-1")).not.toHaveProperty("unread")
expect(registry.collections.channelMemberships.get("post-1:viewer:access"))
.toBeDefined()
expect(registry.collections.channelMemberships.get("post-1:viewer:notify"))
@@ -1259,7 +1262,7 @@ describe("forum sidebar canonical projection", () => {
})
it("keeps cold hidden-child unread ownership in canonical rows", async () => {
- const { registry, wrapper } = await setup()
+ const { queryClient, registry, wrapper } = await setup()
ingestServerDetail(registry, {
id: "server-1", name: "Server", discriminator: "0001", description: "",
icon: null, ownerId: "viewer", categories: [{
@@ -1271,6 +1274,7 @@ describe("forum sidebar canonical projection", () => {
"forum-1": { baseUnread: false, childIds: ["hidden-child"] },
},
})
+ seedCommunityAttentionScope(queryClient, { channelId: "hidden-child", serverId: "server-1", parentChannelId: "forum-1" })
const rendered = renderHook(
() => useForumSidebarProjection("server-1", null, Date.now()),
{ wrapper },
@@ -1279,16 +1283,15 @@ describe("forum sidebar canonical projection", () => {
threads: [],
parentUnread: { "forum-1": true },
}))
- expect(registry.collections.channels.get("hidden-child")).toMatchObject({
- type: "thread", parentChannelId: "forum-1", parentMessageId: null, unread: true,
- })
+ expect(registry.collections.channels.get("hidden-child")).toBeUndefined()
rendered.unmount()
})
it("aggregates persisted unread child ownership even without notify membership", async () => {
- const { queryClient, wrapper } = await setup()
+ const { queryClient, registry, wrapper } = await setup()
publish(queryClient)
- act(() => { removeCanonicalCommunityChannelMembership(queryClient, "post-1", "notify") });
+ registry.collections.channelMemberships.utils.writeDelete("post-1:viewer:notify")
+ seedCommunityAttentionScope(queryClient, { channelId: "post-1", serverId: "server-1", parentChannelId: "forum-1" })
const rendered = renderHook(
() => useForumSidebarProjection("server-1", null, Date.now()),
{ wrapper },
diff --git a/src/web/src/hooks/community/use-forum-sidebar-threads.ts b/src/web/src/hooks/community/use-forum-sidebar-threads.ts
index 2dcdfb3f1..73a46c0be 100644
--- a/src/web/src/hooks/community/use-forum-sidebar-threads.ts
+++ b/src/web/src/hooks/community/use-forum-sidebar-threads.ts
@@ -13,7 +13,6 @@ import { communityKeys } from "@/lib/query-keys"
import { forumSidebarWindowComplete, readForumSidebarWindowResult, type ForumSidebarWindow } from "@/lib/community/forum-sidebar-window"
import { useCommunityWsStore } from "@/stores/community/ws"
import {
-useAttentionScopes,
useServerSidebarProjection,
} from "@/lib/community-db/projections"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
@@ -32,7 +31,6 @@ type CommunityFreshQueryProof,
type CommunityForumSidebarChannel,
type CommunityForumSidebarOpener,
} from "@/lib/community-db/sync"
-import { getActiveAccountUnreadProjection } from "./account-unread-projection"
import { forumSidebarCandidates, viewerNotifyChannelIds, compareForumSidebarThreads as compareThreads,
FORUM_SIDEBAR_ACTIVITY_WINDOW_MS as SIDEBAR_ACTIVITY_WINDOW_MS, type ForumSidebarThread } from "@/lib/community/forum-sidebar"
export type { ForumSidebarThread } from "@/lib/community/forum-sidebar"
@@ -100,7 +98,7 @@ function projectForumSidebarThreads(data: SidebarThreadEnvelope) {
title: openerById.get(channel.parentMessageId)?.content || channel.name,
activityAt: channel.activityAt,
expiresAt: channel.expiresAt,
- unread: channel.unread,
+ unread: false,
}]
})
}
@@ -118,7 +116,7 @@ function sidebarChannelResource(
parentChannelId: channel.parentChannelId,
parentMessageId: channel.parentMessageId,
activityAt: channel.activityAt,
- unread: channel.unread,
+ unread: false,
participating: true,
}
}
@@ -285,17 +283,6 @@ export function hasForumSidebarOwnershipEvidence(
))
}
-export function removeForumSidebarUnreadChild(
- queryClient: QueryClient,
- _serverId: string,
- childChannelId: string,
-) {
- patchCanonicalCommunityChannel(queryClient, childChannelId, (row) => ({
- ...row,
- unread: false,
- }))
-}
-
export function patchForumSidebarActivityExact(
queryClient: QueryClient,
serverId: string,
@@ -330,7 +317,6 @@ export function removeForumSidebarProjectionExact(
childId: string,
) {
removeCanonicalCommunityChannelMembership(queryClient, childId, "notify")
- removeForumSidebarUnreadChild(queryClient, serverId, childId)
}
export async function invalidateForumSidebarBaseExact(
@@ -350,8 +336,6 @@ async function fetchForumSidebarBaseExact(
await queryClient.cancelQueries({ queryKey, exact: true })
await queryClient.invalidateQueries({ queryKey, exact: true, refetchType: "none" })
- const unreadProjection = getActiveAccountUnreadProjection(queryClient)
- const confirmation = unreadProjection.beginAccessConfirmation()
const token = captureCommunityLiveSnapshotToken(queryClient)
let normalized: NormalizedForumSidebarEnvelope | undefined
let proof: CommunityFreshQueryProof | undefined
@@ -371,13 +355,7 @@ async function fetchForumSidebarBaseExact(
signal,
token,
)
- unreadProjection.confirmAccessScopes(
- normalized.base.threads.map((thread) => ({
- kind: "channel" as const,
- channelId: thread.id,
- })),
- confirmation,
- )
+
reconciliation = result.reconciliation
return result.data
},
@@ -461,7 +439,7 @@ function reconcileForumSidebarNotifyMembershipsFromBase(
expiresAt: Number.isFinite(activityMs)
? new Date(activityMs + SIDEBAR_ACTIVITY_WINDOW_MS).toISOString()
: activityAt,
- unread: channel.unread,
+ unread: false,
}
if (siblings.length >= 5 && compareThreads(candidate, siblings[4]!) > 0) continue
publishCommunityForumSidebar(queryClient, {
@@ -484,15 +462,9 @@ export async function grantForumSidebarChild(queryClient: QueryClient, serverId:
retry: false,
queryFn: async ({ signal }: { signal: AbortSignal }) => {
const token = captureCommunityLiveSnapshotToken(queryClient)
- const unreadProjection = getActiveAccountUnreadProjection(queryClient)
- const confirmation = unreadProjection.beginAccessConfirmation()
const normalized = await fetchForumSidebar(queryClient, serverId, childId, signal, token)
const result = publishNormalizedForumSidebar(queryClient, serverId, normalized, childId, signal, token)
queryClient.setQueryData(communityKeys.forumSidebarThreads(serverId), result.data)
- if (hasForumSidebarThread(normalized.base, childId)
- || normalized.retainedDisposition === "eligible" && normalized.retained?.id === childId) {
- unreadProjection.confirmAccessScopes([{ kind: "channel", channelId: childId }], confirmation)
- }
return { id: childId, disposition: normalized.retainedDisposition, verifiedEpoch: token.accessEpoch }
},
}
@@ -525,29 +497,16 @@ export function useForumSidebarThreads(
) {
const queryClient = useQueryClient()
const accessEpoch = useCommunityWsStore((state) => state.accessEpoch)
- const unreadProjection = useMemo(
- () => getActiveAccountUnreadProjection(queryClient),
- [queryClient],
- )
const query = useQuery<ForumSidebarQueryData>({
queryKey: communityKeys.forumSidebarThreads(serverId),
enabled: !!serverId && enabled,
staleTime: Infinity,
queryFn: async ({ signal }) => {
const token = captureCommunityLiveSnapshotToken(queryClient)
- const confirmation = unreadProjection.beginAccessConfirmation()
const normalized = await fetchForumSidebar(queryClient, serverId, retainId, signal, token)
if (signal.aborted) throw new DOMException("Aborted", "AbortError")
const result = publishNormalizedForumSidebar(queryClient, serverId, normalized, retainId, signal, token)
- unreadProjection.confirmAccessScopes(
- [
- ...normalized.base.threads,
- ...(normalized.retainedDisposition === "eligible" && normalized.retained
- ? [normalized.retained]
- : []),
- ].map((thread) => ({ kind: "channel" as const, channelId: thread.id })),
- confirmation,
- )
+
return result.data
},
})
@@ -570,30 +529,7 @@ export function useForumSidebarThreads(
if (!enabled || !(sidebar.needsRead || query.data !== undefined && !result && sidebar.status === "pending") || query.isFetching || query.isError) return
void invalidateForumSidebarBaseExact(queryClient, serverId)
}, [enabled, sidebar.needsRead, sidebar.status, result, query.data, query.isFetching, query.isError, queryClient, serverId])
- const attentionScopes = useAttentionScopes()
- const projection = useMemo(() => {
- const structuralProjection = canonical ?? { threads: [], parentUnread: {} }
- const relevant = attentionScopes.filter((scope) => scope.serverId === serverId)
- const unreadByScope = new Map(relevant.map((scope) => [
- scope.scopeId,
- scope.ordinaryUnread || scope.attentionCount > 0,
- ]))
- const parentUnread: Record<string, boolean> = {}
- for (const scope of relevant) {
- if (scope.parentChannelId && unreadByScope.get(scope.scopeId)) {
- parentUnread[scope.parentChannelId] = true
- } else if (!scope.parentChannelId) {
- parentUnread[scope.channelId] = unreadByScope.get(scope.scopeId) ?? false
- }
- }
- return {
- threads: structuralProjection.threads.map((thread) => ({
- ...thread,
- unread: unreadByScope.get(thread.id) ?? false,
- })),
- parentUnread,
- }
- }, [attentionScopes, serverId, canonical])
+ const projection = canonical ?? { threads: [], parentUnread: {} }
useEffect(() => {
if (serverNowMs === null) return
diff --git a/src/web/src/hooks/community/use-inbox.ts b/src/web/src/hooks/community/use-inbox.ts
index edc443aa8..dede0cee4 100644
--- a/src/web/src/hooks/community/use-inbox.ts
+++ b/src/web/src/hooks/community/use-inbox.ts
@@ -1,5 +1,4 @@
"use client"
-import { useSelector } from "@tanstack/react-store"
import { useMemo } from "react"
import {
keepPreviousData,
@@ -22,9 +21,12 @@ Mention,
UnreadDm,
UnreadServer,
} from "@/lib/community/models/inbox"
-import { accountUnreadAllowsAccess,getActiveAccountUnreadProjection } from "./account-unread-projection"
+import { communityScopeAllowsAccess } from "@/stores/community/ws-store"
+import { communityServerRetirementId, communityServerRetirementKey } from "@/lib/community-db/message-access-scope"
+import { useCommunityWsStore } from "@/stores/community/ws"
import {
materializeCanonicalMessage,
+useOptionalCommunityDbRegistry,
useCanonicalChannelsById,
useCanonicalMessagesById,
useCanonicalProfilesByUserId,
@@ -305,10 +307,6 @@ export function useInboxMarked(enabled: boolean): UseQueryResult<MarkedWindowRes
canonicalPending: boolean
} {
const queryClient = useQueryClient()
- const unreadProjection = useMemo(
- () => getActiveAccountUnreadProjection(queryClient),
- [queryClient],
- )
const query = useQuery({
queryKey: communityKeys.inboxMarked(),
queryFn: inboxMarkedQueryFn(queryClient),
@@ -318,16 +316,18 @@ export function useInboxMarked(enabled: boolean): UseQueryResult<MarkedWindowRes
const messageIds = useMemo(() => query.data?.marked.map((row) => row.m.id) ?? [], [query.data?.marked])
const canonicalMessages = useCanonicalMessagesById(messageIds)
const pendingMarks = useMutationState({ filters: { mutationKey: ["community", "mark-command"], status: "pending" }, select: (mutation) => ({ messageId: (mutation.state.variables as { messageId: string }).messageId, marked: mutation.options.mutationKey?.[2] === true }) })
- const markedAccess = useSelector(unreadProjection.state, (state) => (query.data?.marked ?? []).map((row) => accountUnreadAllowsAccess(state, row)), { compare: (left, right) => left.length === right.length && left.every((value, index) => value === right[index]) })
+ const registry = useOptionalCommunityDbRegistry()
+ const retiringServers = useMutationState({ filters: { mutationKey: communityServerRetirementKey, status: "pending" }, select: mutation => communityServerRetirementId(mutation, registry) })
+ const markedAccess = useCommunityWsStore((state) => state)
const marked = useMemo(() => {
const source = query.data?.marked ?? (EMPTY_MARKED as Marked[])
- return source.flatMap((marked, index) => {
+ return source.flatMap((marked) => {
if (pendingMarks.filter((command) => command.messageId === marked.m.id).at(-1)?.marked === false) return []
- if (!markedAccess[index]) return []
+ if (!communityScopeAllowsAccess(markedAccess, marked) || marked.serverId && retiringServers.includes(marked.serverId)) return []
const message = materializeCanonicalMessage(marked.m, canonicalMessages)
return message ? [{ ...marked, m: message }] : []
})
- }, [canonicalMessages, query.data?.marked, markedAccess, pendingMarks])
+ }, [canonicalMessages, query.data?.marked, markedAccess, pendingMarks, retiringServers])
return { ...query, marked, canonicalPending: enabled && !!query.data && !query.isError && canonicalMessages === undefined }
}
diff --git a/src/web/src/hooks/community/use-message-unread-count.dom.test.ts b/src/web/src/hooks/community/use-message-unread-count.dom.test.ts
new file mode 100644
index 000000000..2be175ad5
--- /dev/null
+++ b/src/web/src/hooks/community/use-message-unread-count.dom.test.ts
@@ -0,0 +1,28 @@
+import { createElement, type PropsWithChildren } from "react"
+import { expect, it } from "vitest"
+import { act, renderHook, waitFor } from "@/test/react-dom-harness"
+import { CommunityTestProvider } from "@/test/community-owner-fixture"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { ingestMessages, publishCommunityConversationReadState, captureCommunityLiveSnapshotToken } from "@/lib/community-db/sync"
+import { confirmReadSurface, registerReadSurface, releaseReadSurface, submitReadIntent } from "./read-coordinator"
+import { useMessageUnreadCount } from "./use-message-unread-count"
+
+it("projects admitted local progress without changing the frozen entry boundary or confirming the read", async () => {
+ const owner = await createCommunityQueryOwner()
+ const messages = [2, 5, 9].map(seq => ({ id: `m${seq}`, channelId: "c1", seq, authorId: "peer", type: "chat" as const, content: "Message", createdAt: `2026-10-27T00:00:0${seq}.000Z` }))
+ ingestMessages(owner.registry, "c1", messages)
+ const entry = Object.freeze({ lastReadSeq: 2 })
+ const wrapper = ({ children }: PropsWithChildren) => createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, retainOwner: true }, children)
+ const rendered = renderHook(() => useMessageUnreadCount({ channelId: "c1", viewerUserId: "viewer", messages, entryReadSeq: entry.lastReadSeq, latestSeq: 9, historyStartKnown: false, hasMoreNewer: false, ready: true }), { wrapper })
+ await waitFor(() => expect(rendered.result.current).toBe(2))
+ const lease = registerReadSurface(owner.client, "viewer", { kind: "timeline", channelId: "c1" }, 2)
+ act(() => { expect(submitReadIntent(lease, { kind: "timeline", channelId: "c1", messageId: "m5", seq: 5 })).toBe(true) })
+ await waitFor(() => expect(rendered.result.current).toBe(1))
+ expect(owner.registry.collections.readStates.get("c1")).toBeUndefined()
+ expect(entry.lastReadSeq).toBe(2)
+ await act(async () => { publishCommunityConversationReadState(owner.client, { channelId: "c1", lastReadMessageId: "m9", lastReadAt: messages[2]!.createdAt, lastReadSeq: 9 }, 1, { token: captureCommunityLiveSnapshotToken(owner.client) }) })
+ await waitFor(() => expect(rendered.result.current).toBe(0))
+ confirmReadSurface(lease, 9)
+ releaseReadSurface(lease)
+ rendered.unmount()
+})
diff --git a/src/web/src/hooks/community/use-message-unread-count.ts b/src/web/src/hooks/community/use-message-unread-count.ts
new file mode 100644
index 000000000..f417d4086
--- /dev/null
+++ b/src/web/src/hooks/community/use-message-unread-count.ts
@@ -0,0 +1,28 @@
+"use client"
+
+import { useMemo } from "react"
+import { useQueryClient } from "@tanstack/react-query"
+import { useSelector } from "@tanstack/react-store"
+import { useChannelReadStateProjection } from "@/lib/community-db/projections"
+import { resolveUnreadMessageCount } from "@/lib/community/message-read-projection"
+import { getLocalReadingPosition, getReadCoordinator } from "./read-coordinator"
+
+export function useMessageUnreadCount(input: {
+ channelId: string | null
+ viewerUserId: string
+ messages: readonly { seq?: number }[]
+ entryReadSeq: number | undefined
+ latestSeq: number
+ historyStartKnown: boolean
+ hasMoreNewer: boolean
+ ready: boolean
+}) {
+ const client = useQueryClient()
+ const coordinator = useMemo(() => getReadCoordinator(client, input.viewerUserId), [client, input.viewerUserId])
+ const localSeq = useSelector(coordinator.state, () => input.channelId ? getLocalReadingPosition(client, input.channelId)?.seq ?? 0 : 0)
+ const { readState, hasSnapshot } = useChannelReadStateProjection(input.channelId)
+ const confirmedSeq = readState?.lastReadSeq ?? (hasSnapshot ? 0 : input.entryReadSeq)
+ return useMemo(() => !input.ready || confirmedSeq === undefined ? undefined : resolveUnreadMessageCount({
+ messages: input.messages, latestSeq: input.latestSeq, historyStartKnown: input.historyStartKnown, hasMoreNewer: input.hasMoreNewer, lastReadSeq: Math.max(confirmedSeq, localSeq),
+ }), [input.ready, input.messages, input.latestSeq, input.historyStartKnown, input.hasMoreNewer, confirmedSeq, localSeq])
+}
diff --git a/src/web/src/hooks/community/use-message.dom.test.ts b/src/web/src/hooks/community/use-message.dom.test.ts
index 6546f5613..a54f15796 100644
--- a/src/web/src/hooks/community/use-message.dom.test.ts
+++ b/src/web/src/hooks/community/use-message.dom.test.ts
@@ -7,7 +7,6 @@ import { CommunityDbProvider } from "@/lib/community-db/projections"
import { ingestMessages } from "@/lib/community-db/sync"
import { communityKeys } from "@/lib/query-keys"
import { useMessage } from "./use-message"
-import { getActiveAccountUnreadProjection } from "./account-unread-projection"
import { takeMessageIdsForAccessScope } from "@/lib/community-db/message-access-scope"
const apiFetchMock = vi.fn(() => new Promise(() => {}))
@@ -64,23 +63,29 @@ describe("useMessage cache-first placeholder", () => {
expect(rendered.result.current.message).toBeNull()
})
- it("keeps the access index empty while fenced and restores it after rollback or grant", async () => {
+ it.each(["current", "retired"] as const)("observes a %s native server retirement without copying access state", async lifetime => {
+ ingestMessages(registry, scope.channelId, [message])
+ client.setQueryData(communityKeys.message(message.id), message.id)
+ const rendered = renderHook(() => useMessage(message.id, scope), { wrapper: Owner })
+ await waitFor(() => expect(rendered.result.current.message?.id).toBe(message.id))
+ let reject!: (error: Error) => void
+ const held = new Promise<void>((_resolve, fail) => { reject = fail })
+ const mutation = client.getMutationCache().build<void, Error, { serverId: string; original: { registry: unknown } }, unknown>(client, { mutationKey: ["community", "server-retirement", "leave"], mutationFn: async () => held })
+ let pending!: Promise<unknown>
+ await act(async () => { pending = mutation.execute({ serverId: scope.serverId, original: { registry: lifetime === "current" ? registry : {} } }).catch(error => error) })
+ await waitFor(() => expect(rendered.result.current.message?.id).toBe(lifetime === "current" ? undefined : message.id))
+ await act(async () => { reject(new Error("denied")); await pending })
+ await waitFor(() => expect(rendered.result.current.message?.id).toBe(message.id))
+ })
+
+ it("keeps the access index empty after revocation and restores it after a fresh grant", async () => {
client.setQueryData(communityKeys.message(message.id), message.id)
const rendered = renderHook(() => useMessage(message.id, scope), { wrapper: Owner })
await waitFor(() => expect(takeMessageIdsForAccessScope(client, new Set([scope.channelId]), null)).toEqual([message.id]))
- const projection = getActiveAccountUnreadProjection(client)
- let retirement!: ReturnType<typeof projection.beginScopeRetirement>
- act(() => { retirement = projection.beginScopeRetirement({ kind: "channel", channelId: scope.channelId }) })
+ act(() => registry.runtime.ws.actions.revokeChannelAccess(scope.serverId, scope.channelId))
expect(rendered.result.current.message).toBeNull()
await waitFor(() => expect(takeMessageIdsForAccessScope(client, new Set([scope.channelId]), null)).toEqual([]))
- act(() => projection.rollbackScopeRetirement(retirement))
- await waitFor(() => expect(takeMessageIdsForAccessScope(client, new Set([scope.channelId]), null)).toEqual([message.id]))
- act(() => projection.retireAccessScope({ kind: "channel", channelId: scope.channelId }))
- expect(takeMessageIdsForAccessScope(client, new Set([scope.channelId]), null)).toEqual([])
- act(() => {
- projection.grantAccessScope({ kind: "channel", channelId: scope.channelId })
- projection.confirmAccessScopes([{ kind: "channel", channelId: scope.channelId }], projection.beginAccessConfirmation())
- })
+ act(() => registry.runtime.ws.actions.rememberChannelAccess(scope.serverId, scope.channelId))
await waitFor(() => expect(takeMessageIdsForAccessScope(client, new Set([scope.channelId]), null)).toEqual([message.id]))
expect(rendered.result.current.message).toBeNull()
})
diff --git a/src/web/src/hooks/community/use-message.test.ts b/src/web/src/hooks/community/use-message.test.ts
index 6f061c4d7..dbfdba0f8 100644
--- a/src/web/src/hooks/community/use-message.test.ts
+++ b/src/web/src/hooks/community/use-message.test.ts
@@ -4,7 +4,6 @@ import { communityKeys } from "@/lib/query-keys"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
import { ingestMessages, retireCommunityChannelReading } from "@/lib/community-db/sync"
import { findCachedMessage, messageQueryFn, prefetchCommunityMessage, prefetchCommunityLatestMessage } from "./use-message"
-import { getActiveAccountUnreadProjection } from "./account-unread-projection"
const apiFetchMock = vi.fn()
vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => apiFetchMock(...args) }))
@@ -60,7 +59,7 @@ describe("background canonical message hydration", () => {
it("does not fetch for retired access or an inactive owner", async () => {
const owner = await createCommunityQueryOwner()
- getActiveAccountUnreadProjection(owner.client).retireAccessScope({ kind: "channel", channelId: payload.channelId })
+ owner.runtime.ws.actions.revokeChannelAccess("server-1", payload.channelId!)
await prefetchCommunityMessage(owner.client, payload.id, { channelId: payload.channelId })
await prefetchCommunityLatestMessage(owner.client, payload.channelId)
owner.runtime.lifecycle.setState((state) => ({ active: false, generation: state.generation + 1 }))
diff --git a/src/web/src/hooks/community/use-message.ts b/src/web/src/hooks/community/use-message.ts
index 75597ace6..8e14ebbbc 100644
--- a/src/web/src/hooks/community/use-message.ts
+++ b/src/web/src/hooks/community/use-message.ts
@@ -1,10 +1,10 @@
"use client"
-import { useSelector } from "@tanstack/react-store"
import { useEffect, useMemo } from "react"
import {
useQuery,
+ useMutationState,
useQueryClient,
queryOptions,
type QueryClient,
@@ -22,10 +22,13 @@ import {
useOptionalCommunityDbRegistry,
} from "@/lib/community-db/projections"
import {
+ communityServerRetirementId,
+ communityServerRetirementKey,
rememberMessageAccessScope,
type MessageAccessScope,
} from "@/lib/community-db/message-access-scope"
-import { accountUnreadAllowsAccess, getActiveAccountUnreadProjection } from "./account-unread-projection"
+import { communityScopeAllowsAccess } from "@/stores/community/ws-store"
+import { useCommunityWsStore } from "@/stores/community/ws"
import { conversationReadRetryPolicy, withConversationReadDeadline } from "@/lib/community/conversation-read"
import {
captureCommunityLiveSnapshotToken,
@@ -85,7 +88,8 @@ function messageQueryOptions(queryClient: QueryClient, messageId: string, channe
export async function prefetchCommunityMessage(queryClient: QueryClient, messageId: string, scope: MessageAccessScope) {
const registry = getCommunityDbRegistry(queryClient)
if (!registry?.runtime.lifecycle.get().active
- || !accountUnreadAllowsAccess(getActiveAccountUnreadProjection(queryClient).state.get(), scope)) return
+ || !communityScopeAllowsAccess(registry.runtime.ws.get(), scope)
+ || queryClient.getMutationCache().findAll({ mutationKey: communityServerRetirementKey, status: "pending" }).some(mutation => communityServerRetirementId(mutation, registry) === scope.serverId && scope.serverId != null)) return
rememberMessageAccessScope(queryClient, messageId, scope)
if (registry.collections.messages.get(messageId)?.resourceComplete) return
await queryClient.query({ ...messageQueryOptions(queryClient, messageId, scope.channelId), staleTime: 0, select: undefined })
@@ -96,7 +100,8 @@ export async function prefetchCommunityLatestMessage(queryClient: QueryClient, c
const registry = token.registry
if (!registry?.runtime.lifecycle.get().active) return
const scope = { channelId, serverId: registry.collections.channels.get(channelId)?.serverId }
- if (!accountUnreadAllowsAccess(getActiveAccountUnreadProjection(queryClient).state.get(), scope)) return
+ if (!communityScopeAllowsAccess(registry.runtime.ws.get(), scope)
+ || queryClient.getMutationCache().findAll({ mutationKey: communityServerRetirementKey, status: "pending" }).some(mutation => communityServerRetirementId(mutation, registry) === scope.serverId && scope.serverId != null)) return
const queryKey = communityKeys.channelLatestMessage(channelId)
await queryClient.cancelQueries({ queryKey, exact: true })
assertCommunityLiveSnapshotTokenCurrent(queryClient, token, undefined)
@@ -144,11 +149,9 @@ export function useMessage(
const selectedIds = useMemo(() => messageId ? [messageId] : [], [messageId])
const canonicalMessages = useCanonicalMessagesById(selectedIds)
const queryClient = useQueryClient()
- const accessProjection = useMemo(
- () => getActiveAccountUnreadProjection(queryClient),
- [queryClient],
- )
- const accessAllowed = useSelector(accessProjection.state, (state) => !accessScope || accountUnreadAllowsAccess(state, accessScope))
+ const retiringServers = useMutationState({ filters: { mutationKey: communityServerRetirementKey, status: "pending" }, select: mutation => communityServerRetirementId(mutation, registry) })
+ const accessAllowed = useCommunityWsStore((state) => !accessScope || communityScopeAllowsAccess(state, accessScope))
+ && !(accessScope?.serverId && retiringServers.includes(accessScope.serverId))
const enabled = !!messageId && accessAllowed
useEffect(() => {
if (!messageId || !accessScope || !accessAllowed) return
diff --git a/src/web/src/hooks/community/use-notification-settings.dom.test.ts b/src/web/src/hooks/community/use-notification-settings.dom.test.ts
index 355741b00..243db6986 100644
--- a/src/web/src/hooks/community/use-notification-settings.dom.test.ts
+++ b/src/web/src/hooks/community/use-notification-settings.dom.test.ts
@@ -66,18 +66,12 @@ describe("useNotificationSettings / notificationSettingsQueryFn", () => {
expect(queryClient.getQueryData(key)).toBeDefined()
})
- it("projects fetched settings into the active account unread owner", async () => {
+ it("publishes fetched settings into the canonical notification collection", async () => {
apiFetchMock.mockResolvedValue([
{ serverId: "srv_1", channelId: null, level: "nothing" },
])
const { useNotificationSettings } = await import("./use-notification-settings")
- const {
- disposeAccountUnreadProjection,
- getAccountUnreadProjection,
- } = await import("./account-unread-projection")
const queryClient = (await createCommunityQueryOwner("viewer_1")).client
- const projection = getAccountUnreadProjection(queryClient, "viewer_1")
- projection.recordArrival({ channelId: "channel_1", serverId: "srv_1", seq: 1 })
const wrapper = ({ children }: PropsWithChildren) => createElement(
QueryClientProvider,
{ client: queryClient, userId: "viewer_1" },
@@ -87,19 +81,13 @@ describe("useNotificationSettings / notificationSettingsQueryFn", () => {
await waitFor(() => expect(rendered.result.current.isSuccess).toBe(true))
expect(rendered.result.current.server).toEqual({ srv_1: "Nothing" })
- expect(projection.projectUnread("servers", "channel_1", false)).toBe(false)
rendered.unmount()
- disposeAccountUnreadProjection(queryClient)
})
it("projects warm canonical policy while the transport request is stalled", async () => {
apiFetchMock.mockReturnValue(new Promise(() => {}))
const { useNotificationSettings } = await import("./use-notification-settings")
- const {
- disposeAccountUnreadProjection,
- getAccountUnreadProjection,
- } = await import("./account-unread-projection")
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
const registry = createCommunityDbRegistry(queryClient, "viewer_1")
const disposeRegistry = registry.cleanup.bind(registry)
@@ -120,8 +108,6 @@ describe("useNotificationSettings / notificationSettingsQueryFn", () => {
signal: undefined,
},
})
- const projection = getAccountUnreadProjection(queryClient, "viewer_1")
- projection.recordArrival({ channelId: "channel_1", serverId: "srv_1", seq: 1 })
const wrapper = ({ children }: PropsWithChildren) => createElement(
QueryClientProvider,
{ client: queryClient, registry, userId: "viewer_1" },
@@ -130,14 +116,10 @@ describe("useNotificationSettings / notificationSettingsQueryFn", () => {
const rendered = renderHook(() => useNotificationSettings(), { wrapper })
await waitFor(() => expect(rendered.result.current.server).toEqual({ srv_1: "Nothing" }))
- await waitFor(() => expect(
- projection.projectUnread("servers", "channel_1", false),
- ).toBe(false))
expect(rendered.result.current.fetchStatus).toBe("fetching")
rendered.unmount()
unregister()
await disposeRegistry()
- disposeAccountUnreadProjection(queryClient)
})
})
diff --git a/src/web/src/hooks/community/use-notification-settings.ts b/src/web/src/hooks/community/use-notification-settings.ts
index 1f094f58b..7b84a7d6e 100644
--- a/src/web/src/hooks/community/use-notification-settings.ts
+++ b/src/web/src/hooks/community/use-notification-settings.ts
@@ -16,15 +16,11 @@ import {
import { notifLevelDisplay } from "@alook/shared"
import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
-import { useCallback, useEffect, useMemo } from "react"
+import { useCallback } from "react"
import { useCommunityMutationOrigin } from "./community-origin"
import { useCommunityViewSource } from "./use-community-view-source"
import { notificationSettingKey } from "@/lib/community-db/schema"
-import {
- getActiveAccountUnreadProjection,
- type AccountUnreadProjection,
-} from "./account-unread-projection"
import {
useNotificationSettingsProjection,
} from "@/lib/community-db/projections"
@@ -100,16 +96,6 @@ export const notificationSettingsQueryFn = async (
return { ids: rows.filter((row) => Boolean(row.serverId) !== Boolean(row.channelId)).map((row) => notificationSettingKey(row)) }
}
-function projectNotificationSettings(
- projection: AccountUnreadProjection,
- settings: Pick<NotificationSettings, "server" | "channel"> | undefined,
-) {
- projection.setNotificationPolicy({
- server: settings?.server ?? {},
- channel: settings?.channel ?? {},
- })
-}
-
export async function reconcileNotificationSettings(queryClient: QueryClient) {
const token = captureCommunityLiveSnapshotToken(queryClient)
assertCommunityLiveSnapshotTokenCurrent(queryClient, token, undefined)
@@ -125,7 +111,6 @@ export async function reconcileNotificationSettings(queryClient: QueryClient) {
assertCommunityLiveSnapshotTokenCurrent(queryClient, token, undefined)
const settings: NotificationSettings = { raw: [...token.registry!.collections.notificationSettings.values()], server: {}, channel: {} }
for (const row of settings.raw) { if (row.channelId) settings.channel[row.channelId] = displayNotifLevel(row.level); else if (row.serverId) settings.server[row.serverId] = displayNotifLevel(row.level) }
- projectNotificationSettings(getActiveAccountUnreadProjection(queryClient), settings)
return settings
}
@@ -134,19 +119,10 @@ export function useNotificationSettings(): UseQueryResult<NotificationSettings>
channel: Record<string, string>
} {
const dbSettings = useNotificationSettingsProjection()
- const queryClient = useQueryClient()
- const projection = useMemo(
- () => getActiveAccountUnreadProjection(queryClient),
- [queryClient],
- )
const query = useQuery({
queryKey: communityKeys.notificationSettings(),
queryFn: notificationSettingsQueryFn,
})
- const projectedSettings = dbSettings
- useEffect(() => {
- if (projectedSettings) projectNotificationSettings(projection, projectedSettings)
- }, [projectedSettings, projection])
return {
...query,
data: dbSettings,
diff --git a/src/web/src/hooks/community/use-read-observer.dom.test.ts b/src/web/src/hooks/community/use-read-observer.dom.test.ts
index b36a99ac6..63eacc878 100644
--- a/src/web/src/hooks/community/use-read-observer.dom.test.ts
+++ b/src/web/src/hooks/community/use-read-observer.dom.test.ts
@@ -23,9 +23,6 @@ const reservation = vi.hoisted(() => ({
promote: vi.fn(),
negative: vi.fn(() => true),
}))
-const projection = vi.hoisted(() => ({
- recordOptimisticRead: vi.fn(),
-}))
const hookState = vi.hoisted(() => ({
candidate: null as null | {
channelId: string
@@ -57,11 +54,6 @@ vi.mock("./inbox-read-reservation", async () => ({
takeInboxReadReservationNegative: (...args: unknown[]) => reservation.negative(...args),
}))
-vi.mock("./account-unread-projection", async () => ({
- ...await vi.importActual<typeof import("./account-unread-projection")>("./account-unread-projection"),
- getAccountUnreadProjection: () => projection,
-}))
-
import { useTimelineReadObserver } from "./use-read-observer"
import { useChannelWatermark } from "./use-channel-watermark"
import { useDmWatermark } from "./use-dm-watermark"
@@ -302,7 +294,6 @@ describe("useTimelineReadObserver", () => {
expect(coordinator.submit).toHaveBeenCalledExactlyOnceWith({ lease: "timeline" }, {
kind: "timeline", channelId: "channel-1", messageId: "message-4", seq: 4,
})
- expect(projection.recordOptimisticRead).toHaveBeenCalledWith("channel-1", 4, 1)
} finally { clock.mockRestore() }
})
@@ -361,7 +352,6 @@ describe("useTimelineReadObserver", () => {
messageId: "message-4",
seq: 4,
})
- expect(projection.recordOptimisticRead).toHaveBeenCalledWith("channel-1", 4, 1)
})
it("does not clear projection or promote an Inbox lease when the coordinator rejects intent", () => {
@@ -371,7 +361,6 @@ describe("useTimelineReadObserver", () => {
trigger(observers[0]!, row)
- expect(projection.recordOptimisticRead).not.toHaveBeenCalled()
expect(reservation.promote).not.toHaveBeenCalled()
})
@@ -454,7 +443,6 @@ describe("useTimelineReadObserver", () => {
trigger(observers[0]!, row)
for (const listener of pageShowListeners) listener()
expect(coordinator.submit).not.toHaveBeenCalled()
- expect(projection.recordOptimisticRead).not.toHaveBeenCalled()
expect(coordinator.resume).not.toHaveBeenCalled()
parent.removeAttribute("inert")
act(() => mutationCallback!([{
@@ -487,7 +475,6 @@ describe("useTimelineReadObserver", () => {
for (const listener of pageShowListeners) listener()
expect(coordinator.submit).not.toHaveBeenCalled()
- expect(projection.recordOptimisticRead).not.toHaveBeenCalled()
expect(reservation.promote).not.toHaveBeenCalled()
expect(reservation.negative).not.toHaveBeenCalled()
expect(coordinator.resume).not.toHaveBeenCalled()
@@ -505,7 +492,6 @@ describe("useTimelineReadObserver", () => {
queueEntry(record, row)
const stale = record.queued[0]!
expect(coordinator.submit).not.toHaveBeenCalled()
- expect(projection.recordOptimisticRead).not.toHaveBeenCalled()
expect(reservation.promote).not.toHaveBeenCalled()
boundary.setAttribute("data-read-position-ready", "true")
act(() => mutationCallback!([presentationAttributeRecord(boundary, "data-read-position-ready")], {} as MutationObserver))
@@ -514,7 +500,6 @@ describe("useTimelineReadObserver", () => {
expect(coordinator.submit).not.toHaveBeenCalled()
trigger(observers.at(-1)!, row)
expect(coordinator.submit).toHaveBeenCalledOnce()
- expect(projection.recordOptimisticRead).toHaveBeenCalledOnce()
expect(reservation.promote).toHaveBeenCalledOnce()
})
diff --git a/src/web/src/hooks/community/use-read-observer.ts b/src/web/src/hooks/community/use-read-observer.ts
index 764495747..01ced73c3 100644
--- a/src/web/src/hooks/community/use-read-observer.ts
+++ b/src/web/src/hooks/community/use-read-observer.ts
@@ -21,7 +21,6 @@ import {
type InboxReadCandidate,
type InboxReadReservationLease,
} from "./inbox-read-reservation"
-import { getAccountUnreadProjection } from "./account-unread-projection"
const READ_VISIBILITY_THRESHOLD = 0.2
const MESSAGE_LIST_CONTENT_SELECTOR = "[data-message-list-content]"
@@ -228,10 +227,6 @@ export function useTimelineReadObserver({
messageId: message.id,
seq: message.seq,
})
- if (generation !== null) {
- getAccountUnreadProjection(queryClient, currentUser.id)
- .recordOptimisticRead(channelId, message.seq, generation)
- }
if (generation !== null && correlated) {
promoteInboxReadReservation(reservationLease, generation)
}
diff --git a/src/web/src/hooks/community/use-scroll-anchor.repin.dom.test.ts b/src/web/src/hooks/community/use-scroll-anchor.repin.dom.test.ts
index 43411ede2..32eac1f94 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.repin.dom.test.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.repin.dom.test.ts
@@ -17,6 +17,25 @@ function retiredInitialReader(onInitialPositionSettled?: () => void) {
}
describe("locked native adapter and existing message scroll owner", () => {
+ it("hands a pending native tail command to real upward intent before exact one-pixel positioning", () => {
+ const h = mount()
+ const native = scrollFixture.latest.virtualizer
+ const max = h.root.scrollHeight - h.root.clientHeight
+ const cancel = vi.spyOn(native, "cancelScroll")
+ act(() => native.scrollToEnd())
+ fireEvent.wheel(h.root, { deltaY: -20 })
+ expect(cancel).toHaveBeenCalledOnce()
+ act(() => h.root.scrollTo({ top: max - 1 }))
+ runFrames(3)
+ expect(h.root.scrollTop).toBe(max - 1)
+ h.stage({ items: Array.from({ length: 14 }, (_, index) => message(`m${index}`)) })
+ resize()
+ expect(h.root.scrollTop).toBe(max - 1)
+ h.stage({ items: Array.from({ length: 15 }, (_, index) => message(`m${index}`)) })
+ resize()
+ expect(h.root.scrollTop).toBe(h.root.scrollHeight - h.root.clientHeight)
+ })
+
it("sends the first initial end only against the measured React sizer and accepts a long final message", () => {
scrollFixture.bodyHeights.set("m0", 1200)
scrollFixture.bodyHeights.set("m13", 1000)
diff --git a/src/web/src/hooks/community/use-servers.dom.test.ts b/src/web/src/hooks/community/use-servers.dom.test.ts
index 4ae9c37da..7d3753686 100644
--- a/src/web/src/hooks/community/use-servers.dom.test.ts
+++ b/src/web/src/hooks/community/use-servers.dom.test.ts
@@ -8,7 +8,6 @@ import { captureCommunityLiveSnapshotToken, publishAccountAttentionSnapshot, pub
import { communityKeys } from "@/lib/query-keys"
import { ApiError } from "@/lib/errors"
import { forumConversationEntryFixture, seedConversationEntry } from "@/test/conversation-entry-fixtures"
-import { AccountUnreadProjection, getActiveAccountUnreadProjection } from "./account-unread-projection"
import { serversQueryFn, serversProjectedQueryFn, serverProjectedQueryFn, useServers, useServer, useViewerServerRole, type ServersResponse, type ServerDetail } from "./use-servers"
const apiFetchMock = vi.fn()
@@ -47,8 +46,8 @@ function attention(channelId: string, count = 1, parentChannelId: string | null
proof: { token: captureCommunityLiveSnapshotToken(client), signal: undefined },
})
}
-function fetchList(projection = getActiveAccountUnreadProjection(client)) {
- return client.query({ queryKey: communityKeys.servers(), queryFn: serversProjectedQueryFn(projection, client), staleTime: 0 })
+function fetchList() {
+ return client.query({ queryKey: communityKeys.servers(), queryFn: serversProjectedQueryFn(client), staleTime: 0 })
}
function fetchDetail() {
return client.query({ queryKey: communityKeys.server(identity.id), queryFn: ({ signal }) => serverProjectedQueryFn(client, identity.id, signal)(), staleTime: 0 })
@@ -73,14 +72,14 @@ describe("useServers / serversQueryFn", () => {
apiFetchMock.mockResolvedValueOnce({ servers: [{ ...identity, official: true, role: "owner", mentions: 3, unread: true }, { ...identity, id: "srv_2", name: "Beta", discriminator: "12345", role: "member", description: undefined }] })
const data = await rawList()
expect(apiFetchMock).toHaveBeenCalledWith("/api/community/servers", expect.objectContaining({ signal: expect.any(AbortSignal), assertActive: expect.any(Function) }))
- expect(data.servers[0]).toMatchObject({ ...identity, official: true, initial: "A", isOwner: true, mentions: 3, active: false, unread: true })
+ expect(data.servers[0]).toMatchObject({ ...identity, official: true, initial: "A", isOwner: true, mentions: 0, active: false, unread: false })
expect(data.servers[1]).toMatchObject({ official: false, mentions: 0, isOwner: false, unread: false, description: "" })
expect(client.getQueryData(["server-transform"])).toEqual(["srv_1", "srv_2"])
})
it("preserves mentions when provided; defaults to 0 when omitted", async () => {
apiFetchMock.mockResolvedValueOnce({ servers: [{ ...identity, mentions: 7 }, { ...identity, id: "srv_2" }] })
- expect((await rawList()).servers.map((server) => server.mentions)).toEqual([7, 0])
+ expect((await rawList()).servers.map((server) => server.mentions)).toEqual([0, 0])
})
it("passes TanStack's abort signal to the canonical request", async () => {
@@ -97,33 +96,15 @@ describe("useServers / serversQueryFn", () => {
expect(registry.collections.servers.get(identity.id)).toMatchObject(identity)
})
- it("uses a complete server list as authoritative unread negative evidence", async () => {
- apiFetchMock.mockResolvedValueOnce({ servers: [] })
- const projection = getActiveAccountUnreadProjection(client)
- projection.setNotificationPolicy({})
- projection.recordArrival({ channelId: "c1", serverId: "s1", seq: 2 })
- await fetchList(projection)
- expect(projection.projectUnread("servers", "c1", false)).toBe(false)
- })
-
- it("cancels server-list snapshot coverage when the transport fails", async () => {
- apiFetchMock.mockRejectedValueOnce(new Error("offline"))
- const projection = getActiveAccountUnreadProjection(client)
- await expect(fetchList(projection)).rejects.toThrow("offline")
- expect(projection.inspectForTests().pendingSnapshots).toBe(0)
- })
-
it("rejects a server-list response captured for an earlier account epoch", async () => {
let release!: (value: { servers: typeof identity[] }) => void
apiFetchMock.mockReturnValueOnce(new Promise((resolve) => { release = resolve }))
- const projection = getActiveAccountUnreadProjection(client)
- const pending = fetchList(projection)
+ const pending = fetchList()
const result = pending.catch((error) => error)
await waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())
registry.runtime.ws.actions.activateProfileAccount("replacement")
release({ servers: [identity] })
expect(await result).toMatchObject({ name: "AbortError" })
- expect(projection.inspectForTests().pendingSnapshots).toBe(0)
expect(registry.collections.servers.size).toBe(0)
})
@@ -179,21 +160,8 @@ describe("useServers / serversQueryFn", () => {
expect(rendered.result.current.isLiveAuthoritative).toBe(false)
})
- it("correlates cold rail unread sources with their attention facets", async () => {
- apiFetchMock.mockResolvedValueOnce({ servers: [{ ...identity, unreadSources: [{ channelId: "attention", lastUnreadSeq: 10 }, { channelId: "ordinary", lastUnreadSeq: 3 }], mentionSources: [{ channelId: "attention", count: 1, lastSeq: 5 }, { channelId: "ignored", count: 0, lastSeq: 99 }] }] })
- const projection = new AccountUnreadProjection("viewer")
- projection.setNotificationPolicy({ server: { srv_1: "mentions" } })
- await fetchList(projection)
- expect(projection.projectUnread("servers", "attention", false)).toBe(true)
- expect(projection.projectUnread("servers", "ordinary", false)).toBe(false)
- expect(projection.projectUnread("servers", "ignored", false)).toBe(false)
- projection.recordRead("attention", 5)
- expect(projection.projectUnread("servers", "attention", false)).toBe(false)
- })
-
it("does not let the legacy unread ledger override canonical attention", async () => {
seedList([canonical(), { ...canonical("s2"), unread: true, mentions: 2 }, { ...canonical("s3"), unread: true }])
- getActiveAccountUnreadProjection(client).recordArrival({ channelId: "c1", serverId: identity.id, seq: 1 })
const rendered = renderHook(() => useServers(), { wrapper: Owner })
await waitFor(() => expect(rendered.result.current.servers).toHaveLength(3))
expect(rendered.result.current.servers.map(({ unread, mentions }) => ({ unread, mentions }))).toEqual(Array.from({ length: 3 }, () => ({ unread: false, mentions: 0 })))
@@ -228,7 +196,7 @@ describe("useServers / serversQueryFn", () => {
await waitFor(() => expect(rendered.result.current.servers[0]?.unread).toBe(false))
act(() => publish({ kind: "servers", data: { servers: [{ ...canonical(), unread: true, unreadSources: [{ channelId: "c1", lastUnreadSeq: 4 }] }] } }))
await waitFor(() => expect(rendered.result.current.servers[0]?.unread).toBe(false))
- act(() => getActiveAccountUnreadProjection(client).acceptPrimarySnapshot({ revision: 1, readStates: [{ channelId: "c1", lastReadSeq: 4 }] }))
+ act(() => publish({ kind: "read-state", data: { revision: 1, readStates: [{ channelId: "c1", lastReadMessageId: "m4", lastReadAt: null, lastReadSeq: 4 }] } }))
expect(rendered.result.current.servers[0]?.unread).toBe(false)
})
})
@@ -345,27 +313,6 @@ describe("useServer / projected canonical detail", () => {
expect(client.getQueryData(communityKeys.server(identity.id))).toBe(identity.id)
})
- it("starts server-detail coverage before transport and preserves a later arrival", async () => {
- seedList()
- let release!: (value: { channels: [] }) => void
- apiFetchMock.mockImplementation((url: string) => url.endsWith("/channels") ? new Promise((resolve) => { release = resolve }) : Promise.resolve(detailApi(url)))
- const projection = getActiveAccountUnreadProjection(client)
- projection.setNotificationPolicy({})
- projection.recordArrival({ channelId: "before", serverId: identity.id, seq: 1 })
- const request = fetchDetail()
- await waitFor(() => expect(release).toBeTypeOf("function"))
- projection.recordArrival({ channelId: "after", serverId: identity.id, seq: 2 })
- release({ channels: [] }); await request
- expect(projection.projectUnread("server-detail:srv_1", "before", false)).toBe(false)
- expect(projection.projectUnread("server-detail:srv_1", "after", false)).toBe(true)
- })
-
- it("cancels server-detail snapshot coverage when transport fails before unread data", async () => {
- seedList(); apiFetchMock.mockRejectedValue(new Error("offline"))
- await expect(fetchDetail()).rejects.toThrow("offline")
- expect(getActiveAccountUnreadProjection(client).inspectForTests().pendingSnapshots).toBe(0)
- })
-
it.each([["offline", new Error("offline")], ["5xx", new ApiError("unavailable", 503)]])("keeps the cached server list on a transient %s failure", async (_label, error) => {
seedDetail(); apiFetchMock.mockRejectedValue(error)
await expect(fetchDetail()).rejects.toBe(error)
@@ -387,22 +334,14 @@ describe("useServer / projected canonical detail", () => {
it("does not merge stale positives from the retired server unread endpoint", async () => {
seedList(); apiFetchMock.mockImplementation((url: string) => url.endsWith("/unreads") ? { channelIds: ["c1"], sources: [{ channelId: "c1", lastUnreadSeq: 3 }], stale: true } : detailApi(url))
await expect(fetchDetail()).resolves.toBe(identity.id)
- expect(getActiveAccountUnreadProjection(client).projectUnread("server-detail:srv_1", "c1", false)).toBe(false)
expect(apiFetchMock.mock.calls.some(([url]) => String(url).endsWith("/unreads"))).toBe(false)
})
it("projects child scope metadata and confirms every loaded channel", async () => {
seedList()
apiFetchMock.mockImplementation((url: string) => url.endsWith("/channels") ? { channels: [{ id: "forum_1", name: "Forum", type: "forum", categoryId: "cat_1" }] } : detailApi(url))
- const projection = getActiveAccountUnreadProjection(client)
- projection.setNotificationPolicy({ server: { srv_1: "all" }, channel: { forum_1: "nothing" } })
- projection.retireAccessScope({ kind: "channel", channelId: "forum_1" }); projection.grantAccessScope({ kind: "channel", channelId: "forum_1" })
await fetchDetail()
expect(registry.collections.channels.get("forum_1")).toMatchObject({ serverId: identity.id, type: "forum" })
- expect(projection.allowsAccess({ channelId: "forum_1", serverId: identity.id })).toBe(true)
- expect(projection.projectUnread("server-detail:srv_1", "post_1", false, 4)).toBe(false)
- projection.recordArrival({ channelId: "forum_1", serverId: identity.id, seq: 5 })
- expect(projection.projectUnread("server-detail:srv_1", "forum_1", false, 5)).toBe(false)
})
it("projects server-detail channels from canonical sources only", async () => {
diff --git a/src/web/src/hooks/community/use-servers.ts b/src/web/src/hooks/community/use-servers.ts
index 0e1a6b4b8..3518759c5 100644
--- a/src/web/src/hooks/community/use-servers.ts
+++ b/src/web/src/hooks/community/use-servers.ts
@@ -21,20 +21,12 @@ import { communityKeys } from "@/lib/query-keys"
import { avatarInitial } from "@/lib/community/avatar"
import { isServerOwner,UNCATEGORIZED_CATEGORY_ID, type CommunityRole } from "@alook/shared"
import type { Server,Category,Channel } from "@/lib/community/models/navigation"
-import {
-getActiveAccountUnreadProjection,
-accountUnreadAllowsAccess,
-type AccountUnreadProjection,
-type AccountUnreadScope,
-type AccountUnreadSource,
-} from "./account-unread-projection"
import { useCommunityWsStore } from "@/stores/community/ws"
import { useCommunityRuntime } from "@/stores/community/runtime"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import { ApiError, isAbortError } from "@/lib/errors"
import { evictServerChannelScopes } from "./community-ws/scope-eviction"
import {
-useAttentionScopes,
useOptionalCommunityDbRegistry,
useServerRailProjection,
useServerTreeProjection,
@@ -91,42 +83,18 @@ export const serversQueryFn = async (
ownerId: s.ownerId,
initial: avatarInitial(s.name),
active: false,
- unread: s.unread ?? false,
- // Defensive fallback: the API always projects `mentions` now, but during
- // rolling deploys or from cached stale responses the field could still be
- // absent — treat it as 0 rather than NaN.
- mentions: s.mentions ?? 0,
+ unread: false,
+ mentions: 0,
isOwner: isServerOwner(s.role),
...(["owner", "admin", "member"].includes(s.role ?? "") ? { role: s.role as CommunityRole } : {}),
...(s.memberId ? { memberId: s.memberId } : {}),
icon: s.icon ?? null,
official: s.official === true,
- ...(s.unreadSources ? { unreadSources: s.unreadSources } : {}),
- ...(s.mentionSources ? { mentionSources: s.mentionSources } : {}),
}))
return { servers }
}
-function serverListUnreadSources(data: ServersResponse): AccountUnreadSource[] {
- return data.servers.flatMap((server) => (
- [
- ...(server.unreadSources ?? []).map((source) => ({
- ...source,
- serverId: server.id,
- })),
- ...(server.mentionSources ?? []).flatMap((source) => source.count > 0 ? [{
- channelId: source.channelId,
- serverId: server.id,
- lastUnreadSeq: source.lastSeq,
- lastMentionSeq: source.lastSeq,
- isMention: true,
- }] : []),
- ]
- ))
-}
-
export const serversProjectedQueryFn = (
- projection: AccountUnreadProjection,
queryClient: QueryClient,
onLiveSuccess?: (
token: CommunityLiveSnapshotToken,
@@ -135,7 +103,6 @@ export const serversProjectedQueryFn = (
) => void,
) => async (context?: QueryFunctionContext) => {
const structuralToken = captureCommunityLiveSnapshotToken(queryClient)
- const token = projection.beginSnapshot("servers", "channels")
try {
const registry = structuralToken.registry
await registry?.ready
@@ -144,12 +111,6 @@ export const serversProjectedQueryFn = (
assertCommunityLiveSnapshotTokenCurrent(queryClient, structuralToken, context?.signal)
const data = await serversQueryFn(context)
assertCommunityLiveSnapshotTokenCurrent(queryClient, structuralToken, context?.signal)
- projection.absorbSnapshot(token, serverListUnreadSources(data), {
- confirmedAccessScopes: data.servers.map((server) => ({
- kind: "server" as const,
- serverId: server.id,
- })),
- })
publishCommunityLiveSnapshot(queryClient, {
snapshot: { kind: "servers", data },
proof: { kind: "structural", token: structuralToken, signal: context?.signal },
@@ -161,14 +122,9 @@ export const serversProjectedQueryFn = (
ownerGeneration: structuralToken.ownerGeneration,
serverIdsSignature: canonicalServerIdsSignature(data.servers),
}))
- for (const server of data.servers) if (server.unreadSources) projection.absorbLegacyServerAggregate(server.id, server.unreadSources)
- projection.recordLegacySnapshot(data, data.servers.flatMap((server) => server.unread && server.unreadSources === undefined
- ? [{ family: "servers" as const, channelId: `\u0000legacy-server:${server.id}`, serverId: server.id }]
- : []))
onLiveSuccess?.(structuralToken, data, context?.signal)
return data.servers.map((server) => server.id)
} catch (error) {
- projection.cancelSnapshot(token)
throw error
}
}
@@ -176,7 +132,7 @@ export const serversProjectedQueryFn = (
function serversQueryOptions(queryClient: QueryClient) {
return {
queryKey: communityKeys.servers(),
- queryFn: serversProjectedQueryFn(getActiveAccountUnreadProjection(queryClient), queryClient),
+ queryFn: serversProjectedQueryFn(queryClient),
staleTime: 30_000,
} as const
}
@@ -184,23 +140,16 @@ function serversQueryOptions(queryClient: QueryClient) {
export function useServers(): UseQueryResult<string[]> & { servers: Server[]; isLiveAuthoritative: boolean } {
const registry = useOptionalCommunityDbRegistry()
const authority = useSelector(registry?.serverListAuthority ?? absentAuthority, (value) => value)
- const attentionScopes = useAttentionScopes()
const dbRail = useServerRailProjection()
const queryClient = useQueryClient()
const structuralGeneration = useCommunityWsStore((state) => `${state.profileViewerId ?? ""}:${state.profileAccountEpoch}:${state.accessEpoch}`)
- const unreadProjection = useMemo(() => getActiveAccountUnreadProjection(queryClient), [queryClient])
- const serverAccess = useSelector(unreadProjection.state, (state) => (dbRail?.servers ?? []).map((server) => accountUnreadAllowsAccess(state, { serverId: server.id })), { compare: (left, right) => left.length === right.length && left.every((value, index) => value === right[index]) })
+ const serverAccess = useCommunityWsStore((state) => state.revokedServerIds)
const query = useQuery({ ...serversQueryOptions(queryClient), refetchOnReconnect: true })
const servers = useMemo(() => {
- const raw = dbRail?.servers.filter((_server, index) => serverAccess[index])
+ const raw = dbRail?.servers.filter((_server) => !serverAccess.has(_server.id))
if (!raw) return EMPTY_SERVERS as Server[]
- return raw.map((server) => {
- const scopes = attentionScopes.filter((scope) => scope.serverId === server.id)
- const unread = scopes.some((scope) => scope.ordinaryUnread)
- const mentions = scopes.reduce((total, scope) => total + (scope.attentionCount ?? 0), 0)
- return unread === server.unread && mentions === server.mentions ? server : { ...server, unread, mentions }
- })
- }, [attentionScopes, dbRail?.servers, serverAccess])
+ return raw
+ }, [dbRail?.servers, serverAccess])
void structuralGeneration
const state = registry?.runtime.ws.get()
return {
@@ -346,9 +295,6 @@ export const serverProjectedQueryFn = (
signal?: AbortSignal,
) => async () => {
const structuralToken = captureCommunityLiveSnapshotToken(queryClient)
- const projection = getActiveAccountUnreadProjection(queryClient)
- const family = `server-detail:${serverId}` as const
- const token = projection.beginSnapshot(family, "channels")
try {
return await withConversationReadDeadline(signal, async (readSignal) => {
await structuralToken.registry?.ready
@@ -361,18 +307,6 @@ export const serverProjectedQueryFn = (
assertCommunityLiveSnapshotTokenCurrent(queryClient, structuralToken, readSignal)
const data = await serverQueryFn(queryClient, serverId, readSignal)()
assertCommunityLiveSnapshotTokenCurrent(queryClient, structuralToken, readSignal)
- const confirmedAccessScopes: AccountUnreadScope[] = [
- { kind: "server", serverId },
- ...data.categories.flatMap((category) => category.channels.map((channel) => ({
- kind: "channel" as const,
- channelId: channel.id,
- }))),
- ]
- projection.absorbSnapshot(
- token,
- [],
- { confirmedAccessScopes },
- )
publishCommunityLiveSnapshot(queryClient, {
snapshot: { kind: "server-detail", data },
proof: { kind: "structural", token: structuralToken, signal: readSignal },
@@ -380,7 +314,6 @@ export const serverProjectedQueryFn = (
return data.id
})
} catch (error) {
- projection.cancelSnapshot(token)
if (error instanceof ApiError && (error.status === 403 || error.status === 404)) {
evictServerChannelScopes(queryClient, serverId)
}
@@ -399,7 +332,6 @@ export const serverProjectedQueryFn = (
export function useServer(
serverId: string | null,
): UseQueryResult<string> & { server: ServerDetail | null } {
- const attentionScopes = useAttentionScopes()
const dbServer = useServerTreeProjection(serverId)
const queryClient = useQueryClient()
const enabled = !!serverId
@@ -426,33 +358,11 @@ export function useServer(
void restart({ cancelRefetch: false })
}
}, [query.error, queryClient, serverId, restart])
- const projectedServer = useMemo(() => {
- const source = dbServer
- if (!source || !serverId) return null
- let changed = false
- const categories = source.categories.map((category) => {
- let categoryChanged = false
- const channels = category.channels.map((channel) => {
- const unread = attentionScopes.some((scope) => (
- scope.serverId === serverId
- && (scope.channelId === channel.id || scope.parentChannelId === channel.id)
- && scope.ordinaryUnread
- ))
- if (unread === channel.unread) return channel
- categoryChanged = true
- return { ...channel, unread }
- })
- if (!categoryChanged) return category
- changed = true
- return { ...category, channels }
- })
- return changed ? { ...source, categories } : source
- }, [attentionScopes, dbServer, serverId])
return {
...query,
server: query.error instanceof ApiError
&& (query.error.status === 403 || query.error.status === 404)
? null
- : projectedServer,
+ : dbServer ?? null,
}
}
diff --git a/src/web/src/hooks/community/use-thread-participants.dom.test.ts b/src/web/src/hooks/community/use-thread-participants.dom.test.ts
index 31e5d9994..d0a00c8de 100644
--- a/src/web/src/hooks/community/use-thread-participants.dom.test.ts
+++ b/src/web/src/hooks/community/use-thread-participants.dom.test.ts
@@ -1,3 +1,4 @@
+import { seedCommunityAttentionScope } from "@/test/community-query-owner"
import { createElement, type PropsWithChildren } from "react"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
@@ -6,7 +7,6 @@ import { communityKeys } from "@/lib/query-keys"
import { createCommunityDbRegistry, type CommunityDbRegistry } from "@/lib/community-db/collections"
import { CommunityDbProvider } from "@/lib/community-db/projections"
import { captureCommunityLiveSnapshotToken, ingestServerDetail, publishCommunityForumSidebar } from "@/lib/community-db/sync"
-import { getAccountUnreadProjection } from "./account-unread-projection"
import { getForumSidebarBase } from "./use-forum-sidebar-threads"
import { useAddThreadParticipant, useRemoveThreadParticipant } from "./use-thread-participants"
@@ -49,8 +49,8 @@ describe("useRemoveThreadParticipant", () => {
seedSidebar()
const metaKey = communityKeys.channelMeta("server_1", "post_1")
client.setQueryData(metaKey, { id: "post_1", parentChannelId: "forum_1" })
- const projection = getAccountUnreadProjection(client, "viewer_1")
- projection.recordArrival({ channelId: "post_1", serverId: "server_1", seq: 7 })
+
+ seedCommunityAttentionScope(client, { channelId: "post_1", serverId: "server_1", seq: 7 })
const rendered = renderHook(() => useRemoveThreadParticipant("post_1", "server_1", "viewer_1"), { wrapper: Owner })
await command(() => rendered.result.current.mutateAsync("viewer_1"))
expect(apiFetchMock).toHaveBeenCalledWith("/api/community/channels/post_1/participants/viewer_1", expect.objectContaining({ method: "DELETE", signal: expect.any(AbortSignal), assertActive: expect.any(Function) }))
@@ -58,29 +58,29 @@ describe("useRemoveThreadParticipant", () => {
expect(registry.collections.channelMemberships.get("post_1:viewer_1:access")).toBeDefined()
expect(registry.collections.channelMemberships.get("post_1:viewer_1:notify")).toBeUndefined()
expect(client.getQueryData(metaKey)).toEqual({ id: "post_1", parentChannelId: "forum_1" })
- expect(projection.projectUnread("inbox-unreads", "post_1", false, 7)).toBe(false)
+ expect(Boolean(registry.collections.attentionScopes.get("post_1")?.ordinaryUnread)).toBe(false)
})
it("does not retire viewer unread scope when participant removal fails", async () => {
seedSidebar()
- const projection = getAccountUnreadProjection(client, "viewer_1")
- projection.recordArrival({ channelId: "post_1", serverId: "server_1", seq: 7 })
+
+ seedCommunityAttentionScope(client, { channelId: "post_1", serverId: "server_1", seq: 7 })
apiFetchMock.mockRejectedValueOnce(new Error("failed"))
const rendered = renderHook(() => useRemoveThreadParticipant("post_1", "server_1", "viewer_1"), { wrapper: Owner })
await act(async () => { await expect(rendered.result.current.mutateAsync("viewer_1")).rejects.toThrow("failed") })
- expect(projection.projectUnread("inbox-unreads", "post_1", false, 7)).toBe(true)
+ expect(Boolean(registry.collections.attentionScopes.get("post_1")?.ordinaryUnread)).toBe(true)
expect(getForumSidebarBase(client, "server_1").threads).toHaveLength(1)
expect(registry.collections.channelMemberships.get("post_1:viewer_1:notify")).toBeDefined()
})
it("keeps the viewer's sidebar row when the creator removes someone else", async () => {
seedSidebar()
- const projection = getAccountUnreadProjection(client, "viewer_1")
- projection.recordArrival({ channelId: "post_1", serverId: "server_1", seq: 7 })
+
+ seedCommunityAttentionScope(client, { channelId: "post_1", serverId: "server_1", seq: 7 })
const rendered = renderHook(() => useRemoveThreadParticipant("post_1", "server_1", "viewer_1"), { wrapper: Owner })
await command(() => rendered.result.current.mutateAsync("other_1"))
expect(getForumSidebarBase(client, "server_1").threads).toHaveLength(1)
- expect(projection.projectUnread("inbox-unreads", "post_1", false, 7)).toBe(true)
+ expect(Boolean(registry.collections.attentionScopes.get("post_1")?.ordinaryUnread)).toBe(true)
})
it("does not revalidate the viewer's forum access when adding someone else", async () => {
diff --git a/src/web/src/hooks/community/use-thread-participants.ts b/src/web/src/hooks/community/use-thread-participants.ts
index 8f378ce6e..40f14006f 100644
--- a/src/web/src/hooks/community/use-thread-participants.ts
+++ b/src/web/src/hooks/community/use-thread-participants.ts
@@ -2,8 +2,7 @@
import { useQueryClient } from "@tanstack/react-query"
import { useChannelMemberCommand } from "./use-channel-members"
-import { grantForumSidebarChild, removeForumSidebarProjectionExact, removeForumSidebarUnreadChild } from "./use-forum-sidebar-threads"
-import { getActiveAccountUnreadProjection } from "./account-unread-projection"
+import { grantForumSidebarChild, removeForumSidebarProjectionExact } from "./use-forum-sidebar-threads"
export function useAddThreadParticipant(channelId: string, serverId?: string, viewerUserId?: string) {
const client = useQueryClient()
@@ -16,7 +15,6 @@ export function useRemoveThreadParticipant(channelId: string, serverId?: string,
const client = useQueryClient()
return useChannelMemberCommand(channelId, "remove", { endpoint: "participants", relation: "notify", onConfirmed: (userId) => {
if (userId !== viewerUserId) return
- getActiveAccountUnreadProjection(client).retireNotificationScope({ kind: "channel", channelId })
- if (serverId && forumSidebar) { removeForumSidebarUnreadChild(client, serverId, channelId); removeForumSidebarProjectionExact(client, serverId, channelId) }
+ if (serverId && forumSidebar) { removeForumSidebarProjectionExact(client, serverId, channelId) }
} })
}
diff --git a/src/web/src/lib/community-db/message-access-scope.ts b/src/web/src/lib/community-db/message-access-scope.ts
index 00da757c6..7168e808f 100644
--- a/src/web/src/lib/community-db/message-access-scope.ts
+++ b/src/web/src/lib/community-db/message-access-scope.ts
@@ -39,3 +39,15 @@ export function takeMessageIdsForAccessScope(
}
return messageIds
}
+
+export const communityServerRetirementKey = ["community", "server-retirement"] as const
+
+export function communityServerRetirementId(
+ mutation: { options: { mutationKey?: readonly unknown[] }; state: { variables: unknown } },
+ registry: unknown,
+): string | undefined {
+ const key = mutation.options.mutationKey
+ const input = mutation.state.variables as { serverId?: string; original?: { registry?: unknown } } | undefined
+ return registry && communityServerRetirementKey.every((part, index) => key?.[index] === part) && (key?.[2] === "leave" || key?.[2] === "delete") && input?.original?.registry === registry
+ ? input.serverId : undefined
+}
diff --git a/src/web/src/lib/community-db/projections.dom.test.ts b/src/web/src/lib/community-db/projections.dom.test.ts
index 277d68ea0..2865f75f1 100644
--- a/src/web/src/lib/community-db/projections.dom.test.ts
+++ b/src/web/src/lib/community-db/projections.dom.test.ts
@@ -418,6 +418,10 @@ describe("community DB projections", () => {
channelId: "c1", lastReadMessageId: "m1", lastReadAt: "2026-09-25T00:00:01.000Z",
lastReadSeq: 1,
}])
+ collection("attentionScopes", [
+ { scopeId: "c1", channelId: "c1", serverId: "s1", parentChannelId: null, ordinaryUnread: true, lastUnreadSeq: 2, attentionCount: 2, lastAttentionSeq: 2 },
+ { scopeId: "dm1", channelId: "dm1", serverId: null, parentChannelId: null, ordinaryUnread: true, lastUnreadSeq: 8, attentionCount: 0, lastAttentionSeq: null },
+ ])
collection("readStateClock", [{ id: "account", revision: 1 }])
collection("folders", [
{ id: "f2", name: "Later", position: 2 },
@@ -462,7 +466,7 @@ describe("community DB projections", () => {
await waitFor(() => expect(rendered.result.current.restored).toBe(true))
expect(rendered.result.current.rail?.servers).toEqual([
- expect.objectContaining({ id: "s1", name: "Server" }),
+ expect.objectContaining({ id: "s1", name: "Server", unread: true, mentions: 2 }),
])
expect(rendered.result.current.rail?.folders).toEqual(expect.arrayContaining([
expect.objectContaining({ id: "f1", servers: [expect.objectContaining({ id: "s1" })] }),
diff --git a/src/web/src/lib/community-db/projections.ts b/src/web/src/lib/community-db/projections.ts
index 5c576abb1..be7b9ccb4 100644
--- a/src/web/src/lib/community-db/projections.ts
+++ b/src/web/src/lib/community-db/projections.ts
@@ -126,6 +126,7 @@ export function useServerRailProjection() {
servers: useServerRows(),
serverMemberships: useServerMembershipRows(),
serverRail: useCollectionRows("serverRail"),
+ attention: useAttentionScopes(),
folders: useFolderRows(),
folderItems: useFolderItemRows(),
}
@@ -152,8 +153,8 @@ export function useServerRailProjection() {
ownerId: server.ownerId,
initial: avatarInitial(server.name),
active: false,
- unread: server.unread,
- mentions: server.mentions,
+ unread: rows.attention.some(scope => scope.serverId === server.id && scope.ordinaryUnread),
+ mentions: rows.attention.reduce((sum, scope) => sum + (scope.serverId === server.id ? scope.attentionCount : 0), 0),
official: server.official,
isOwner: server.isOwner,
icon: server.icon,
@@ -191,13 +192,14 @@ export function useServerRailProjection() {
const topOrder = serverRailTopOrder(state)
const byFolder = new Map(folders.map((folder) => [folder.id, folder]))
return { servers: sortServerRailRows(state, servers), folders: topOrder.flatMap((entry) => entry.kind === "folder" ? [byFolder.get(entry.id)!] : []), topOrder }
- }, [rows.registry, rows.servers, rows.serverMemberships, rows.folders, rows.folderItems, rows.serverRail])
+ }, [rows.registry, rows.servers, rows.serverMemberships, rows.folders, rows.folderItems, rows.serverRail, rows.attention])
}
export function useServerTreeProjection(serverId: string | null) {
const servers = useCollectionQuery("servers", ({ row }) => eq(row.id, serverId ?? ""))
const categories = useCollectionQuery("categories", ({ row }) => eq(row.serverId, serverId ?? ""))
const channels = useCollectionQuery("channels", ({ row }) => eq(row.serverId, serverId ?? ""))
+ const attention = useAttentionScopes()
const ready = servers.isReady && categories.isReady && channels.isReady
const rows = { servers: servers.data, categories: categories.data, channels: channels.data }
return useMemo(() => {
@@ -211,7 +213,7 @@ export function useServerTreeProjection(serverId: string | null) {
id: channel.id,
name: channel.name ?? "",
active: false,
- unread: channel.unread,
+ unread: attention.some((scope) => scope.serverId === serverId && (scope.channelId === channel.id || scope.parentChannelId === channel.id) && (scope.ordinaryUnread || scope.attentionCount > 0)),
muted: channel.muted,
type: channel.type === "forum" ? "forum" : "text",
tags: channel.tags,
@@ -245,7 +247,7 @@ export function useServerTreeProjection(serverId: string | null) {
ownerId: server.ownerId, categories,
}
return view
- }, [ready, rows.servers, rows.categories, rows.channels, serverId])
+ }, [attention, ready, rows.servers, rows.categories, rows.channels, serverId])
}
export function useDmProjection() {
@@ -257,14 +259,13 @@ export function useDmProjection() {
membership.relation === "access" && membership.userId !== registry?.accountId
)).map((membership) => membership.userId), [channelMemberships, registry?.accountId])
const profiles = useCollectionQuery("profiles", ({ row }) => inArray(row.id, userIds)).data
- const readStates = useCollectionQuery("readStates", ({ row }) => inArray(row.channelId, channelIds)).data
- const rows = { registry, channels, channelMemberships, profiles, readStates }
+ const attention = useAttentionScopes()
+ const rows = { registry, channels, channelMemberships, profiles }
return useMemo(() => {
const viewerId = rows.registry?.accountId
if (!viewerId || !rows.channels || !rows.channelMemberships || !rows.profiles) return undefined
const channelMemberships = rows.channelMemberships
const profileById = new Map(rows.profiles.map((profile) => [profile.id, profile]))
- const readStateByChannel = new Map((rows.readStates ?? []).map((state) => [state.channelId, state]))
const result = sortDmsByActivity(rows.channels
.filter((channel) => channel.type === "dm")
.flatMap((channel): DM[] => {
@@ -276,7 +277,7 @@ export function useDmProjection() {
if (!peerMembership) return []
const profile = profileById.get(peerMembership.userId)
if (!profile) return []
- const readState = readStateByChannel.get(channel.id)
+ const scope = attention.find((scope) => scope.channelId === channel.id)
return [{
...readCommunityProfile(profile, profile.id),
id: channel.id,
@@ -284,14 +285,12 @@ export function useDmProjection() {
status: "offline",
preview: channel.preview ?? "",
...(channel.lastMessageAt ? { activityAt: channel.lastMessageAt } : {}),
- unread: channel.unread,
- ...(channel.lastUnreadSeq === undefined && !readState
- ? {}
- : { lastUnreadSeq: channel.lastUnreadSeq ?? readState?.lastReadSeq }),
+ unread: scope?.ordinaryUnread ?? false,
+ ...(scope ? { lastUnreadSeq: scope.lastUnreadSeq } : {}),
}]
}))
return result
- }, [rows.registry, rows.channels, rows.channelMemberships, rows.profiles, rows.readStates])
+ }, [attention, rows.registry, rows.channels, rows.channelMemberships, rows.profiles])
}
export function useRouteChannelProjection(channelId: string | null) {
@@ -494,30 +493,36 @@ function useForumSidebarRows(serverId: string) {
const messageProjection = useCollectionQuery("messages", ({ row }) => inArray(row.id, openerIds))
const ready = serverProjection.isReady && channelProjection.isReady && membershipProjection.isReady && messageProjection.isReady
return { registry: channelProjection.registry, ready, servers: serverProjection.data, channels,
- channelMemberships: membershipProjection.data, messages: messageProjection.data }
+ channelMemberships: membershipProjection.data, messages: messageProjection.data, attention: useAttentionScopes() }
}
export function useForumSidebarProjection(serverId: string, retainId: string | null, serverNowMs: number | null) {
const rows = useForumSidebarRows(serverId)
return useMemo(() => {
if (serverNowMs === null || !rows.ready || !rows.registry || !rows.channels || !rows.channelMemberships || !rows.messages) return undefined
- return projectForumSidebar(rows.channels, rows.channelMemberships, rows.messages, rows.registry.accountId, serverId, retainId, serverNowMs)
- }, [serverNowMs, rows.ready, rows.registry, rows.channels, rows.channelMemberships, rows.messages, serverId, retainId])
+ return projectForumSidebar(rows.channels, rows.channelMemberships, rows.messages, rows.registry.accountId, serverId, retainId, serverNowMs, rows.attention)
+ }, [rows.attention, serverNowMs, rows.ready, rows.registry, rows.channels, rows.channelMemberships, rows.messages, serverId, retainId])
}
export function useServerSidebarProjection(
serverId: string, retainId: string | null, serverNowMs: number | null, window: ForumSidebarWindow | undefined, failed: boolean,
) {
const server = useServerTreeProjection(serverId)
- const { ready, registry, servers, channels, channelMemberships, messages } = useForumSidebarRows(serverId)
+ const { ready, registry, servers, channels, channelMemberships, messages, attention } = useForumSidebarRows(serverId)
return useMemo(() => {
if (serverNowMs === null || !ready || !registry || !servers || !channels || !channelMemberships || !messages) {
return { server, projection: undefined, status: failed ? "error" as const : "pending" as const, needsRead: false }
}
const complete = !!server && (!channels.some(row => row.type === "forum")
|| !!window && forumSidebarWindowComplete(window, { servers, channels, channelMemberships, messages }, registry.accountId, serverId, retainId, serverNowMs))
- const projection = projectForumSidebar(channels, channelMemberships, messages, registry.accountId, serverId, retainId, serverNowMs)
+ const projection = projectForumSidebar(channels, channelMemberships, messages, registry.accountId, serverId, retainId, serverNowMs, attention)
return { server, projection, status: complete ? "ready" as const : failed ? "error" as const : "pending" as const,
needsRead: !!server && !!window && !complete }
- }, [server, serverNowMs, ready, registry, servers, channels, channelMemberships, messages, window, serverId, retainId, failed])
+ }, [attention, server, serverNowMs, ready, registry, servers, channels, channelMemberships, messages, window, serverId, retainId, failed])
+}
+
+export function useChannelReadStateProjection(channelId: string | null) {
+ const read = useCollectionQuery("readStates", ({ row }) => eq(row.channelId, channelId ?? ""), !!channelId)
+ const clock = useCollectionRows("readStateClock")
+ return { readState: read.data?.[0], hasSnapshot: (clock?.[0]?.revision ?? -1) >= 0 }
}
diff --git a/src/web/src/lib/community-db/schema.ts b/src/web/src/lib/community-db/schema.ts
index 912b11cd2..7bef7f900 100644
--- a/src/web/src/lib/community-db/schema.ts
+++ b/src/web/src/lib/community-db/schema.ts
@@ -17,8 +17,6 @@ export const serverSchema = z.object({
icon: nullableString,
official: z.boolean(),
isOwner: z.boolean(),
- unread: z.boolean(),
- mentions: z.number().int().nonnegative(),
detailComplete: z.boolean().default(false),
})
@@ -34,16 +32,12 @@ export const categorySchema = z.object({
export const channelLocalSchema = z.object({
muted: z.boolean(),
- unread: z.boolean(),
- /** Forum channel's own unread bit, excluding participating child rows. */
- baseUnread: z.boolean().optional(),
tags: z.array(z.string()),
pending: z.boolean(),
openerSeq: z.number().int().nonnegative().optional(),
openerUnread: z.boolean().optional(),
preview: z.string().optional(),
firstMessageId: z.string().min(1).nullable().optional(),
- lastUnreadSeq: z.number().int().nonnegative().optional(),
participantCount: z.number().int().nonnegative().optional(),
})
@@ -196,7 +190,6 @@ export function canonicalChannelRow(
position: 0,
archived: false,
muted: false,
- unread: false,
tags: [],
pending: false,
lastMessageAt: null,
diff --git a/src/web/src/lib/community-db/sync.test.ts b/src/web/src/lib/community-db/sync.test.ts
index b0780e400..b40fd3418 100644
--- a/src/web/src/lib/community-db/sync.test.ts
+++ b/src/web/src/lib/community-db/sync.test.ts
@@ -1,9 +1,9 @@
+import { seedCommunityAttentionScope } from "@/test/community-query-owner"
import { projectPostedMessage } from "@/lib/community/message-wire"
import { QueryClient } from "@tanstack/react-query"
import { afterEach, describe, expect, it, vi } from "vitest"
import { AccountAttentionSnapshotSchema, CommunityMessageResourceSchema, communityMessagePreviewFromLegacy, type CommunityWsEvent } from "@alook/shared"
import { communityKeys } from "@/lib/query-keys"
-import { getAccountUnreadProjection } from "@/hooks/community/account-unread-projection"
import { rememberMessageAccessScope } from "./message-access-scope"
import { getLastChannel, setLastChannel } from "@/lib/community/last-channel"
import {
@@ -47,6 +47,7 @@ import {
purgeCommunityChannel,
purgeCommunityServer,
retireCommunityChannelReading,
+ removeCanonicalCommunityChannelMembership,
removeAttentionItemsOptimistically,
restoreAttentionScopeOptimisticSnapshot,
type CommunityLiveSnapshot,
@@ -93,6 +94,19 @@ function forumAttentionSnapshot(seq = 4) {
})
}
+it("keeps explicit attention when ordinary thread notifications are retired", async () => {
+ const db = await registry()
+ const attention = forumAttentionSnapshot()
+ ingestAttentionSnapshot(db, attention)
+ setCanonicalCommunityChannelMember(db.queryClient, "post", "viewer", "notify", true, { event: true })
+ expect(removeCanonicalCommunityChannelMembership(db.queryClient, "post", "notify")).toBe(true)
+ expect(db.collections.channelMemberships.get("post:viewer:notify")).toBeUndefined()
+ expect(db.collections.attentionScopes.get("post")).toMatchObject({ ordinaryUnread: false, unreadCount: 0, attentionCount: 1, lastAttentionSeq: 4 })
+ expect(db.collections.attentionItems.get("reply:m4")).toMatchObject(attention.items[0]!)
+ expect(db.collections.messages.get("m4")?.content).toBe("Reply")
+ expect(db.collections.channels.has("post")).toBe(true)
+})
+
function publishCommunityLiveSnapshot(
queryClient: QueryClient,
snapshot: CommunityLiveSnapshot,
@@ -124,6 +138,22 @@ afterEach(async () => {
})
describe("community DB sync", () => {
+ it("keeps a partial eligible count unknown until fresh authoritative readback, and restores it on rollback", async () => {
+ const db = await registry()
+ const scope = { scopeId: "dm", channelId: "dm", serverId: null, parentChannelId: null, ordinaryUnread: true, lastUnreadSeq: 9, attentionCount: 0, lastAttentionSeq: null, unreadCount: 3 }
+ const seed = (unreadCount: number) => ingestAttentionSnapshot(db, { scopes: [{ ...scope, unreadCount }], items: [], limit: 100, truncated: false })
+ seed(3)
+ const first = clearAttentionScopeOptimistically(db, "dm", 5)
+ expect(db.collections.attentionScopes.get("dm")?.unreadCount).toBeUndefined()
+ restoreAttentionScopeOptimisticSnapshot(db, first)
+ expect(db.collections.attentionScopes.get("dm")?.unreadCount).toBe(3)
+ const next = clearAttentionScopeOptimistically(db, "dm", 5)
+ publishCommunityConversationReadState(db.queryClient, { channelId: "dm", lastReadMessageId: "m5", lastReadAt: "2026-10-27T00:00:05.000Z", lastReadSeq: 5 }, 2, { token: captureCommunityLiveSnapshotToken(db.queryClient) }, "advance")
+ seed(1)
+ await commitAttentionScopeOptimisticSnapshot(db, next)
+ expect(db.collections.attentionScopes.get("dm")?.unreadCount).toBe(1)
+ })
+
it("keeps unloaded and partial member data unknown but prunes a fresh complete roster without requiring profiles", async () => {
const db = await registry()
publishCommunityChannelMetadata(db.queryClient, {
@@ -465,7 +495,7 @@ describe("community DB sync", () => {
expect(db.collections.serverMemberships.get(membership.id)).toStrictEqual(membership)
expect(db.collections.servers.get("s2")).toMatchObject({ id: "s2", position: 1,
name: "New", discriminator: "0003", description: "", ownerId: "", icon: null,
- official: false, isOwner: false, unread: false, mentions: 0, detailComplete: false })
+ official: false, isOwner: false, detailComplete: false })
expect([...db.collections.serverMemberships.values()].find((row) => row.serverId === "s2"))
.toMatchObject({ serverId: "s2", userId: "viewer", role: "member", viewer: true })
})
@@ -1657,14 +1687,12 @@ describe("community DB sync", () => {
muted: true,
preview: "keep preview",
lastMessageAt: "2026-09-28T00:00:07.000Z",
- lastUnreadSeq: 7,
})
expect(db.collections.channels.get("new")).toMatchObject({
position: 1,
muted: false,
preview: "",
lastMessageAt: "2026-09-28T00:00:08.000Z",
- lastUnreadSeq: 8,
})
})
})
@@ -2249,7 +2277,7 @@ describe("community DB sync", () => {
setItem: (key: string, value: string) => navigationMemory.set(key, value),
removeItem: (key: string) => navigationMemory.delete(key),
})
- const unreadProjection = getAccountUnreadProjection(db.queryClient, "viewer")
+
ingestServers(db, {
servers: [{
id: "s1", name: "Server", initial: "S", active: false, unread: false,
@@ -2282,7 +2310,7 @@ describe("community DB sync", () => {
id: "m1", type: "chat", authorId: "thread-author", authorName: "Thread Author",
content: "thread", createdAt: "2026-09-25T00:00:01.000Z",
}])
- unreadProjection.recordArrival({ channelId: "c1", serverId: "s1", seq: 1 })
+ seedCommunityAttentionScope(db.queryClient, { channelId: "c1", serverId: "s1", seq: 1 })
db.queryClient.setQueryData(communityKeys.inboxUnreads(), {
friendRequests: [],
servers: [{
@@ -2318,7 +2346,7 @@ describe("community DB sync", () => {
expect(db.collections.messages.get("m1")).toBeUndefined()
expect(db.collections.channelMemberships.get("c1:viewer:access")).toBeUndefined()
expect(db.collections.profiles.get("thread-author")).toBeUndefined()
- expect(unreadProjection.projectUnread("inbox-unreads", "c1", true)).toBe(false)
+ expect(Boolean(db.collections.attentionScopes.get("c1")?.ordinaryUnread)).toBe(false)
expect(db.queryClient.getQueryData<{ servers: unknown[] }>(
communityKeys.inboxUnreads(),
)?.servers).toEqual([])
@@ -2334,7 +2362,7 @@ describe("community DB sync", () => {
id: "dm-message", type: "chat", authorId: "peer", authorName: "Peer",
content: "dm", createdAt: "2026-09-25T00:00:02.000Z",
}])
- unreadProjection.recordArrival({ channelId: "dm1", seq: 2 })
+ seedCommunityAttentionScope(db.queryClient, { channelId: "dm1", seq: 2 })
db.queryClient.setQueryData(communityKeys.inboxUnreads(), {
friendRequests: [],
servers: [],
@@ -2347,7 +2375,7 @@ describe("community DB sync", () => {
expect(db.collections.channelMemberships.get("dm1:peer:access")).toBeUndefined()
expect(db.collections.messages.get("dm-message")).toBeUndefined()
expect(db.collections.profiles.get("peer")).toBeUndefined()
- expect(unreadProjection.projectUnread("inbox-unreads", "dm1", true)).toBe(false)
+ expect(Boolean(db.collections.attentionScopes.get("dm1")?.ordinaryUnread)).toBe(false)
expect(db.queryClient.getQueryData<{ dms: unknown[] }>(
communityKeys.inboxUnreads(),
)?.dms).toEqual([])
@@ -2961,8 +2989,8 @@ describe("community DB sync", () => {
event({ type: "community:member.leave", serverId: "s1", userId: "peer" })
event({ type: "community:category.delete", serverId: "s1", categoryId: "cat2" })
- expect(db.collections.servers.get("s1")).toMatchObject({ name: "Renamed", unread: true, mentions: 1 })
- expect(db.collections.channels.get("c1")).toMatchObject({ name: "renamed", position: 9, unread: true })
+ expect(db.collections.servers.get("s1")).toMatchObject({ name: "Renamed" })
+ expect(db.collections.channels.get("c1")).toMatchObject({ name: "renamed", position: 9 })
expect(db.collections.channels.get("thread1")).toMatchObject({ name: "Thread renamed", tags: ["tag"] })
expect(db.collections.messages.get("m1")?.reactions).toEqual([
{ emoji: "👍", count: 1, me: true, userIds: ["viewer"] },
diff --git a/src/web/src/lib/community-db/sync.ts b/src/web/src/lib/community-db/sync.ts
index 21208f323..16b327585 100644
--- a/src/web/src/lib/community-db/sync.ts
+++ b/src/web/src/lib/community-db/sync.ts
@@ -49,7 +49,6 @@ import { avatarInitial } from "@/lib/community/avatar"
import { canonicalUserImage } from "@/lib/community/storage"
import { projectCommunityMessageCreate } from "@/lib/community/message-wire"
import { clearTypingIndicator } from "@/hooks/community/community-ws/typing"
-import { getAccountUnreadProjection } from "@/hooks/community/account-unread-projection"
import { takeMessageIdsForAccessScope } from "./message-access-scope"
import { clearLastChannel,getLastChannel } from "@/lib/community/last-channel"
import { clearLastMeLocation,getLastMeLeaf } from "@/lib/community/last-me-location"
@@ -664,12 +663,7 @@ function clearChannelTransientState(
if (channelIds.has(entry.scope.id)) registry.runtime.messageStream.actions.removeScope(entry.scope)
}
const community = registry.runtime.ui.get()
- const unreadProjection = getAccountUnreadProjection(
- registry.queryClient,
- registry.accountId ?? "__anonymous__",
- )
for (const channelId of channelIds) {
- unreadProjection.retireAccessScope({ kind: "channel", channelId })
for (const scope of [`ch:${channelId}`, `dm:${channelId}`]) {
for (const userId of community.typingByScope.get(scope)?.keys() ?? []) {
clearTypingIndicator(registry.queryClient, scope, userId)
@@ -737,8 +731,7 @@ export function ingestServers(
icon: server.icon ?? null,
official: server.official === true,
isOwner: server.isOwner === true,
- unread: server.unread,
- mentions: server.mentions,
+
detailComplete: existingById.get(server.id)?.detailComplete ?? false,
}))
const viewerId = registry.accountId
@@ -782,8 +775,7 @@ export function ingestServerDetail(
icon: detail.icon,
official: detail.official === true,
isOwner: existing?.isOwner ?? detail.ownerId === registry.accountId,
- unread: existing?.unread ?? false,
- mentions: existing?.mentions ?? 0,
+
detailComplete: true,
}
const categories: CategoryRow[] = []
@@ -820,10 +812,6 @@ export function ingestServerDetail(
position: resource.position ?? channelIndex,
archived: resource.archived ?? previous?.archived ?? false,
muted: channel.muted === true,
- unread: channel.unread,
- ...(channel.type === "forum" ? {
- baseUnread: detail.forumUnreadState?.[channel.id]?.baseUnread ?? channel.unread,
- } : {}),
tags: channel.tags ?? [],
pending: channel.pending === true,
resourceComplete: complete,
@@ -842,30 +830,6 @@ export function ingestServerDetail(
const accessMemberships: ChannelMembershipRow[] = viewerId
? channels.map((channel) => (canonicalChannelMembershipRow(channel.id, viewerId, "access", { source: "inherited" })))
: []
- const existingChannels = new Map(
- collectionRows(registry, "channels").map((row) => [row.id, row]),
- )
- const unreadChildOwnership = Object.entries(detail.forumUnreadState ?? {})
- .flatMap(([parentChannelId, state]) => state.childIds.map((childId) => ({
- childId,
- parentChannelId,
- })))
- const unreadChildStubs: ChannelRow[] = unreadChildOwnership.flatMap((ownership) => {
- if (existingChannels.has(ownership.childId)) return []
- return [canonicalChannelRow({
- id: ownership.childId,
- serverId: detail.id,
- type: "thread" as const,
- parentChannelId: ownership.parentChannelId,
- unread: true,
- })]
- })
- const unreadChildMemberships: ChannelMembershipRow[] = viewerId
- ? unreadChildOwnership.flatMap(({ childId }) => ([
- canonicalChannelMembershipRow(childId, viewerId, "access", { source: "explicit" as const }),
- canonicalChannelMembershipRow(childId, viewerId, "notify", { source: "explicit" as const }),
- ]))
- : []
const authoritativeTopLevelIds = new Set([...currentTopLevelIds, ...incomingTopLevelIds])
notifyManager.batch(() => {
for (const channelId of removedTopLevelIds) purgeCommunityChannel(registry, channelId)
@@ -895,22 +859,7 @@ export function ingestServerDetail(
&& row.relation === "access"
&& authoritativeTopLevelIds.has(row.channelId),
)
- upsertRows(
- registry,
- "channelMemberships",
- unreadChildMemberships,
- )
}
- upsertRows(registry, "channels", unreadChildStubs)
- const unreadChildren = new Set(
- Object.values(detail.forumUnreadState ?? {}).flatMap((state) => state.childIds),
- )
- patchRows(
- registry,
- "channels",
- (row) => ({ ...row, unread: unreadChildren.has(row.id) }),
- (row) => row.serverId === detail.id && row.type === "thread",
- )
})
}
@@ -949,8 +898,7 @@ export function ingestDms(
for (const [position, dm] of response.conversations.entries()) {
channels.push(canonicalChannelRow({
id: dm.id, type: "dm", position,
- unread: dm.unread === true, lastMessageAt: dm.activityAt ?? null, preview: dm.preview,
- ...(dm.lastUnreadSeq === undefined ? {} : { lastUnreadSeq: dm.lastUnreadSeq }),
+ lastMessageAt: dm.activityAt ?? null, preview: dm.preview,
}, registry.collections.channels.get(dm.id)))
memberships.push(
canonicalChannelMembershipRow(dm.id, viewerId, "access"),
@@ -1114,6 +1062,7 @@ export function ingestReadStateSnapshot(
registry: CommunityDbRegistry,
snapshot: AccountReadStateSnapshot,
) {
+ const previousReads = new Map(collectionRows(registry, "readStates").map(row => [row.channelId, row.lastReadSeq]))
const currentRevision = collectionRows(registry, "readStateClock")
.find((row) => row.id === "account")?.revision ?? -1
if (snapshot.revision <= currentRevision) return
@@ -1124,10 +1073,12 @@ export function ingestReadStateSnapshot(
...newer,
]
const clock: ReadStateClockRow = { id: "account", revision: snapshot.revision }
+ const nextReadSeq = new Map(readStates.map(row => [row.channelId, row.lastReadSeq]))
+ const changedReads = new Set([...previousReads.keys(), ...nextReadSeq.keys()].filter(id => previousReads.get(id) !== nextReadSeq.get(id)))
notifyManager.batch(() => {
replaceRows(registry, "readStates", readStates, () => true)
replaceRows(registry, "readStateClock", [clock], () => true)
- projectConfirmedAttention(registry)
+ projectConfirmedAttention(registry, changedReads)
})
}
@@ -1136,13 +1087,15 @@ export function publishCommunityConversationReadState(
readState: ReadStateRow,
revision: number,
proof: CommunityFreshQueryProof,
+ mode: "snapshot" | "advance" = "snapshot",
) {
return withCommunityQueryProof(queryClient, proof, (registry) => {
const clock = collectionRows(registry, "readStateClock").find((row) => row.id === "account")?.revision ?? -1
const current = collectionRows(registry, "readStates").find((row) => row.channelId === readState.channelId)
- if (clock > revision || (current?.observedRevision ?? -1) >= revision) return "superseded" as const
+ if (clock > revision || (current?.observedRevision ?? -1) > revision
+ || (mode === "snapshot" ? (current?.observedRevision ?? -1) === revision : (current?.lastReadSeq ?? -1) >= readState.lastReadSeq)) return "superseded" as const
upsertRows(registry, "readStates", [{ ...readState, observedRevision: revision }])
- projectConfirmedAttention(registry)
+ projectConfirmedAttention(registry, new Set([readState.channelId]))
return "published" as const
})
}
@@ -1153,7 +1106,7 @@ function serverSummaryRows(registry: CommunityDbRegistry, summaries: readonly Pi
const existing = existingById.get(server.id)
return {
description: "", ownerId: "", icon: null, official: false, isOwner: false,
- unread: false, mentions: 0, detailComplete: false, ...existing,
+ detailComplete: false, ...existing,
id: server.id, position: existing?.position ?? position,
name: server.name, discriminator: server.discriminator,
}
@@ -1189,10 +1142,9 @@ function ingestAttentionIncluded(
type: "dm",
position: existing?.position ?? position,
muted: existing?.muted ?? false,
- unread: true,
+
lastMessageAt: dm.lastMessageAt,
preview: existing?.preview ?? "",
- lastUnreadSeq: dm.lastUnreadSeq,
}, existing)
})
upsertRows(registry, "channels", dmChannels)
@@ -1220,7 +1172,7 @@ function ingestAttentionIncluded(
for (const [channelId, messages] of byChannel) ingestMessages(registry, channelId, messages)
}
-type AttentionDomain = "channels" | "dms" | "mentions"
+export type AttentionDomain = "channels" | "dms" | "mentions"
type AttentionFloor = {
throughSeq: number
clearedCount: number
@@ -1288,14 +1240,8 @@ function attentionIntentActive(registry: CommunityDbRegistry, intent: AttentionI
&& registry.queryClient.getQueryCache().find({ queryKey: communityKeys.communityDbCollection(registry.scopeId, "attentionItems"), exact: true }) === intent.itemsQuery
}
-function confirmedAttentionProjection(registry: CommunityDbRegistry, scopes: AttentionScopeRow[], items: AttentionItemRow[]) {
+function confirmedAttentionProjection(registry: CommunityDbRegistry, scopes: AttentionScopeRow[], items: AttentionItemRow[], changedReads: ReadonlySet<string> = new Set()) {
const readSeq = new Map(collectionRows(registry, "readStates").map((row) => [row.channelId, row.lastReadSeq]))
- const unreadProjection = getAccountUnreadProjection(registry.queryClient, registry.accountId ?? "__anonymous__")
- const floorFor = (channelId: string) => {
- const canonical = readSeq.get(channelId)
- const confirmed = unreadProjection.getConfirmedReadSeq(channelId)
- return confirmed === undefined ? canonical : Math.max(canonical ?? 0, confirmed)
- }
const scopeById = new Map(scopes.map((scope) => [scope.scopeId, scope]))
const messages = new Map(collectionRows(registry, "messages").map((message) => [message.id, message]))
const removedByScope = new Map<string, number>()
@@ -1306,7 +1252,7 @@ function confirmedAttentionProjection(registry: CommunityDbRegistry, scopes: Att
const message = item.messageId ? messages.get(item.messageId) : undefined
const channelId = item.readTarget?.channelId ?? scope?.channelId
const seq = item.readTarget?.seq ?? (message?.channelId === channelId ? message?.seq : undefined)
- const floor = channelId ? floorFor(channelId) : undefined
+ const floor = channelId ? readSeq.get(channelId) : undefined
const removed = seq !== undefined && floor !== undefined && seq <= floor
if (item.scopeId && (item.kind === "mention" || item.kind === "reply")) {
const counts = removed ? removedByScope : survivingByScope
@@ -1315,15 +1261,15 @@ function confirmedAttentionProjection(registry: CommunityDbRegistry, scopes: Att
return !removed
})
const nextScopes = scopes.flatMap((scope): AttentionScopeRow[] => {
- const floor = floorFor(scope.channelId)
- if (floor === undefined) return [scope]
+ const floor = readSeq.get(scope.channelId)
+ if (floor === undefined) return [changedReads.has(scope.channelId) ? { ...scope, unreadCount: undefined } : scope]
const ordinaryUnread = scope.ordinaryUnread && scope.lastUnreadSeq > floor
const remaining = scope.lastAttentionSeq != null && scope.lastAttentionSeq <= floor
? 0
: Math.max(0, scope.attentionCount - (removedByScope.get(scope.scopeId) ?? 0))
const attentionCount = Math.min(scope.attentionCount, Math.max(remaining, survivingByScope.get(scope.scopeId) ?? 0))
if (!ordinaryUnread && attentionCount === 0) return []
- return [{ ...scope, ordinaryUnread, attentionCount, lastAttentionSeq: attentionCount === 0 ? null : scope.lastAttentionSeq }]
+ return [{ ...scope, ordinaryUnread, attentionCount, ...(changedReads.has(scope.channelId) ? { unreadCount: undefined } : {}), lastAttentionSeq: attentionCount === 0 ? null : scope.lastAttentionSeq }]
})
return { scopes: nextScopes, items: nextItems }
}
@@ -1342,11 +1288,11 @@ function writeAttentionProjection(registry: CommunityDbRegistry, scopes: Attenti
return { nextScopes, previousScopes }
}
-export function projectConfirmedAttention(registry: CommunityDbRegistry) {
+function projectConfirmedAttention(registry: CommunityDbRegistry, changedReads: ReadonlySet<string> = new Set()) {
notifyManager.batch(() => {
const scopes = collectionRows(registry, "attentionScopes")
const items = collectionRows(registry, "attentionItems")
- writeAttentionProjection(registry, scopes, items, confirmedAttentionProjection(registry, scopes, items))
+ writeAttentionProjection(registry, scopes, items, confirmedAttentionProjection(registry, scopes, items, changedReads))
})
}
@@ -1359,6 +1305,7 @@ function attentionProjection(
const confirmed = confirmedAttentionProjection(registry, scopes, items)
scopes = confirmed.scopes
items = confirmed.items
+ const readSeqs = new Map(collectionRows(registry, "readStates").map(row => [row.channelId, row.lastReadSeq]))
const floors = new Map<string, { ordinary: number; mentions: number; cleared: number }>()
const itemIds = new Set<string>()
for (const intent of intents) {
@@ -1398,7 +1345,7 @@ function attentionProjection(
)
const attentionCount = Math.max(0, Math.min(scope.attentionCount, remaining) - (removedByScope.get(scope.scopeId) ?? 0))
if (!ordinaryUnread && attentionCount === 0) return []
- return [{ ...scope, ordinaryUnread, lastAttentionSeq: attentionCount === 0 ? null : lastAttentionSeq, attentionCount }]
+ return [{ ...scope, ordinaryUnread, ...(floor && floor.ordinary > (readSeqs.get(scope.channelId) ?? -1) ? { unreadCount: undefined } : {}), lastAttentionSeq: attentionCount === 0 ? null : lastAttentionSeq, attentionCount }]
})
return { scopes: nextScopes, items: nextItems }
}
@@ -1853,6 +1800,7 @@ export function publishCommunityLiveSnapshot(
}
switch (snapshot.kind) {
case "servers":
+ for (const server of snapshot.data.servers) registry.runtime.ws.actions.grantServerAccess(server.id)
ingestServers(registry, snapshot.data)
break
case "server-detail":
@@ -2051,7 +1999,7 @@ export function publishCommunityForumSidebar(
parentMessageId: channel.parentMessageId,
creatorId: channel.creatorId ?? existing?.creatorId ?? null,
archived: channel.archived === true || channel.archived === 1,
- unread: channel.unread,
+
lastMessageAt: channel.lastMessageAt ?? channel.activityAt,
}, existing)]
})
@@ -2115,14 +2063,8 @@ export function publishCommunityForumSidebar(
&& row.userId === viewerId
&& row.relation === "notify",
)
- if (disposition === "genuine-negative") {
- patchRows(
- registry,
- "channels",
- (row) => ({ ...row, unread: false }),
- (row) => row.id === id,
- )
- }
+ retireCommunityNotificationScope(registry, id)
+
}
})
return "published" as const
@@ -2420,6 +2362,13 @@ export function patchCanonicalCommunityMessage(
))
}
+function retireCommunityNotificationScope(registry: CommunityDbRegistry, channelId: string) {
+ const scope = collectionRows(registry, "attentionScopes").find(row => row.channelId === channelId)
+ if (!scope) return
+ if (scope.attentionCount === 0) deleteRows(registry, "attentionScopes", row => row.channelId === channelId, [scope.scopeId])
+ else patchRows(registry, "attentionScopes", row => ({ ...row, ordinaryUnread: false, unreadCount: 0 }), row => row.channelId === channelId, [scope.scopeId], ["ordinaryUnread", "unreadCount"])
+}
+
export function removeCanonicalCommunityChannelMembership(
queryClient: QueryClient,
channelId: string,
@@ -2427,13 +2376,10 @@ export function removeCanonicalCommunityChannelMembership(
) {
const registry = getCommunityDbRegistry(queryClient)
if (!registry?.accountId) return false
- deleteRows(
- registry,
- "channelMemberships",
- (row) => row.channelId === channelId
- && row.userId === registry.accountId
- && row.relation === relation,
- )
+ withCanonicalWriteContext(queryClient, { kind: "event" }, () => {
+ deleteRows(registry, "channelMemberships", row => row.channelId === channelId && row.userId === registry.accountId && row.relation === relation)
+ if (relation === "notify") retireCommunityNotificationScope(registry, channelId)
+ })
return true
}
@@ -2457,6 +2403,7 @@ export function setCanonicalCommunityChannelMember(queryClient: QueryClient, cha
const write = () => {
if (!present) {
deleteRows(registry, "channelMemberships", (row) => row.id === id, [id])
+ if (userId === registry.accountId && relation === "notify") retireCommunityNotificationScope(registry, channelId)
return true
}
const previous = collectionRows(registry, "channelMemberships").find((row) => row.id === id)
@@ -2506,13 +2453,6 @@ export function purgeCommunityServer(registry: CommunityDbRegistry, serverId: st
for (const id of removedChannelIds) registry.runtime.ws.actions.revokeChannelAccess(serverId, id)
clearChannelTransientState(registry, removedChannelIds, serverId)
pruneInboxCaches(registry.queryClient, removedChannelIds, serverId)
- getAccountUnreadProjection(
- registry.queryClient,
- registry.accountId ?? "__anonymous__",
- ).retireAccessScope({
- kind: "server",
- serverId,
- })
clearLastChannel(serverId)
registry.runtime.ws.actions.revokeServerAccess(serverId)
void registry.retireReadingDisk(removedChannelIds).catch((error: unknown) => console.error("Server cache retirement failed", error))
@@ -2607,8 +2547,8 @@ export function retireCommunityChannelReading(
.catch((error: unknown) => console.error("Channel cache retirement failed", error))
if (options.clearTransient !== false) clearChannelTransientState(registry, removed, serverId, options.preserveQuery, options)
withCanonicalWriteContext(registry.queryClient, { kind: "event" }, () => notifyManager.batch(() => {
- patchRows(registry, "channels", (row) => ({ ...row, preview: "", unread: false, baseUnread: false, lastUnreadSeq: undefined }),
- (row) => removed.has(row.id), removed, ["preview", "unread", "baseUnread", "lastUnreadSeq"])
+ patchRows(registry, "channels", (row) => ({ ...row, preview: "" }),
+ (row) => removed.has(row.id), removed, ["preview"])
deleteRows(registry, "messages", (row) => removed.has(row.channelId))
deleteRows(registry, "readStates", (row) => removed.has(row.channelId))
deleteRows(registry, "attentionScopes", (row) => removed.has(row.channelId))
@@ -2939,30 +2879,6 @@ export function projectCommunityWsEventToDb(
Object.keys(event.changes),
)
return
- case "community:unread.bump":
- if (event.userId !== registry.accountId) return
- patchRows(
- registry,
- "channels",
- (row) => ({ ...row, unread: true }),
- (row) => row.id === event.channelId || row.id === event.railChannelId,
- [event.channelId, event.railChannelId]
- .filter((channelId): channelId is string => Boolean(channelId)),
- )
- if (event.serverId) {
- patchRows(
- registry,
- "servers",
- (row) => ({
- ...row,
- unread: true,
- mentions: row.mentions + (event.isMention ? 1 : 0),
- }),
- (row) => row.id === event.serverId,
- [event.serverId],
- )
- }
- return
case "community:status.update":
projectProfilePatch(registry, event.userId, {
status: {
diff --git a/src/web/src/lib/community/forum-sidebar.ts b/src/web/src/lib/community/forum-sidebar.ts
index dddce7779..8f554e892 100644
--- a/src/web/src/lib/community/forum-sidebar.ts
+++ b/src/web/src/lib/community/forum-sidebar.ts
@@ -1,7 +1,7 @@
import { compareAsciiSqliteBinary, FORUM_ARCHIVE_TAG } from "@alook/shared"
-import type { ChannelMembershipRow, ChannelRow, MessageRow } from "@/lib/community-db/schema"
+import type { AttentionScopeRow, ChannelMembershipRow, ChannelRow, MessageRow } from "@/lib/community-db/schema"
-export type ForumSidebarThread = Pick<ChannelRow, "id" | "unread"> & {
+export type ForumSidebarThread = Pick<ChannelRow, "id"> & { unread: boolean } & {
parentChannelId: string
parentMessageId: string
title: string
@@ -23,7 +23,7 @@ export function compareForumSidebarThreads(left: ForumSidebarThread, right: Foru
export function forumSidebarCandidates(
channels: readonly ChannelRow[], memberships: readonly ChannelMembershipRow[], messages: readonly MessageRow[],
- viewerId: string | null, serverId: string,
+ viewerId: string | null, serverId: string, attention: readonly AttentionScopeRow[] = [],
) {
const participating = viewerNotifyChannelIds(memberships, viewerId)
const messageById = new Map(messages.map((message) => [message.id, message]))
@@ -36,17 +36,15 @@ export function forumSidebarCandidates(
const activityAt = channel.lastMessageAt ?? "", activityMs = Date.parse(activityAt)
const expiresAt = Number.isFinite(activityMs) ? new Date(activityMs + FORUM_SIDEBAR_ACTIVITY_WINDOW_MS).toISOString() : activityAt
return [{ id: channel.id, parentChannelId: channel.parentChannelId, parentMessageId: channel.parentMessageId,
- title: messageById.get(channel.parentMessageId)?.content ?? channel.name ?? "", activityAt, expiresAt, unread: channel.unread }]
+ title: messageById.get(channel.parentMessageId)?.content ?? channel.name ?? "", activityAt, expiresAt, unread: attention.some((scope) => scope.scopeId === channel.id && (scope.ordinaryUnread || scope.attentionCount > 0)) }]
}).sort(compareForumSidebarThreads)
}
export function projectForumSidebar(
channels: readonly ChannelRow[], memberships: readonly ChannelMembershipRow[], messages: readonly MessageRow[],
- viewerId: string | null, serverId: string, retainId: string | null, serverNowMs: number,
+ viewerId: string | null, serverId: string, retainId: string | null, serverNowMs: number, attention: readonly AttentionScopeRow[] = [],
) {
- const parents = channels.filter((channel) => channel.serverId === serverId && channel.type === "forum")
- const parentIds = new Set(parents.map((channel) => channel.id))
- const candidates = forumSidebarCandidates(channels, memberships, messages, viewerId, serverId)
+ const candidates = forumSidebarCandidates(channels, memberships, messages, viewerId, serverId, attention)
.filter((thread) => thread.id === retainId || !Number.isFinite(Date.parse(thread.expiresAt)) || Date.parse(thread.expiresAt) > serverNowMs)
const byParent = new Map<string, ForumSidebarThread[]>()
for (const thread of candidates) {
@@ -59,12 +57,9 @@ export function projectForumSidebar(
if (!retained || siblings.slice(0, 5).some((thread) => thread.id === retainId)) return siblings.slice(0, 5)
return [...siblings.filter((thread) => thread.id !== retainId).slice(0, 4), retained].sort(compareForumSidebarThreads)
})
- const renderedIds = new Set(threads.map((thread) => thread.id))
- const parentUnread: Record<string, boolean> = {}
- for (const parent of parents) parentUnread[parent.id] = parent.baseUnread ?? parent.unread
- for (const child of channels) {
- if (child.serverId === serverId && child.type === "thread" && child.unread && child.parentChannelId
- && parentIds.has(child.parentChannelId) && !renderedIds.has(child.id)) parentUnread[child.parentChannelId] = true
+ const parentUnread: Record<string, boolean> = Object.fromEntries(channels.filter(channel => channel.serverId === serverId && channel.type !== "thread").map(channel => [channel.id, false]))
+ for (const scope of attention) {
+ if (scope.serverId === serverId && (scope.ordinaryUnread || scope.attentionCount > 0)) parentUnread[scope.parentChannelId ?? scope.channelId] = true
}
return { threads, parentUnread }
}
diff --git a/src/web/src/lib/community/message-read-projection.test.ts b/src/web/src/lib/community/message-read-projection.test.ts
index 244ae77a9..52bb9b59b 100644
--- a/src/web/src/lib/community/message-read-projection.test.ts
+++ b/src/web/src/lib/community/message-read-projection.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest"
-import { resolveMessageReadProjection } from "./message-read-projection"
+import { resolveMessageReadProjection, resolveUnreadMessageCount } from "./message-read-projection"
const messages = [
{ id: "self", authorId: "viewer" },
@@ -57,3 +57,13 @@ describe("resolveMessageReadProjection", () => {
})).toEqual({ newDividerBefore: "peer", anchorFound: true })
})
})
+
+
+describe("qualified unread message counts", () => {
+ const count = (input: Partial<Parameters<typeof resolveUnreadMessageCount>[0]> = {}) => resolveUnreadMessageCount({ messages: [{ seq: 2 }, { seq: 5 }, { seq: 9 }], lastReadSeq: 2, latestSeq: 9, historyStartKnown: false, hasMoreNewer: false, ...input })
+ it("counts actual messages across sequence gaps", () => { expect(count()).toBe(2); expect(count({ lastReadSeq: 5 })).toBe(1) })
+ it("uses the proven history start when the old cursor was deleted", () => { expect(count({ lastReadSeq: 1, historyStartKnown: true })).toBe(3) })
+ it("does not invent a count beyond an unloaded read boundary or tail", () => { expect(count({ lastReadSeq: 1 })).toBeUndefined(); expect(count({ hasMoreNewer: true })).toBeUndefined(); expect(count({ latestSeq: 10 })).toBeUndefined() })
+ it("requires hydrated message sequences and deduplicates exact rows", () => { expect(count({ messages: [{ seq: 2 }, {}, { seq: 9 }] })).toBeUndefined(); expect(count({ messages: [{ seq: 2 }, { seq: 9 }, { seq: 9 }] })).toBe(1) })
+ it("does not report messages past a fully covered cursor", () => { expect(count({ lastReadSeq: 9, hasMoreNewer: true })).toBe(0) })
+})
diff --git a/src/web/src/lib/community/message-read-projection.ts b/src/web/src/lib/community/message-read-projection.ts
index 3a202b71c..63968fa14 100644
--- a/src/web/src/lib/community/message-read-projection.ts
+++ b/src/web/src/lib/community/message-read-projection.ts
@@ -36,3 +36,18 @@ export function resolveMessageReadProjection({
.find((message) => message.authorId !== viewerUserId)
return { newDividerBefore: firstUnread?.id, anchorFound: true }
}
+
+export function resolveUnreadMessageCount({ messages, lastReadSeq, latestSeq, historyStartKnown, hasMoreNewer }: {
+ messages: readonly { seq?: number }[]
+ lastReadSeq: number
+ latestSeq: number
+ historyStartKnown: boolean
+ hasMoreNewer: boolean
+}): number | undefined {
+ if (latestSeq <= lastReadSeq) return 0
+ if (hasMoreNewer || messages.some(message => message.seq === undefined)) return undefined
+ if (!historyStartKnown && !messages.some(message => message.seq! <= lastReadSeq)) return undefined
+ const seqs = new Set(messages.flatMap(message => message.seq! > lastReadSeq ? [message.seq!] : []))
+ if (!seqs.has(latestSeq)) return undefined
+ return seqs.size
+}
diff --git a/src/web/src/lib/query-persister.race.test.ts b/src/web/src/lib/query-persister.race.test.ts
index e7348a4bd..1bc17495b 100644
--- a/src/web/src/lib/query-persister.race.test.ts
+++ b/src/web/src/lib/query-persister.race.test.ts
@@ -145,6 +145,7 @@ function readingSnapshot(user: string): PersistedClient {
const queryClient = new QueryClient()
const setRows = (name: string, rows: unknown[]) => queryClient.setQueryData(communityKeys.communityDbCollection(user, name), rows)
setRows("channels", ["dm-A", "dm-B"].map((id) => canonicalChannelRow({ id, type: "dm", name: id, preview: `body-${id}`, unread: true })))
+ setRows("attentionScopes", ["dm-A", "dm-B"].map(channelId => ({ scopeId: channelId, channelId, serverId: null, parentChannelId: null, ordinaryUnread: true, lastUnreadSeq: 1, attentionCount: 0, lastAttentionSeq: null })))
setRows("messages", ["dm-A", "dm-B"].map((channelId) => ({ id: `m-${channelId}`, channelId, type: "chat", resourceComplete: false, authorId: user, authorName: "Viewer", authorAvatar: "V", authorAvatarVersion: 0, seq: 1, content: `body-${channelId}` })))
setRows("channelMemberships", ["dm-A", "dm-B"].map((channelId) => ({ id: `${channelId}:peer:access`, channelId, userId: "peer", relation: "access" })))
return { timestamp: Date.now(), buster: PERSIST_BUSTER, clientState: dehydrate(queryClient) }
@@ -224,9 +225,11 @@ describe("native channel persistence fence", () => {
const restored = await otherDocument.createIdbPersister(user).restoreClient()
expect(readingRows(restored, "messages")?.map((row) => row.channelId)).toEqual(["dm-B"])
expect(readingRows(restored, "channels")).toEqual(expect.arrayContaining([
- expect.objectContaining({ id: "dm-A", preview: "", unread: false }),
- expect.objectContaining({ id: "dm-B", preview: "body-dm-B", unread: true }),
+ expect.objectContaining({ id: "dm-A", preview: "" }),
+ expect.objectContaining({ id: "dm-B", preview: "body-dm-B" }),
]))
+ expect(readingRows(restored, "channels")?.every(row => !("unread" in row))).toBe(true)
+ expect(readingRows(restored, "attentionScopes")?.map(row => row.channelId)).toEqual(["dm-B"])
expect(readingRows(restored, "channelMemberships")).toHaveLength(2)
const fresh = otherDocument.createIdbPersister(user)
await fresh.persistClient(before)
diff --git a/src/web/src/lib/query-persister.ts b/src/web/src/lib/query-persister.ts
index 0ff4d1ced..5348262e4 100644
--- a/src/web/src/lib/query-persister.ts
+++ b/src/web/src/lib/query-persister.ts
@@ -132,7 +132,7 @@ function scrubDehydratedClient(
const fence = retired.get(row.id)
if (!fence) return [row]
return row.type === "dm" && !fence.deleted
- ? [{ ...row, preview: "", unread: false, baseUnread: false, lastUnreadSeq: undefined }]
+ ? [{ ...row, preview: "" }]
: []
})
const attentionScopes = rows("attentionScopes").filter((row) => !retired.has(row.channelId))
diff --git a/src/web/src/stores/community/runtime-owner.ts b/src/web/src/stores/community/runtime-owner.ts
index 89f72f335..e1bcebf4e 100644
--- a/src/web/src/stores/community/runtime-owner.ts
+++ b/src/web/src/stores/community/runtime-owner.ts
@@ -26,3 +26,10 @@ export function readCurrentCommunityChannelMeta(queryClient: QueryClient) {
const id = registry.runtime.ui.get().currentChannelId
return id ? registry.collections.channels.get(id) ?? null : null
}
+
+export function bindCommunityTransport(runtime: CommunityRuntime, send: (message: object) => void) {
+ const transport = runtime.transport
+ if (transport.send !== null && transport.send !== send) console.warn("[useCommunityWs] Multiple instances detected — mount this hook once at the tree root.")
+ transport.send = send
+ return () => { if (transport.send === send) transport.send = null }
+}
diff --git a/src/web/src/stores/community/runtime.tsx b/src/web/src/stores/community/runtime.tsx
index 8f5ab1a0d..aa92c1d61 100644
--- a/src/web/src/stores/community/runtime.tsx
+++ b/src/web/src/stores/community/runtime.tsx
@@ -3,7 +3,7 @@
import { createStoreContext } from "@tanstack/react-store"
import type { CommunityRuntime } from "./runtime-owner"
export type { CommunityRuntime } from "./runtime-owner"
-export { getCommunityRuntime, readCurrentCommunityChannelMeta } from "./runtime-owner"
+export { bindCommunityTransport, getCommunityRuntime, readCurrentCommunityChannelMeta } from "./runtime-owner"
const { StoreProvider, useStoreContext } = createStoreContext<{ runtime: CommunityRuntime }>()
export const CommunityRuntimeProvider = StoreProvider
diff --git a/src/web/src/stores/community/ws-store.ts b/src/web/src/stores/community/ws-store.ts
index 67f81fe58..f5925ec38 100644
--- a/src/web/src/stores/community/ws-store.ts
+++ b/src/web/src/stores/community/ws-store.ts
@@ -97,6 +97,17 @@ const initialState = (): Pick<
seenDeliveryOperations: new Map(),
})
+export function communityScopeAllowsAccess(
+ state: Pick<CommunityWsStoreState, "revokedServerIds" | "channelAccessScopes">,
+ scope: { serverId?: string | null; channelId?: string; parentChannelId?: string | null },
+) {
+ const channel = scope.channelId ? state.channelAccessScopes.get(scope.channelId) : undefined
+ const serverId = scope.serverId ?? channel?.serverId
+ const parentId = scope.parentChannelId ?? channel?.parentChannelId
+ return !((serverId && state.revokedServerIds.has(serverId))
+ || channel?.revoked || (parentId && state.channelAccessScopes.get(parentId)?.revoked))
+}
+
export function createCommunityWsStore(viewerId: string | null) {
const store = createStore(initialState(), ({ setState, get }): Omit<CommunityWsStoreState, keyof ReturnType<typeof initialState>> => {
const writePresence = (
diff --git a/src/web/src/test/architecture/community-read-state-writer-contract.test.ts b/src/web/src/test/architecture/community-read-state-writer-contract.test.ts
index 176ddb5a0..256157f23 100644
--- a/src/web/src/test/architecture/community-read-state-writer-contract.test.ts
+++ b/src/web/src/test/architecture/community-read-state-writer-contract.test.ts
@@ -104,26 +104,18 @@ describe("human account read-state writer contract", () => {
])
})
- it("keeps the account unread ledger synchronous and I/O-free", () => {
- const projection = source(
- "src/web/src/hooks/community/account-unread-projection.ts",
- )
- expect(projection).not.toMatch(/\b(?:apiFetch|fetch|setTimeout|setInterval)\s*\(/)
- expect(projection).not.toMatch(
- /queryClient\.(?:setQueryData|invalidateQueries|fetchQuery|query|fetchInfiniteQuery|infiniteQuery|refetchQueries|cancelQueries)\s*\(/,
- )
- })
-
- it("keeps optimistic unread clearing owned by the visible-row observer", () => {
+ it("keeps read and reservation projections in the existing native owners", () => {
const webSourceRoot = resolve(repositoryRoot, "src/web/src")
const owners = walkTypeScript(webSourceRoot)
.filter((path) => !path.includes("/test/") && !path.endsWith(".test.ts"))
- .filter((path) => /\.recordOptimisticRead\s*\(/.test(readFileSync(path, "utf8")))
+ .filter((path) => /\bclearAttentionScopeOptimistically\s*\(/.test(readFileSync(path, "utf8")))
.map((path) => relative(repositoryRoot, path).replaceAll("\\", "/"))
.sort()
expect(owners).toEqual([
- "src/web/src/hooks/community/use-read-observer.ts",
+ "src/web/src/hooks/community/inbox-read-reservation.ts",
+ "src/web/src/hooks/community/read-coordinator.ts",
+ "src/web/src/lib/community-db/sync.ts",
])
})
diff --git a/src/web/src/test/architecture/community-unread-projection-owner-contract.test.ts b/src/web/src/test/architecture/community-unread-projection-owner-contract.test.ts
index bc96ce7be..6c1add991 100644
--- a/src/web/src/test/architecture/community-unread-projection-owner-contract.test.ts
+++ b/src/web/src/test/architecture/community-unread-projection-owner-contract.test.ts
@@ -1,5 +1,5 @@
import { readdirSync, readFileSync } from "node:fs"
-import { relative, resolve } from "node:path"
+import { resolve } from "node:path"
import { fileURLToPath } from "node:url"
import { describe, expect, it } from "vitest"
@@ -19,18 +19,14 @@ function walkTypeScript(directory: string, files: string[] = []): string[] {
}
describe("community unread projection owner contract", () => {
- it("creates the authenticated account owner only at the query boundary", () => {
- const webSourceRoot = resolve(repositoryRoot, "src/web/src")
- const constructors = walkTypeScript(webSourceRoot)
- .filter((path) => !path.includes("/test/") && !path.endsWith(".test.ts"))
- .filter((path) => /new AccountUnreadProjection\s*\(/.test(readFileSync(path, "utf8")))
- .map((path) => relative(repositoryRoot, path).replaceAll("\\", "/"))
-
- expect(constructors).toEqual([
- "src/web/src/hooks/community/account-unread-projection.ts",
- ])
- expect(source("src/web/src/app/c/QueryProvider.tsx"))
- .toContain("getAccountUnreadProjection(queryClient, userId)")
+ it("keeps every unread fact in canonical DB instead of a parallel owner", () => {
+ const production = walkTypeScript(resolve(repositoryRoot, "src/web/src"))
+ .filter((path) => !path.includes("/test/") && !/\.test\.tsx?$/.test(path))
+ for (const path of production) expect(readFileSync(path, "utf8")).not.toContain("account-unread-projection")
+ const schema = source("src/web/src/lib/community-db/schema.ts")
+ expect(schema).not.toMatch(/(?:unread|baseUnread|lastUnreadSeq|mentions): z\./)
+ expect(source("src/web/src/hooks/community/read-coordinator.ts")).toContain("publishCommunityConversationReadState")
+ expect(source("src/web/src/hooks/community/community-ws/read-state-reconciliation.ts")).not.toContain("setTimeout")
})
it("keeps dot components presentation-only", () => {
diff --git a/src/web/src/test/community-query-owner.ts b/src/web/src/test/community-query-owner.ts
index d92c2d2d6..a6b01f420 100644
--- a/src/web/src/test/community-query-owner.ts
+++ b/src/web/src/test/community-query-owner.ts
@@ -1,8 +1,9 @@
+import { AttentionScopeSchema, AttentionItemSchema } from "@alook/shared"
import { beforeEach } from "vitest"
import { act } from "react"
import { QueryClient, type InfiniteData, type QueryKey, type SetDataOptions, type QueryClientConfig } from "@tanstack/react-query"
import { createCommunityDbRegistry, getCommunityDbRegistry, type CommunityDbRegistry } from "@/lib/community-db/collections"
-import { ingestMessages } from "@/lib/community-db/sync"
+import { ingestMessages, ingestAttentionSnapshot } from "@/lib/community-db/sync"
import type { MessagesPage } from "@/hooks/community/use-messages"
import { getCommunityRuntime } from "@/stores/community/runtime"
import { communityKeys } from "@/lib/query-keys"
@@ -52,3 +53,9 @@ beforeEach(() => async () => {
if (typeof document === "undefined") await retire()
else await act(retire)
})
+
+export function seedCommunityAttentionScope(client: QueryClient, input: { channelId: string; serverId?: string | null; parentChannelId?: string | null; seq?: number; ordinaryUnread?: boolean; attentionCount?: number }) {
+ const registry = getCommunityDbRegistry(client)!
+ const scope = { scopeId: input.channelId, channelId: input.channelId, serverId: input.serverId ?? null, parentChannelId: input.parentChannelId ?? null, lastUnreadSeq: input.seq ?? 1, ordinaryUnread: input.ordinaryUnread ?? true, attentionCount: input.attentionCount ?? 0, lastAttentionSeq: input.attentionCount ? input.seq ?? 1 : null }
+ ingestAttentionSnapshot(registry, { scopes: [...[...registry.collections.attentionScopes.values()].filter(row => row.channelId !== input.channelId).map(row => AttentionScopeSchema.strip().parse(row)), scope], items: [...registry.collections.attentionItems.values()].map(row => AttentionItemSchema.strip().parse(row)), limit: 100, truncated: false, included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } })
+}
diff --git a/src/web/src/test/e2e-ui/16-jump-to-present.spec.ts b/src/web/src/test/e2e-ui/16-jump-to-present.spec.ts
index a5d042f12..17404bfa6 100644
--- a/src/web/src/test/e2e-ui/16-jump-to-present.spec.ts
+++ b/src/web/src/test/e2e-ui/16-jump-to-present.spec.ts
@@ -33,8 +33,10 @@ test("anchored channel jumps to the newest tail with one request", async ({ case
const { page } = await asUser("alice")
await page.goto(`/c/channels/${serverId}/${channelId}`)
await expect(page.getByTestId(tid.message(anchorId))).toBeVisible({ timeout: 30_000 })
- const jumpButton = page.getByRole("button", { name: /^Jump to present, \d+ unread below$/ })
+ const jumpButton = page.getByRole("button", { name: "Jump to present", exact: true })
await expect(jumpButton).toBeVisible({ timeout: 20_000 })
+ await expect(jumpButton).toHaveAttribute("data-testid", tid.scrollToPresent)
+ await expect(jumpButton).toHaveText("Jump to present")
let newestGets = 0
let anchorGets = 0
diff --git a/src/web/src/test/e2e-ui/22-committed-message-delivery.spec.ts b/src/web/src/test/e2e-ui/22-committed-message-delivery.spec.ts
index d85818747..5d13c1ee8 100644
--- a/src/web/src/test/e2e-ui/22-committed-message-delivery.spec.ts
+++ b/src/web/src/test/e2e-ui/22-committed-message-delivery.spec.ts
@@ -244,10 +244,10 @@ test.describe("committed message delivery QA", () => {
let armed = false
let duplicated = false
const body = `atomic duplicate ${Date.now()}`
- const serverRequests: string[] = []
+ const attentionRequests: string[] = []
bob.page.on("request", (request) => {
- if (new URL(request.url()).pathname === "/api/community/servers") {
- serverRequests.push(request.url())
+ if (new URL(request.url()).pathname === "/api/community/users/me/attention") {
+ attentionRequests.push(request.url())
}
})
const proxy = await proxyCommunityWebSockets(bob.context, { decide: (frame) => {
@@ -293,7 +293,7 @@ test.describe("committed message delivery QA", () => {
expect(messageId).toBeTruthy()
await expect(bob.page.getByTestId(tid.message(messageId!))).toHaveCount(1)
- const requestsBeforeReload = serverRequests.length
+ const requestsBeforeReload = attentionRequests.length
const pendingReloadRequests = new Set<Request>()
const reloadFailures: string[] = []
let reloadCommitted = false
@@ -303,14 +303,14 @@ test.describe("committed message delivery QA", () => {
}
const trackReloadRequest = (request: Request) => {
if (reloadCommitted && request.method() === "GET"
- && new URL(request.url()).pathname === "/api/community/servers") {
+ && new URL(request.url()).pathname === "/api/community/users/me/attention") {
pendingReloadRequests.add(request)
}
}
const finishReloadRequest = (request: Request) => {
if (!pendingReloadRequests.has(request)) return
void request.response().then(async (response) => {
- if (!response) throw new Error("Reload servers response missing")
+ if (!response) throw new Error("Reload attention response missing")
const failure = await response.finished()
if (response.status() !== 200 || failure !== null) {
reloadFailures.push(`HTTP ${response.status()}: ${failure?.message ?? "unexpected status"}`)
@@ -323,7 +323,7 @@ test.describe("committed message delivery QA", () => {
}
const failReloadRequest = (request: Request) => {
if (!pendingReloadRequests.delete(request)) return
- reloadFailures.push(request.failure()?.errorText ?? "Reload servers request failed")
+ reloadFailures.push(request.failure()?.errorText ?? "Reload attention request failed")
}
bob.page.on("framenavigated", trackReloadCommit)
bob.page.on("request", trackReloadRequest)
@@ -333,7 +333,7 @@ test.describe("committed message delivery QA", () => {
await gotoAfterUserWsAuth(bob.page, `/c/channels/${serverId}/${channelId}`)
await expect(bob.page.getByTestId(tid.message(messageId!))).toHaveCount(1)
await expect.poll(() => ({
- requestsIncreased: serverRequests.length > requestsBeforeReload,
+ requestsIncreased: attentionRequests.length > requestsBeforeReload,
responseCompleted: completedReloadRequests > 0,
pending: pendingReloadRequests.size,
failures: reloadFailures,
@@ -346,9 +346,9 @@ test.describe("committed message delivery QA", () => {
bob.page.off("requestfinished", finishReloadRequest)
bob.page.off("requestfailed", failReloadRequest)
}
- const requestsBeforeReplay = serverRequests.length
+ const requestsBeforeReplay = attentionRequests.length
proxy.replay(batch)
- await expect.poll(() => serverRequests.length, { timeout: 20_000 })
+ await expect.poll(() => attentionRequests.length, { timeout: 20_000 })
.toBeGreaterThan(requestsBeforeReplay)
await expect(bob.page.getByTestId(tid.message(messageId!))).toHaveCount(1)
})
diff --git a/src/web/src/test/e2e-ui/40-mobile-server-header-hierarchy.spec.ts b/src/web/src/test/e2e-ui/40-mobile-server-header-hierarchy.spec.ts
index 76b44da29..7640bfb81 100644
--- a/src/web/src/test/e2e-ui/40-mobile-server-header-hierarchy.spec.ts
+++ b/src/web/src/test/e2e-ui/40-mobile-server-header-hierarchy.spec.ts
@@ -228,19 +228,13 @@ test.describe("mobile server header direct hierarchy", () => {
const expectStartupFinished = async (generation: StartupPhase, paths: string[]) => {
await expect.poll(() => {
const records = [...startupRequests].map(([request, record]) => ({ ...record, timing: request.timing() }))
- const readStateEnd = Math.max(-1, ...records.filter((record) => record.phase === "authenticated"
- && record.pathname === readStatePath && record.method === "GET"
- && record.terminal === "finished" && record.status === 200 && record.timing.responseEnd >= 0)
- .map((record) => record.timing.startTime + record.timing.responseEnd))
return {
failed: records.filter((record) => record.terminal === "failed"
|| (record.status !== undefined && (record.status < 200 || record.status >= 300))),
pending: records.filter((record) => record.terminal === "pending"),
missing: paths.filter((pathname) => !records.some((record) => record.phase === generation
&& record.pathname === pathname && record.method === "GET"
- && record.terminal === "finished" && record.status === 200
- && (generation === "initial" || !directoryPaths.includes(pathname)
- || (readStateEnd >= 0 && record.timing.startTime >= readStateEnd)))),
+ && record.terminal === "finished" && record.status === 200)),
}
}).toEqual({ failed: [], pending: [], missing: [] })
}
@@ -252,17 +246,20 @@ test.describe("mobile server header direct hierarchy", () => {
expect(await threadComposer.isVisible()).toBe(true)
}).toPass({ timeout: 20_000 })
await expectMobileBack(page)
- // RULE: Cold HTTP reads and first-auth read-state/directory reconciliation
+ // RULE: Cold HTTP reads and first-auth read-state/attention reconciliation
// must finish before the all-community resize measurement begins.
- await expectStartupFinished("initial", ["/api/community/users/me/attention", ...directoryPaths])
+ const canonicalPaths = [readStatePath, "/api/community/users/me/attention"]
+ await expectStartupFinished("initial", [...canonicalPaths, ...directoryPaths])
await expect.poll(() => proxy.heldConnectionCount()).toBe(1)
expect(proxy.connectionCount()).toBe(1)
phase = "authenticated"
holdAuthentication = false
expect(proxy.releaseHeldConnections((frame) => frame.type === "auth.ok")).toBe(1)
- await expectStartupFinished("authenticated", [readStatePath, ...directoryPaths])
+ await expectStartupFinished("authenticated", canonicalPaths)
await page.waitForLoadState("networkidle")
- await expectStartupFinished("authenticated", [readStatePath, ...directoryPaths])
+ await expectStartupFinished("authenticated", canonicalPaths)
+ expect([...startupRequests.values()].filter(record => record.phase === "authenticated"
+ && directoryPaths.includes(record.pathname))).toEqual([])
expect(proxy.connectionCount()).toBe(1)
await page.evaluate(({ composerTestId, threadPanelTestId }) => {
diff --git a/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts b/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts
index bf5027b88..f764cc360 100644
--- a/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts
+++ b/src/web/src/test/e2e-ui/41-account-unread-projection.spec.ts
@@ -107,7 +107,7 @@ async function readSeq(page: Page, channelId: string): Promise<number> {
return snapshot.readStates.find((row) => row.channelId === channelId)?.lastReadSeq ?? 0
}
-async function expectRailReplacementDoesNotBlockMessages({
+async function expectReadbackDoesNotBlockMessages({
page,
observerGate,
href,
@@ -115,6 +115,7 @@ async function expectRailReplacementDoesNotBlockMessages({
latestText,
inboxRowTestId,
triggerUnread,
+ triggerReadback,
}: {
page: Page
observerGate: Awaited<ReturnType<typeof installReadObserverGate>>
@@ -123,8 +124,13 @@ async function expectRailReplacementDoesNotBlockMessages({
latestText: string
inboxRowTestId: string
triggerUnread: () => Promise<string>
+ triggerReadback: () => Promise<void>
}, caseResources: CaseResources) {
const beforeReadSeq = await readSeq(page, channelId)
+ const latestId = await triggerUnread()
+ await page.getByTestId(tid.inboxTrigger).click()
+ await expect(page.getByTestId(inboxRowTestId)).toBeVisible({ timeout: 30_000 })
+ await page.getByTestId(tid.inboxTrigger).click()
let releaseRailGate!: () => void
const railRelease = new Promise<void>((resolve) => { releaseRailGate = resolve })
caseResources.own(releaseRailGate, async (captured) => { captured() })
@@ -139,16 +145,17 @@ async function expectRailReplacementDoesNotBlockMessages({
releaseRailGate()
if (railRequestHeld) await railSettled
}
- let serverListRequests = 0
+ let readbackRequests = 0
let messagesRequests = 0
- await page.route("**/api/community/servers", async (route) => {
- if (new URL(route.request().url()).pathname !== "/api/community/servers") {
+ const readbackPattern = "**/api/community/users/me/read-state"
+ await page.route(readbackPattern, async (route) => {
+ if (route.request().method() !== "GET") {
await route.continue()
return
}
- serverListRequests += 1
- if (serverListRequests === 1) {
+ readbackRequests += 1
+ if (readbackRequests === 1) {
railRequestHeld = true
markRailHeld()
await railRelease
@@ -170,7 +177,7 @@ async function expectRailReplacementDoesNotBlockMessages({
page.on("request", countMessagesRequest)
try {
- const latestId = await triggerUnread()
+ await triggerReadback()
await railHeld
await page.getByTestId(tid.inboxTrigger).click()
const inboxRow = page.getByTestId(inboxRowTestId)
@@ -183,7 +190,7 @@ async function expectRailReplacementDoesNotBlockMessages({
await inboxRow.click()
const response = await messagesResponse
- expect(serverListRequests).toBeGreaterThanOrEqual(1)
+ expect(readbackRequests).toBeGreaterThanOrEqual(1)
expect(messagesRequests).toBeGreaterThanOrEqual(1)
expect(await readSeq(page, channelId)).toBe(beforeReadSeq)
await releaseRail()
@@ -207,7 +214,7 @@ async function expectRailReplacementDoesNotBlockMessages({
} finally {
await releaseRail()
page.off("request", countMessagesRequest)
- await page.unroute("**/api/community/servers")
+ await page.unroute(readbackPattern)
}
}
@@ -434,7 +441,7 @@ test.setTimeout(180_000)
expect(cursor(dmId)).toBe(beforeCursor(dmId))
})
- test("a held rail server-list request does not block channel or child messages", async ({ caseActors, caseResources }) => {
+ test("a held canonical read-state request does not block channel or child messages", async ({ caseActors, caseResources }) => {
const actors = await caseActors(["alice", "bob"])
const { asUser, userId } = actors
const { memberInfo, seedChannel, seedForumThread, seedJoinServer, seedMessage, seedServer } = actors.seed
@@ -502,33 +509,42 @@ test.setTimeout(180_000)
await alice.page.getByTestId(tid.mentionOption(bobInfo.id)).click()
await triggerComposer.pressSequentially(` ${label}`)
await alice.page.keyboard.press("Enter")
- expect((await response).status()).toBe(201)
+ const sent = await response
+ expect(sent.status()).toBe(201)
+ const body = await sent.json() as { message: { id: string } }
+ return body.message.id
}
- await expectRailReplacementDoesNotBlockMessages({
+ await expectReadbackDoesNotBlockMessages({
page,
observerGate: channelObserverGate,
href: `/c/channels/${channelServer}/${channelId}`,
channelId,
latestText: channelText,
inboxRowTestId: tid.inboxUnreadChannel(channelId),
- triggerUnread: async () => {
- await sendRailMention(`channel rail ${stamp}`)
- return seedMessage("alice", channelId, channelText)
+ triggerUnread: () => seedMessage("alice", channelId, channelText),
+ triggerReadback: async () => {
+ const messageId = await sendRailMention(`channel readback ${stamp}`)
+ expect((await page.request.put(`/api/community/channels/${railTriggerChannel}/read`, {
+ data: { lastReadMessageId: messageId },
+ })).status()).toBe(200)
},
}, caseResources)
await gotoAfterUserWsAuth(childPage, "/c/me")
- await expectRailReplacementDoesNotBlockMessages({
+ await expectReadbackDoesNotBlockMessages({
page: childPage,
observerGate: childObserverGate,
href: `/c/channels/${childServer}/${childId}`,
channelId: childId,
latestText: childText,
inboxRowTestId: tid.inboxUnreadChild(childId),
- triggerUnread: async () => {
- await sendRailMention(`child rail ${stamp}`)
- return seedMessage("alice", childId, childText)
+ triggerUnread: () => seedMessage("alice", childId, childText),
+ triggerReadback: async () => {
+ const messageId = await sendRailMention(`child readback ${stamp}`)
+ expect((await childPage.request.put(`/api/community/channels/${railTriggerChannel}/read`, {
+ data: { lastReadMessageId: messageId },
+ })).status()).toBe(200)
},
}, caseResources)
await childPage.close()
diff --git a/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts b/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts
index fad7c0364..f2e646075 100644
--- a/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts
+++ b/src/web/src/test/e2e-ui/55-message-scroll-characterization.spec.ts
@@ -18,6 +18,7 @@ import {
markScrollTrace,
scrollTraceSelfTest,
startScrollTrace,
+ startAnalyzedScrollTrace,
summarizeScrollTrace,
type ScrollTraceResult,
} from "./_fixtures/scroll-trace"
@@ -894,12 +895,23 @@ test.describe("message scroll characterization", () => {
await newest.dispose()
}
await attachLocalTrace()
+ const finishPassiveTrace = await startAnalyzedScrollTrace(alice.page, {
+ scenario: "passive-append-position-admission",
+ identity: identity(channelId),
+ dataTransitionSource: "overlay-ws",
+ })
+ const attachPassiveTrace = async () => {
+ await finishPassiveTrace(testInfo)
+ }
+ actors.onCleanup(attachPassiveTrace)
for (const author of ["bob", "alice"] as const) {
for (const distance of [0, 1, 2, 20, 100, 101]) {
+ await markScrollTrace(alice.page, `${author}-${distance}-admission-start`)
await establishScrollDistancePrecondition(scroller, `${author}-${distance}`, distance, 0.01)
const before = await waitForCommittedGeometry(scroller)
expect(before.firstVisibleId).not.toBeNull()
expect(Math.abs(before.distanceToEnd - distance)).toBeLessThanOrEqual(0.01)
+ await markScrollTrace(alice.page, `${author}-${distance}-precondition`, { detail: before })
const nonce = `scroll186_${author}_${distance}_${Date.now()}`
const content = `passive ${author} at ${distance} ${nonce}`
const response = await fetch(`${WEB_URL}/api/community/channels/${channelId}/messages`, {
@@ -932,6 +944,7 @@ test.describe("message scroll characterization", () => {
}
}
expect(newestGets).toBe(1)
+ await attachPassiveTrace()
})
test("remote receive states and sustained upward input produce diagnostic traces", async ({ caseActors }, testInfo) => {
diff --git a/src/web/src/test/e2e-ui/_fixtures/community-notification-requests.ts b/src/web/src/test/e2e-ui/_fixtures/community-notification-requests.ts
index 3be1174a8..54e8d7aba 100644
--- a/src/web/src/test/e2e-ui/_fixtures/community-notification-requests.ts
+++ b/src/web/src/test/e2e-ui/_fixtures/community-notification-requests.ts
@@ -6,6 +6,7 @@ export const notificationPaths = [
"/api/community/users/me/attention",
"/api/community/users/me/dms",
]
+const accountStartupPaths = [...notificationPaths, "/api/community/users/me/read-state"]
export async function notificationResponsesFinished(page: Page, paths = notificationPaths) {
await Promise.all(paths.map(async (path) => {
@@ -47,7 +48,7 @@ export function captureNotificationRequests(page: Page) {
requestIds.set(request, requestIds.size + 1)
requests.push(path)
record({ kind: "request-start", id: requestIds.get(request), path, method: request.method() })
- if (notificationPaths.includes(path)) pendingNotifications.add(request)
+ if (accountStartupPaths.includes(path)) pendingNotifications.add(request)
})
page.on("requestfinished", (request) => {
pendingNotifications.delete(request)
@@ -70,14 +71,14 @@ export async function gotoAfterNotificationStartup(
const proxy = await proxyCommunityWebSockets(context, {
decideConnectionFrame: (frame) => frame.type === "auth.ok" && holdAuthentication ? "hold" : "forward",
})
- const initial = notificationResponsesFinished(page)
+ const initial = notificationResponsesFinished(page, accountStartupPaths)
await page.goto("/c/me", { waitUntil: "commit" })
await initial
await expect.poll(() => proxy.heldConnectionCount()).toBe(1)
trace.phase("auth-release")
const authenticatedRefresh = notificationResponsesFinished(
page,
- notificationPaths.filter((path) => path.endsWith("/attention")),
+ accountStartupPaths.filter((path) => !path.endsWith("/dms")),
)
holdAuthentication = false
expect(proxy.releaseHeldConnections((frame) => frame.type === "auth.ok")).toBe(1)
diff --git a/src/web/src/test/e2e-ui/_fixtures/scroll-trace.ts b/src/web/src/test/e2e-ui/_fixtures/scroll-trace.ts
index 04c69cc7a..6df99402a 100644
--- a/src/web/src/test/e2e-ui/_fixtures/scroll-trace.ts
+++ b/src/web/src/test/e2e-ui/_fixtures/scroll-trace.ts
@@ -312,6 +312,26 @@ export async function abortScrollTrace(page: Page): Promise<void> {
}).catch(() => {})
}
+export async function startAnalyzedScrollTrace(page: Page, input: {
+ scenario: string
+ identity: ScrollTraceIdentity
+ dataTransitionSource: ScrollTraceDataSource
+}) {
+ await installScrollTraceInCurrentDocument(page)
+ await startScrollTrace(page, input)
+ await beginScrollTraceAnalysis(page, input.scenario, { dataTransitionSource: input.dataTransitionSource })
+ let pending = true
+ return async (testInfo: TestInfo) => {
+ if (!pending) return
+ pending = false
+ await endScrollTraceAnalysis(page, input.scenario)
+ await markScrollTrace(page, "final-stimulus")
+ const result = await finishScrollTrace(page)
+ await attachScrollTrace(testInfo, result)
+ return result
+ }
+}
+
export async function attachScrollTrace(
testInfo: TestInfo,
result: ScrollTraceResult,
diff --git a/src/web/src/test/scroll-trace-probe.dom.test.ts b/src/web/src/test/scroll-trace-probe.dom.test.ts
new file mode 100644
index 000000000..0019be69b
--- /dev/null
+++ b/src/web/src/test/scroll-trace-probe.dom.test.ts
@@ -0,0 +1,65 @@
+import type { Page, TestInfo } from "@playwright/test"
+import { createElement } from "react"
+import { expect, it, vi } from "vitest"
+import { mockElementGeometry, render } from "@/test/react-dom-harness"
+import { createScrollTraceIdentity, startAnalyzedScrollTrace, validateScrollTrace } from "./e2e-ui/_fixtures/scroll-trace"
+
+it("reinstalls and validates consecutive real probe captures with their analysis window and write cleanup", async () => {
+ vi.useFakeTimers()
+ const frames = new Map<number, FrameRequestCallback>()
+ let nextFrame = 0
+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => { frames.set(++nextFrame, callback); return nextFrame })
+ vi.stubGlobal("cancelAnimationFrame", (id: number) => { frames.delete(id) })
+ vi.stubGlobal("ResizeObserver", class { observe() {} unobserve() {} disconnect() {} })
+ const view = render(createElement("div", { "data-testid": "community-message-scroller" },
+ createElement("div", { "data-message-list-content": "" },
+ createElement("div", { "data-index": 0 }, createElement("div", { "data-msg-id": "m1" }, "row")),
+ ),
+ ))
+ const root = view.getByTestId("community-message-scroller")
+ const restoreGeometry = mockElementGeometry(root, { scrollHeight: 1000, clientHeight: 400 })
+ const page = {
+ addScriptTag: async ({ content }: { content: string }) => { new Function(content)() },
+ evaluate: async (fn: (arg: unknown) => unknown, arg: unknown) => fn(arg),
+ } as unknown as Page
+ const attach = vi.fn(async () => {})
+ const info = { attach } as unknown as TestInfo
+ const advance = async (count: number) => {
+ for (let i = 0; i < count; i++) {
+ await vi.advanceTimersByTimeAsync(16)
+ const pending = [...frames.values()]
+ frames.clear()
+ for (const callback of pending) callback(performance.now())
+ await Promise.resolve()
+ }
+ }
+ try {
+ for (const scenario of ["local-history-submission", "passive-append-position-admission"]) {
+ const finish = await startAnalyzedScrollTrace(page, {
+ scenario,
+ identity: createScrollTraceIdentity({ account: "fixture", channel: "fixture", viewport: { width: 1280, height: 800 } }),
+ dataTransitionSource: "overlay-ws",
+ })
+ await advance(3)
+ root.scrollTop = 599
+ await advance(2)
+ const finished = finish(info)
+ await advance(12)
+ const result = (await finished)!
+ expect(validateScrollTrace(result)).toEqual([])
+ expect(result.writes).toEqual(expect.arrayContaining([expect.objectContaining({ method: "scrollTop", args: [599] })]))
+ expect(result.marks.map(mark => mark.name)).toEqual(expect.arrayContaining([`analysis-start:${scenario}`, `analysis-end:${scenario}`, "final-stimulus"]))
+ expect(Reflect.get(globalThis, "__alookScrollTrace")).toBeUndefined()
+ expect(Object.hasOwn(root, "scrollTop")).toBe(false)
+ expect(frames.size).toBe(0)
+ await expect(finish(info)).resolves.toBeUndefined()
+ }
+ expect(attach).toHaveBeenCalledTimes(4)
+ } finally {
+ Reflect.get(globalThis, "__alookScrollTrace")?.abort()
+ restoreGeometry()
+ view.unmount()
+ vi.unstubAllGlobals()
+ vi.useRealTimers()
+ }
+})