From 31b7c0c23253673376c16032b48d29d54c314395 Mon Sep 17 00:00:00 2001 From: peter rich Date: Tue, 22 Sep 2026 17:38:52 +0800 Subject: [PATCH 01/11] feat(core): make TopicDetailSession the sole topic-detail control plane Move pagination, prefetch, MessageBus refresh, and mutation reconcile into a Rust per-topic session with UI snapshots, and thin iOS/Android hosts to command/observer consumers while removing the old page-fetch RPC path. Co-authored-by: Cursor --- ...26-09-19-ios-topic-detail-local-updates.md | 13 + .../2026-09-22-ios-topic-detail-session.md | 1200 +++++++++ docs/architecture/fire-native-architecture.md | 8 +- .../app/data/repository/TopicRepository.kt | 60 - .../com/fire/app/session/FireSessionStore.kt | 21 +- .../fire/app/ui/home/HomeTopicDetailPatch.kt | 53 +- .../app/ui/topicdetail/TopicDetailActivity.kt | 1 - .../ui/topicdetail/TopicDetailViewModel.kt | 408 +-- .../app/ui/home/HomeTopicDetailPatcherTest.kt | 2 + .../App/Core/SessionState+Helpers.swift | 3 +- .../TopicDetail/FirePostCellNode+Body.swift | 75 +- .../TopicDetail/FirePostCellNode.swift | 88 +- .../Routing/FireAppRouteDestinationView.swift | 2 +- .../FireTopicInteractionService.swift | 18 +- .../App/Stores/FireHomeFeedStore.swift | 75 +- .../Stores/FireTopicDetailStore+Load.swift | 1392 ---------- .../FireTopicDetailStore+Mutations.swift | 583 ----- .../FireTopicDetailStore+Presence.swift | 387 --- .../FireTopicDetailStore+Reactions.swift | 249 -- .../App/Stores/FireTopicDetailStore.swift | 1354 ++-------- .../FireTopicDetailArticleSnapshot.swift | 112 + .../FireTopicDetailCommentListSnapshot.swift | 159 ++ ...ireTopicDetailInteractionCoordinator.swift | 11 +- .../FireTopicDetailModalRouter.swift | 30 +- .../FireTopicDetailSearchCoordinator.swift | 2 +- .../FireTopicDetailToolbarCoordinator.swift | 71 +- .../FireTopicDetailViewController.swift | 303 ++- .../Feed/FireTopicDetailFeedController.swift | 32 +- .../Feed/FireTopicDetailFeedModels.swift | 96 +- .../FireTopicDetailFeedUpdatePipeline.swift | 13 +- ...FireTopicDetailPaginationCoordinator.swift | 12 +- ...ireTopicDetailRuntimeSnapshotBuilder.swift | 325 +-- .../Nodes/FireTopicQuickReplyBarNode.swift | 69 +- .../Shell/FireTopicDetailPageSkeleton.swift | 152 ++ .../State/FireTopicDetailPageState.swift | 2 +- .../FireTopicDetailSnapshotAssembler.swift | 5 +- .../Support/FireTopicPresentation.swift | 109 + .../App/ViewModels/FireAppViewModel.swift | 113 +- .../App/Views/Composer/FireComposerView.swift | 8 +- .../FireFollowListViewController.swift | 2 +- .../FireProfileActivityTimelineView.swift | 2 +- .../App/Views/Profile/FireProfileView.swift | 2 +- .../Views/Profile/FirePublicProfileView.swift | 2 +- .../FireAppSession/FireSessionStore.swift | 43 +- .../FireListPaginationAndUpdateTests.swift | 7 +- .../Tests/Unit/FireSessionStoreTests.swift | 3 +- .../Unit/FireTopicDetailRuntimeTests.swift | 1 + .../Unit/FireTopicDetailStoreTests.swift | 1094 -------- .../FireTopicListMessageBusRefreshTests.swift | 28 +- .../Unit/FireTopicPresentationTests.swift | 6 +- rust/crates/fire-core/src/core/messagebus.rs | 1544 ------------ .../fire-core/src/core/messagebus/channels.rs | 157 ++ .../fire-core/src/core/messagebus/mod.rs | 113 + .../fire-core/src/core/messagebus/parse.rs | 251 ++ .../fire-core/src/core/messagebus/poll.rs | 639 +++++ .../fire-core/src/core/messagebus/runtime.rs | 559 +++++ rust/crates/fire-core/src/core/mod.rs | 21 +- rust/crates/fire-core/src/core/persistence.rs | 2 + .../fire-core/src/core/topic_detail/actor.rs | 425 ++++ .../fire-core/src/core/topic_detail/bus.rs | 119 + .../fire-core/src/core/topic_detail/load.rs | 266 ++ .../fire-core/src/core/topic_detail/mod.rs | 268 ++ .../src/core/topic_detail/mutations.rs | 449 ++++ .../src/core/topic_detail/publish.rs | 161 ++ .../src/core/topic_detail/reactions.rs | 179 ++ .../src/core/topic_detail/registry.rs | 360 +++ .../src/core/topic_detail/session.rs | 324 +++ .../src/core/topic_detail/summary.rs | 103 + .../fire-core/src/core/topic_detail/tests.rs | 112 + .../fire-core/src/core/topic_detail/window.rs | 253 ++ .../src/core/topic_detail_project.rs | 697 +++++ rust/crates/fire-core/src/core/topics.rs | 2233 ----------------- rust/crates/fire-core/src/core/topics/list.rs | 235 ++ rust/crates/fire-core/src/core/topics/mod.rs | 11 + .../crates/fire-core/src/core/topics/posts.rs | 99 + .../src/core/topics/source/hydrate.rs | 495 ++++ .../fire-core/src/core/topics/source/load.rs | 671 +++++ .../fire-core/src/core/topics/source/mod.rs | 146 ++ .../src/core/topics/source/session.rs | 353 +++ rust/crates/fire-core/src/core/topics/tree.rs | 563 +++++ rust/crates/fire-core/src/lib.rs | 1 + rust/crates/fire-core/src/session_store.rs | 1 + rust/crates/fire-core/src/state_observer.rs | 1 + rust/crates/fire-models/src/lib.rs | 5 + rust/crates/fire-models/src/session.rs | 4 + .../crates/fire-models/src/topic_detail_ui.rs | 300 +++ rust/crates/fire-store/src/lib.rs | 26 + rust/crates/fire-uniffi-session/src/lib.rs | 16 +- .../crates/fire-uniffi-session/src/records.rs | 13 + rust/crates/fire-uniffi-topics/src/lib.rs | 71 +- rust/crates/fire-uniffi-topics/src/records.rs | 1247 --------- .../fire-uniffi-topics/src/records/detail.rs | 451 ++++ .../fire-uniffi-topics/src/records/list.rs | 121 + .../fire-uniffi-topics/src/records/mod.rs | 11 + .../fire-uniffi-topics/src/records/poll.rs | 90 + .../fire-uniffi-topics/src/records/post.rs | 498 ++++ .../fire-uniffi-topics/src/records/upload.rs | 167 ++ rust/crates/fire-uniffi-topics/src/session.rs | 423 ++++ .../fire-uniffi-topics/src/ui_records.rs | 569 +++++ 99 files changed, 13848 insertions(+), 10781 deletions(-) create mode 100644 docs/architecture/2026-09-22-ios-topic-detail-session.md create mode 100644 native/ios-app/App/TopicDetail/Article/FireTopicDetailArticleSnapshot.swift create mode 100644 native/ios-app/App/TopicDetail/Comments/FireTopicDetailCommentListSnapshot.swift create mode 100644 native/ios-app/App/TopicDetail/Shell/FireTopicDetailPageSkeleton.swift delete mode 100644 rust/crates/fire-core/src/core/messagebus.rs create mode 100644 rust/crates/fire-core/src/core/messagebus/channels.rs create mode 100644 rust/crates/fire-core/src/core/messagebus/mod.rs create mode 100644 rust/crates/fire-core/src/core/messagebus/parse.rs create mode 100644 rust/crates/fire-core/src/core/messagebus/poll.rs create mode 100644 rust/crates/fire-core/src/core/messagebus/runtime.rs create mode 100644 rust/crates/fire-core/src/core/topic_detail/actor.rs create mode 100644 rust/crates/fire-core/src/core/topic_detail/bus.rs create mode 100644 rust/crates/fire-core/src/core/topic_detail/load.rs create mode 100644 rust/crates/fire-core/src/core/topic_detail/mod.rs create mode 100644 rust/crates/fire-core/src/core/topic_detail/mutations.rs create mode 100644 rust/crates/fire-core/src/core/topic_detail/publish.rs create mode 100644 rust/crates/fire-core/src/core/topic_detail/reactions.rs create mode 100644 rust/crates/fire-core/src/core/topic_detail/registry.rs create mode 100644 rust/crates/fire-core/src/core/topic_detail/session.rs create mode 100644 rust/crates/fire-core/src/core/topic_detail/summary.rs create mode 100644 rust/crates/fire-core/src/core/topic_detail/tests.rs create mode 100644 rust/crates/fire-core/src/core/topic_detail/window.rs create mode 100644 rust/crates/fire-core/src/core/topic_detail_project.rs delete mode 100644 rust/crates/fire-core/src/core/topics.rs create mode 100644 rust/crates/fire-core/src/core/topics/list.rs create mode 100644 rust/crates/fire-core/src/core/topics/mod.rs create mode 100644 rust/crates/fire-core/src/core/topics/posts.rs create mode 100644 rust/crates/fire-core/src/core/topics/source/hydrate.rs create mode 100644 rust/crates/fire-core/src/core/topics/source/load.rs create mode 100644 rust/crates/fire-core/src/core/topics/source/mod.rs create mode 100644 rust/crates/fire-core/src/core/topics/source/session.rs create mode 100644 rust/crates/fire-core/src/core/topics/tree.rs create mode 100644 rust/crates/fire-models/src/topic_detail_ui.rs delete mode 100644 rust/crates/fire-uniffi-topics/src/records.rs create mode 100644 rust/crates/fire-uniffi-topics/src/records/detail.rs create mode 100644 rust/crates/fire-uniffi-topics/src/records/list.rs create mode 100644 rust/crates/fire-uniffi-topics/src/records/mod.rs create mode 100644 rust/crates/fire-uniffi-topics/src/records/poll.rs create mode 100644 rust/crates/fire-uniffi-topics/src/records/post.rs create mode 100644 rust/crates/fire-uniffi-topics/src/records/upload.rs create mode 100644 rust/crates/fire-uniffi-topics/src/session.rs create mode 100644 rust/crates/fire-uniffi-topics/src/ui_records.rs diff --git a/docs/architecture/2026-09-19-ios-topic-detail-local-updates.md b/docs/architecture/2026-09-19-ios-topic-detail-local-updates.md index de03e94d..479f30cb 100644 --- a/docs/architecture/2026-09-19-ios-topic-detail-local-updates.md +++ b/docs/architecture/2026-09-19-ios-topic-detail-local-updates.md @@ -2,8 +2,21 @@ 日期:2026-09-19 +Rust `layout_checksum` and `interaction_checksum` hash server fields only. The Swift builder folds local chrome onto those checksums: reply shortcut, reply-thread expansion, reaction-picker expansion, and text expansion go into the layout token; search highlight and `canWriteInteractions` join the in-place token with the local layout chrome. Do not set `contentToken` or `inPlaceUpdateToken` to the bare Rust checksum. Topic detail data comes from `TopicDetailSession` snapshots. Swift does not merge pages. + 详情页小操作不再为了刷新计数而 bump collection revision。实现是真相源:单测跟落地行为走,不为过期断言改产品幅度。 +## 页面骨架 + +详情页按四块刷新,正文和评论仍在同一条滚动列表里: + +| 区域 | 组成 | 刷新 | +| --- | --- | --- | +| 标题栏 | 系统返回、中间标题、右侧图标 | 标题和右侧图标各比一次,没变的槽不重画 | +| 头部正文 | 标题和标签、摘要、正文、表情图标、数值统计 | 标题和统计是独立 cell。原帖 cell 内作者、正文、操作图标、表情、楼层线按 `messageBands` 只刷变化的一块 | +| 评论列表 | 楼层头、消息 item、楼层尾 | 一条评论再拆成引用入口、图片、文案、展示更多。引用正文仍在文案段里。展开正文或楼层只刷展示更多,不重建图片 | +| 底部输入 | 正在输入、回复目标、输入框、校验文案 | 只改正在输入时不重写输入框 | + ## 三档管道 `FireTopicDetailFeedUpdatePipeline` 仍按 token 选档: diff --git a/docs/architecture/2026-09-22-ios-topic-detail-session.md b/docs/architecture/2026-09-22-ios-topic-detail-session.md new file mode 100644 index 00000000..4587dcc9 --- /dev/null +++ b/docs/architecture/2026-09-22-ios-topic-detail-session.md @@ -0,0 +1,1200 @@ +# iOS 话题详情:Rust 会话唯一控制面 + +| 项 | 值 | +| --- | --- | +| 日期 | 2026-09-22 | +| 状态 | 已落地(Rust 会话 + iOS/Android 单源;旧分页 RPC 已删) | +| 范围 | 话题详情模块。Home / 搜索 / 通知 / 聊天不改架构 | +| 通道 | 只动 `fire-uniffi-topics` + `fire-core` 话题模块。不合并 session / chat / search / notification | +| 参考 | KycNative 模块内对象生命周期与 ABI 投影。不把 Fire 收成一个 `FaceVerifySession` 式应用对象 | + +## Feasibility Assessment + +可行,且应做。源游标、树、未读根自动延伸已经在 Rust: + +- `FireTopicDetailSourceRuntime` / 私有 `TopicDetailSourceSession`:`rust/crates/fire-core/src/core/topics.rs` +- `FireCore::fetch_topic_detail_source_snapshot`、`fetch_topic_detail_page`、`append_topic_detail_source`、`load_more_topic_posts`、`extend_topic_source_to_unread_root_if_needed` +- 模型 `TopicDetailPage { source_snapshot, tree_presentation }`:`rust/crates/fire-models/src/topic_detail.rs` +- FFI 仍是 RPC 目录:`FireTopicsHandle::{fetch_topic_detail_page, load_more_topic_posts, like_post, create_reply, ...}`(`rust/crates/fire-uniffi-topics/src/lib.rs`) + +缺口是 iOS 第二控制面,不是缺协议。`FireTopicDetailStore` 持有 `topicDetails`、`topicSourceSnapshots`、`topicTreePresentations`、`topicPostLookups`、`topicSourceCursorsByTopic`、窗口 / 区间 / hydration task,并自己决定重试、预取、乐观回滚、MessageBus 刷新。这违反 `docs/architecture/fire-native-architecture.md` §1.1 与 §2.4。 + +不需要新网络栈。CF 挑战与 cookie self-healing 已在 `FireNetworkLayer`(`cloudflare_challenge_handler`、`cookie_self_healing_handler`,注册入口在 `FireSessionHandle`)。话题详情不再在 Swift 里解析 `FireUniFfiError` 决定重试。 + +Android 早期阶段不改调用点。`TopicRepository.fetchTopicDetailPage` / `loadMoreTopicPosts` 与 `FireSessionStore.fetchTopicDetailPage` 继续打旧 RPC。旧 RPC 只转发 `load_topic_detail_*`,不 `open` 会话,直到两端都迁完再删。 + +主要风险:iOS 消费面一次切走 `TopicDetailState` / `TopicPostState` / `postLookup`;LoginRequired 的 headless 重登今天只从话题 store 和首页 store 进入。见 Architectural Notes。 + +## Current Surface Inventory (method-level) + +### Rust 已有,会话应吃掉而不是重写 + +| 位置 | 符号 | 归宿 | +| --- | --- | --- | +| `topics.rs` | `TopicDetailSourceSession` 及 `source_snapshot` / `merge_posts` / `recompute_loaded_state` | 留在会话私有状态。不导出 | +| `topics.rs` | `fetch_topic_detail_source_snapshot` | 会话 `open` / `reload` 的内部步骤 | +| `topics.rs` | `fetch_topic_detail_page` | 同上,含 `extend_topic_source_to_unread_root_if_needed` | +| `topics.rs` | `load_more_topic_posts` / `append_topic_detail_source` | 会话 `load_more` 与可见区预取 | +| `topics.rs` | `build_topic_tree_presentation` | 私有。树不进 UI 快照的源字段 | +| `topics.rs` | `fetch_topic_posts` / `fetch_topic_ai_summary` | 会话内部补洞与摘要 | +| `interactions.rs` | `like_post` / `unlike_post` -> `Option`;`toggle_post_reaction`;`create_reply`;`create_boost`;`vote_poll` | 会话命令调用。返回值不穿过 FFI 给 Swift 改帖 | +| `messagebus.rs` | `subscribe_message_bus_channel` / `unsubscribe_message_bus_channel` | 会话在 open/close 自己订阅 | +| `presence.rs` | `bootstrap_topic_reply_presence` / `update_topic_reply_presence` / `topic_reply_presence_state` | 会话内部 | +| `state_observer.rs` | `notify_session` / `notify_topic_list` / `notify_notification_center` | 不扩展。话题详情用会话级 observer | +| `network.rs` | `StaleSessionResponse`(epoch 前进后丢弃响应);CF `retry_after_cloudflare_challenge` | 会话内重试一次 `force_load`。Swift 不再看见这个错误 | + +`TopicDetailSourceQuery` 仍带 `initial_batch_size`、`load_more_batch_size`、`max_auto_batches_per_gesture`、`max_auto_posts_per_gesture`。生产路径改为常量。`tests/network.rs` 用 1/3/10 等非生产批量,见测试节。 + +常量今天分裂两处,数值已经一致,收到会话旁边: + +| 策略 | Swift 现状 | Rust 现状 | +| --- | --- | --- | +| 首批 / 续批 | `topicDetailInitialBatchSize = 40`,`topicDetailLoadMoreBatchSize = 40` | `DEFAULT_TOPIC_INITIAL_BATCH_SIZE` / `DEFAULT_TOPIC_LOAD_MORE_BATCH_SIZE` | +| 自动连批 | Swift 写死 `maxAutoBatchesPerGesture: 3`,`maxAutoPostsPerGesture: 120` | 同名 default | +| 流内预取 | `topicPostPrefetchThreshold = 10`,`topicPostForwardExpansionSize = 60`,`topicPostPageSize = 30`,`topicPostHydrationIterationLimit = 8`,debounce 120ms | 无。在 Swift `handleVisiblePostNumbersChanged` / `expandRequestedRangeIfNeeded` | +| 列表尾预取 | `fireTopicDetailShouldLoadMore` 默认 `trailingThreshold = 5` | 无 | +| 回复上下文 | `replyContextPostBatchSize = 20` | 无 | +| MessageBus 刷新 | `scheduleTopicDetailRefresh` 睡 1.5s;滚动中延期 | 无 | +| presence 心跳 | 30s | `update_topic_reply_presence` 另有服务端节流 | + +### FFI 现状 + +`FireTopicsHandle` 是无生命周期的 RPC。话题详情相关:`fetch_topic_detail_source_snapshot`、`fetch_topic_detail_page`、`load_more_topic_posts`、`fetch_topic_posts`、`fetch_topic_ai_summary`、`create_reply`、`create_boost`、`delete_boost`、`fetch_post`、`fetch_post_replies`、`fetch_post_reply_ids`、`fetch_post_reply_history`、`update_post`、`delete_post`、`recover_post`、`flag_post`、`fetch_post_action_types`、`update_topic`、`report_topic_timings`、`like_post`、`unlike_post`、`toggle_post_reaction`、`fetch_reaction_users`、`accept_solution`、`unaccept_solution`、`vote_poll`、`unvote_poll`、`vote_topic`、`unvote_topic`、`fetch_topic_voters`。 + +记录在 `fire-uniffi-topics/src/records.rs`。`TopicPostState.presentation` 已是 `Option>`(`fire-uniffi-types/src/handle.rs`,`checksum()` / `plain_text()` / `segment(i)`)。单元格不得再拿 cooked HTML。 + +全局 `StateObserver`(`fire-uniffi/src/lib.rs`)只有 `on_session_snapshot`、`on_topic_list_snapshot`、`on_notification_center_snapshot`。`fetch_topic_list` 注释写明分页结果不能广播成权威全表。话题详情禁止塞进这个 observer。 + +### iOS store:逐方法归类 + +归类:`删` = 逻辑进 Rust,方法删除。`转` = 保留,函数体变成一行命令转发。`留` = 纯 UI,不进 Rust。store 最终只留「转」和快照持有。 + +`FireTopicDetailStore.swift` + +| 方法 | 类 | +| --- | --- | +| `checksum` | 删。服务端字段的 `layout_checksum` / `interaction_checksum` 由 Rust 算。Swift builder 仍把本地 chrome 折进 layout / in-place token,不把 token 设成 Rust checksum 本身 | +| `bumpTopicCollectionRevision` / `Chrome` / `Sidecar` / `Interaction` | 删。快照带单调 revision | +| `setLoadingTopic` / `setLoadingMoreTopicPosts` / `setLoadMoreTopicPostsError` / `setLoadingTopicAiSummary` | 删 | +| `setMutatingPost` / `setSubmittingReply` / `setLoadingPostReplyContext` / `setPostReplyContextError` | 删。进快照行标志或 composer 段 | +| `setTopicPresenceUsers` / `setPendingScrollTarget` / `updateTopicErrorMessage` / `updateTopicDetailNotice` | 删 | +| `applySession` | 转。只转发两种 readiness,见「三种会话过渡」。`canReadAuthenticatedApi == true` 时直接 return,epoch 变化不在这里清快照。完整登出才 `release` 全部 owner 并清空快照。短暂未登录只取消在途 HTTP | +| `cancelInFlightFetches` | 删。`close` 取消 actor 任务 | +| `handleMessageBusStopped` | 删。bus runtime 通知内部 listener | +| `reset` | 转。`registry.close_all()` | +| `clearTopicDetailAnchor` / `clearTransientAnchor` | 转。`clear_scroll_target` | +| `markScrollTargetSatisfied` | 转。`acknowledge_scroll_target` | +| `pendingScrollTarget` / `isScrollTargetExhausted` / `topicDetail` / `topicRenderState` / `topicPostLookup` / presence 与 AI summary / notice / revision / loading / `hasMoreTopicPosts` / `isSubmittingReply` / `isMutatingPost` 全部 getter | 删。VC 读 `snapshot(for:)` | +| `canStartNextTopicSourcePageLoad` | 删 | +| `mergeReplyContextTreeRows` | 删 | +| `formattedTopicIDs` | 删 | +| `renderStateCoversRowInputs` | 删 | +| `elapsedMilliseconds` | 留在 VC 诊断,从 store 挪走 | +| `snapshotByAppending` / `cookedByteCount` / `hydrateRequestedRange` | 删 | +| `nextDirectionalSearchRange` / `previousDirectionalSearchRange` / `nextForwardSearchRange` | 删。这是滚动锚点找流位置,不是正文搜索。调用点在 `+Load.swift` `nextRequestedRangeForUnresolvedTarget` | +| `performWithTimeout` 及文件末尾 request gate(`start` / `cancel` / `setWorkTask` / `setTimeoutTask` / `finish`) | 删。超时是会话常量 | + +`FireTopicDetailStore+Load.swift` + +| 方法 | 类 | +| --- | --- | +| `loadTopicDetail` | 转。`open` 或已打开时 `reload` | +| `fetchTopicDetailPagePayload` | 删。含 `performWithCloudflareRecovery`、`StaleSessionResponse` 循环、`attemptReadPathLoginRecovery`、批量参数 | +| `detailContainsPostNumber` | 删 | +| `rememberTopicRecoverySlug` / `bestKnownTopicRecoverySlug` / `topicCloudflareRecoveryURL` | 删。slug 作为 `open` 入参,供首包前的 CF URL;header 到达后以 header.slug 为准。URL 由网络层按现有 foreground 请求构造 | +| `synthesizedTopicDetail` / `prepareTopicDetailPagePayload` | 删。禁止再把 source+tree 合成 `TopicDetailState` | +| `applyTopicDetailPagePayload` | 删。今天第 318 行 `appViewModel.patchHomeTopicCounts(from:)` 改由快照上的窄 patch 触发 | +| `loadNextTopicSourcePage` / `enqueueNextTopicSourcePageLoad` | 删 | +| `loadMoreTopicPostsIfNeeded` | 转。只服务用户点「加载更多」/ 失败 footer 重试。阈值预取删除 | +| `handleVisiblePostNumbersChanged` | 转。`note_visible_posts` | +| `needsAnchoredReload` / `prepareTopicDetail` / `cacheTopicDetail` / `setTopicDetail` / `rebuildTopicDetail` | 删 | +| `buildTopicDetailRenderUpdate` / `applyTopicDetailRenderUpdate` / `scheduleTopicRenderCacheUpdate` / `applyTopicRenderCache` / `applyTopicDetail` | 删。渲染缓存改读 `RenderDocumentHandle` | +| `reloadTopicAiSummary` | 转。`reload_ai_summary` | +| `loadTopicAiSummaryIfNeeded` | 删。`summarizable` 后会话自己拉 | +| `prehydrateAnchoredContextBeforeDisplayIfNeeded` / `expandRequestedRangeIfNeeded` / `hydrateTopicPostsToTargetIfNeeded` / `advanceRequestedRangeTowardPendingScrollTargetIfNeeded` / `loadedPostNumbers` / `applyHydratedTopicPostsIfNeeded` / `hasMissingPostsInRequestedRange` / `refreshTopicWindowState` / `resolvedTopicWindowState` / `resolveRequestedRange` / `clampedRequestedRange` / `streamIndex` / `scrollTargetIsExhausted` / `nextRequestedRangeForUnresolvedTarget` / `initialRequestedRange` / `expandedRequestedRange` / `boundedRequestedRange` | 删 | + +`FireTopicDetailStore+Mutations.swift` + +| 方法 | 类 | +| --- | --- | +| `submitReply` / `createBoost` / `updatePost` / `deletePost` / `recoverPost` / `flagPost` / `votePoll` / `unvotePoll` | 转。不返回 `TopicPostState` 给调用方改树。`updatePost` 今天返回帖,改为 `async throws`,编辑器预填走 `prepare_edit` | +| `loadPostActionTypesIfNeeded` | 转。`ensure_flag_types`。目录进快照 `flag_types`,store 不再缓存 | +| `loadPostReplyContextIfNeeded` | 转。`load_reply_context` | +| `applyReplyContextRowsIfPossible` / `fetchReplyContextReplies` / `orderedUniquePostIDs` | 删 | +| `performPostManagementMutation` / `refreshTopicDetailAfterMutation` / `refreshTopicDetailPageFromNetwork` | 删 | +| `applyCreatedBoost` / `applyCreatedReply` | 删 | + +`FireTopicDetailStore+Presence.swift` + +| 方法 | 类 | +| --- | --- | +| `beginTopicDetailLifecycle` | 转。并入 `open` 的 owner token | +| `endTopicDetailLifecycle` | 转。`close`。不再因首页行可见而保留详情(见 Key Decisions) | +| `pruneInactiveTopicDetailState`(两个)/ `retainedTopicDetailIDs` / `evictTopicDetailState` | 删。refcount 替代 | +| `maintainTopicDetailSubscription` | 删。订阅频道与今天 iOS 一致:`/topic/{id}`、`/topic/{id}/reactions`、`/polls/{id}`、`/presence/discourse-presence/reply/{id}`(`FireSessionStore.subscribeTopic*`) | +| `handleMessageBusEvent` | 删。`FireAppViewModel.handleMessageBusEvent` 不再把 `.topicDetail` / `.topicReaction` / `.presence` 转给 topic store。聊天分支不动 | +| `setTopicDetailScrollInteractionActive` | 转。`note_scroll_interaction` | +| `beginTopicReplyPresence` / `endTopicReplyPresence` | 转。`begin_reply_typing` / `end_reply_typing` | +| `scheduleTopicDetailRefresh` / `refreshTopicDetailFromMessageBus` / `refreshTopicPresenceState` / `applyTopicPresenceState` / `activeAnchorPostNumber` | 删 | + +`FireTopicDetailStore+Reactions.swift` + +| 方法 | 类 | +| --- | --- | +| `setPostLiked` / `togglePostReaction` | 转 | +| `captureReactionSnapshot` / `restoreReactionSnapshot` / `applyOptimisticReactionChange` / `adjustCount` / `applyPostReactionUpdate` | 删 | + +### 留在 VC / cell 的 UI 状态(不进 store,不进 Rust) + +`expandedPostTextIDs`、`expandedReplyRootPostIDs`、`expandedReactionPickerPostIDs`、composer draft / `composerContext` / `quickReplyError`、`isTopicAiSummaryExpanded`、键盘、搜索高亮、滚动偏移、cell 本地 overflow(`docs/architecture/2026-09-19-ios-topic-detail-local-updates.md`)。三档 Texture 管道留在 Swift。Rust checksum 只覆盖服务端字段。builder 仍把展开、搜索高亮等本地 chrome 折进 layout / in-place token。 + +### UI 消费点(本设计要改输入,不改管道语义) + +| 文件 | 今天读什么 | 之后 | +| --- | --- | --- | +| `FireTopicDetailViewController` `buildCurrentFeedState` / `Chrome` / `Composer` / `Sidecar` / `Interaction` / `PageState` / `buildRuntimeConfiguration` | `TopicDetailState`、`postLookup`、store revision | 快照段 + VC 本地 chrome | +| `FireTopicDetailPageState.swift` | 同上 | 重写成快照视图,不再嵌 `TopicDetailState` | +| `FireTopicDetailFeedModels.swift` | `FireTopicDetailRuntimePostContext.post: TopicPostState` | 行 DTO | +| `FireTopicDetailRuntimeSnapshotBuilder` | detail + renderState + lookup | 快照行 + 本地展开集合 | +| `FireTopicDetailFeedUpdatePipeline` | `invalidationToken` / `postLayoutContentToken` / `postContentToken` | 三档规则不变。Rust checksum 只是 builder 的输入之一。禁止 `contentToken = layout_checksum` | +| `FireTopicDetailPaginationCoordinator` | `fireTopicDetailShouldLoadMore` 用过滤后的 item 下标,默认尾阈值 5 | 协调器只上报 `note_filtered_feed_tail(itemCount, visibleMaxItem)`。比较进 Rust。footer 重试仍 `load_more`。删掉 Swift 里的第二份阈值 | +| `FireTopicDetailVisibilityCoordinator` | 240ms 合并可见楼层号 | 留。只调 `note_visible_posts`。120ms 产品 debounce 进 Rust,240ms 仍是 UI 合并 | +| `Controller/` 下 toolbar / interaction / search / modal | 读 store 帖 | 读快照行。搜索只扫已加载行的 `plain_text()` | +| `FireTopicInteractionService` | 赞/表情/投票走 store;`voteTopic`、书签、通知级别、timings 直接打 session store 再 `refreshTopicDetailAfterMutation` | 话题详情屏幕上的写操作全部走 store 转发。`fetchReactionUsers` / `fetchTopicVoters` 仍是一次性拉取,不进帖树 | +| `FireAppViewModel.submitReply` / `updatePost` | 已转发 store | 保持转发,签名去掉返回帖 | +| `FireRootCoordinator` | 拥有唯一生产 store(约第 95 行) | 仍是唯一 store | + +额外 `FireTopicDetailStore(appViewModel:)` 构造(必须改成拿 root store,否则会再开一套会话): + +- `FireAppRouteDestinationView.swift` +- `FirePublicProfileView.swift` +- `FireFollowListViewController.swift` +- `FireProfileActivityTimelineView.swift` +- `FireProfileView.swift` +- 单测里的临时 store 改为注入 snapshot fixture,不拉网 + +### 首页行补丁(唯一允许碰首页的点) + +调用链今天是: + +1. `FireTopicDetailStore.applyTopicDetailPagePayload` 与 `+Mutations` 刷新成功后调 `FireAppViewModel.patchHomeTopicCounts(from: TopicDetailState)`(`FireAppViewModel.swift` 约 791 行) +2. `FireHomeFeedStore.patchTopicCounts` -> `patchedTopicRow(_:from:)`(`FireHomeFeedStore.swift` 98–209 行) + +公式:帖数 / 回复数 / 浏览 / `lastRead` / `highest` 覆盖;`lastRead == nil` 时保留原 `hasUnreadPosts`;`lastRead >= highest` 时未读与新帖数清零;否则保留原 `unreadPosts` / `newPosts` 且 `hasUnreadPosts = true`。没有从 stream 重算未读。 + +Rust 没有对应方法。`notify_topic_list` 推的是整表 `TopicListResponse`,不能用于单行。设计只加窄 patch,不改首页分页。 + +### Android(本阶段只保证能编过) + +`TopicDetailViewModel.loadTopicDetail` -> `fetchTopicDetailPagePayload` -> `TopicRepository.fetchTopicDetailPage` -> `FireSessionStore.fetchTopicDetailPage` -> `core.topics().fetchTopicDetailPage`。`loadMorePosts` 同理走 `loadMoreTopicPosts(cursor)`。这些签名在删除 PR 之前保持。 + +## Design + +### 决策 + +1. 一个话题一个 `TopicDetailSession`。`open` / 命令 / `close`。不是 `FireTopicsHandle` 上再堆 HTTP。 +2. Registry 挂在 `FireCore`,key = topic id。`open` 按 owner token 引用计数,同一 token 再 open 是替换 observer。`release(topic_id, owner_token)` 只卸该 owner。最后一人离开才拆会话。 +3. 命令进,不可变 `TopicDetailUiSnapshot` 出。后台刷新推同一类型。Swift 不保留第二份 source / tree / post 字典。 +4. UniFFI 只做 `into_core` / `from_core`、错误映射、panic 边界。业务分支不进 `fire-uniffi-topics`。 +5. 不新增「请宿主决定下一步」回调。平台能力继续用 session 通道已有的 CF / cookie hook。 +6. 不复制 Kyc:无逐帧同步 tick、无专用会话线程、不在 UI 线程等 HTTP。Kyc 的 `cfg(target_os)` 主要是 JNI、日志和 vendor 绑定,不是产品语义开关。话题详情不按 `target_os` 分产品行为。 +7. Actor 跑在现有 tokio(`run_on_ffi_runtime` 那套),每会话一个 task + `mpsc`。HTTP 在 actor 内 await。observer 在放下锁之后调用,`catch_unwind`,不 debounce 点赞。 +8. 新会话 API 不收批量参数。actor 用常量组 query。旧 RPC 在删除前仍把宿主 query 的批量原样交给同一个 `load_topic_detail_page`。 +9. 旧 RPC 在删除前只转发 `load_topic_detail_page` / `load_topic_detail_source_snapshot` / `load_more_topic_detail_posts`,不进 `Registry.open`。无 observer、无 MessageBus 订阅、无预取、无 owner。Android 行为不变。 +10. 首页只收窄计数 patch。不调用 `notify_topic_list`。 + +### 不复制的 Kyc 形状 + +要的:`FaceVerifySession` 的生命周期对象;`Ffi*::into_core` / `from_core`;`docs/ARCHITECTURE.md`「接口层只做 ABI」;壳(`FacePipelineController` / `FaceSessionHost`)投影 tick、不拥有 login/compare。话题详情里壳只投影快照、上报可见楼层与生命周期。 + +不要的:`process_frame` -> `FrameTick` 同步回路;`facelight-session` 专用线程;把平台绑定用的 `cfg(target_os)` 拿来切产品语义。Fire 这边不新增这种分叉。 + +### 模块 + +```text +fire-models/src/topic_detail_ui.rs UI 投影,无逻辑 +fire-core/src/core/topic_detail_session.rs +fire-core/src/core/topic_detail_project.rs +fire-uniffi-topics/src/session.rs Handle + observer 适配 +fire-uniffi-topics/src/records.rs from_core 记录 +``` + +`topics.rs` 里的 source session 原样搬进会话文件(或留在 `topics.rs` 作为 `pub(crate)`)。`FireCore.topic_detail_source` 从 `core/mod.rs` 移除,改成: + +```rust +topic_detail_sessions: Arc, +``` + +`FireCore::fetch_topic_detail_page` 等公开方法保留为兼容包装,内部调用 `load_topic_detail_page` / `load_more_topic_detail_posts`。不另写一套。 + +### 生命周期与调用 + +```text +VC appear + | + v +Store.open(id, owner, slug, target, bypass) 1 line + | + v +FireTopicsHandle.open_topic_detail + | + v +Registry.open(topic_id, owner, observer) + | + +-- same owner token --> replace that observer + | + +-- other owners exist --> fan-out current snapshot + | + +-- new session --> spawn actor on shared tokio + | + v + same path as fetch_topic_detail_page + source session + tree + unread-root seek + | + v + project TopicDetailUiSnapshot + | + v + observer.on_snapshot not on UI thread + | + v + Store.snapshots[id] = snap + | + v + VC: rows + local chrome + Texture 3-tier pipeline +``` + +`open` 立即返回 handle。第一帧可以是 `phase = loading`。缓存短路只属于 `open`,而且只在调用方没要求绕过缓存、并且已有 source 已经包含目标楼时:重推快照,不打网。这对应今天 `loadTopicDetail` 里 `!force` 且 source 已覆盖目标就 return(`+Load.swift` 33–41 行)。`bypass_cache == false` 才走这条。`force_load` 是另一位,只进服务端 query,不决定要不要打网。 + +```text +VC tap like / reply / load-more + | + v +Store command 1 line, no post merge + | + v +session mpsc + | + +-- optimistic write posts_by_id + +-- push snapshot (interaction or collection rev) + +-- HTTP via existing FireCore methods + | ok -> reconcile, push + | err -> rollback, push, surface error + v +observer + | + v +pipeline reads checksums, does not patch posts +``` + +```text +MessageBus poll loop, each message + | + +-- read live listener list not the list at start + | + +-- host UnboundedSender home / chat / notif + | + v +TopicDetailSession + TopicDetail | TopicReaction: + scrolling -> defer + else sleep 1.5s, reload track_visit=false + TopicDetail + detail_event_type polls: + same refresh path, no new kind + Presence: + typing users onto snapshot +``` + +`FireMessageBusRuntime` 只有一个在 `start_message_bus` 时放进 `MessageBusPollContext` 的 `event_sender`。内部 listener 必须在每条消息上从 runtime 现读,不能在 start 时拷走。`add_internal_listener` / `remove_internal_listener` 不替换 host sender。`stop_message_bus` 通知 listener;会话若仍有 owner,bus 再次 start 后重订阅。频道与 last id 保持 `FireSessionStore.subscribeTopicDetailChannel`:detail 用 header `message_bus_last_id`,reactions 为 nil,polls 为 0,scope transient。 + +没有 `MessageBusEventKind::Polls`。`/polls/{id}` 在 `messagebus.rs` 里是 `TopicDetail` 且 `detail_event_type == "polls"`。监听这个组合,或频道前缀 `/polls/`,不要新枚举。 + +```text +header counts changed + | + v +FireCore::patch_cached_home_topic_counts + read cached row if present + do not call notify_topic_list + | + v +snapshot.home_row_patch: Option<...> + | + v +FireHomeFeedStore.applyHomeRowCountPatch + assign fields only +``` + +未读决策在 Rust,照抄 `patchedTopicRow`,不从 stream 重算: + +```rust +pub enum TopicHomeUnreadDecision { + /// last_read is None. Do not compare post numbers in Swift. + /// If row.hasUnreadPosts: keep unreadPosts and newPosts. + /// If !row.hasUnreadPosts: zero both. Leave the flag as it is. + WhenLastReadMissing, + /// last_read >= highest. Zero both counts. hasUnreadPosts = false. + CaughtUp, + /// last_read < highest. Keep both counts. hasUnreadPosts = true. + StillUnread, +} +``` + +这是 `patchedTopicRow`(`FireHomeFeedStore.swift` 105–109 行)的原公式。`lastRead == nil` 时用行上已有的 `hasUnreadPosts`,为 false 则清零,不是「两个计数字段都不动」。`lastRead < highest` 的比较只在 Rust。patch 结构体没有 `like_count`:`patchedTopicRow` 不写 `likeCount`。 + +只在 header 的 `posts_count` / `reply_count` / `views` / `last_read_post_number` / `highest_post_number` 或上述未读结果会改变该行时设置 `home_row_patch`。只改赞的 generation 为 `None`,不写磁盘。 + +内存行:`FireHomeFeedStore.applyHomeRowCountPatch` 按三态赋值。话题不在 `topicEntities` 则 no-op。 + +磁盘(今天的 `patchTopicCounts` 不写磁盘,这是新增,范围写死):`FireCore::patch_cached_home_topic_counts` 的键是 `current_auth_scope_hash()` 加上 `topic_list_cache_scope_key(&self.current_home_topic_list_query())`。`HomeTopicListScope` 不是这个字符串。`FireStore` 增加 `topic_list_cache_list_pages(auth_scope_hash, scope_key) -> Vec<(u32, String)>`,只列这一对键下的页。命中后同时改两处,禁止调用 `topic_row_from_topic`(它把 `has_unread_posts` 写成 `unread_posts > 0`,和 `patchedTopicRow` 不一致): + +- `topics[]` 里匹配的 `TopicSummary`:`posts_count`、`reply_count`、`views`、`last_read_post_number`、`highest_post_number`、`unread_posts`、`new_posts`。`TopicSummary` 没有 `has_unread_posts`。 +- `rows[]` 里匹配的 `TopicRow`:嵌套 `topic` 的同一组计数字段,加上行自己的 `has_unread_posts`。`WhenLastReadMissing` 读的是这个 `TopicRow.has_unread_posts`,不是 summary。 + +写回用 `topic_list_cache_write`,键不变。不调用 `notify_topic_list`。不扫其它 scope。 + +PR-B 删除 `patchedTopicRow` 和 `patchTopicCounts`。`FireTopicListMessageBusRefreshTests` 改断言 `applyHomeRowCountPatch`。未读三态的单元测试放在 Rust,Swift 不再留第二份公式。 + +### Core 类型 + +```rust +// fire-core/src/core/topic_detail_session.rs + +pub const TOPIC_DETAIL_INITIAL_BATCH: u16 = 40; +pub const TOPIC_DETAIL_LOAD_MORE_BATCH: u16 = 40; +pub const TOPIC_DETAIL_MAX_AUTO_BATCHES: u8 = 3; +pub const TOPIC_DETAIL_MAX_AUTO_POSTS: u16 = 120; +pub const TOPIC_DETAIL_PREFETCH_THRESHOLD: u32 = 10; +pub const TOPIC_DETAIL_FORWARD_EXPANSION: u32 = 60; +pub const TOPIC_DETAIL_HYDRATION_PAGE: usize = 30; +pub const TOPIC_DETAIL_HYDRATION_ITERS: u8 = 8; +pub const TOPIC_DETAIL_VISIBLE_DEBOUNCE: Duration = Duration::from_millis(120); +pub const TOPIC_DETAIL_LIST_TAIL_THRESHOLD: u32 = 5; +pub const TOPIC_DETAIL_REPLY_CONTEXT_BATCH: usize = 20; +pub const TOPIC_DETAIL_REFRESH_DEBOUNCE: Duration = Duration::from_millis(1500); +pub const TOPIC_DETAIL_PRESENCE_HEARTBEAT: Duration = Duration::from_secs(30); +pub const TOPIC_DETAIL_REQUEST_TIMEOUT: Duration = Duration::from_secs(30); + +pub struct TopicDetailOpenRequest { + pub topic_id: u64, + pub owner_token: String, + pub slug_hint: Option, + pub target_post_number: Option, + /// Local cache bypass for `open` only. Not the server query bit. + pub bypass_cache: bool, + /// `TopicDetailSourceQuery.force_load`. Does not decide whether to skip HTTP. + pub force_load: bool, + pub track_visit: bool, + pub allow_suggested_unread_root: bool, +} + +pub trait TopicDetailObserver: Send + Sync { + fn on_snapshot(&self, snapshot: TopicDetailUiSnapshot); +} + +impl TopicDetailSessionRegistry { + pub fn open( + &self, + request: TopicDetailOpenRequest, + observer: Arc, + ) -> Arc; + /// Drops only this owner and its observer. Last owner unsubscribes, + /// cancels tasks, and removes the session. Same token re-open replaces + /// the observer; it does not append a second one. + pub fn release(&self, topic_id: u64, owner_token: &str); + pub fn close_all(&self); + /// Transient unauth. Cancels actor HTTP. Keeps owners and the last Ready snapshot. + pub fn cancel_inflight_http(&self); +} + +impl TopicDetailSession { + pub fn release_owner(&self, owner_token: &str); + /// Always HTTP. No cache short-circuit. `force_load` is only the server query bit. + pub fn reload( + &self, + target_post_number: Option, + force_load: bool, + track_visit: bool, + allow_suggested_unread_root: bool, + ); + pub fn load_more(&self); + pub fn note_visible_posts(&self, post_numbers: Vec); + pub fn note_filtered_feed_tail(&self, item_count: u32, visible_max_item: Option); + pub fn note_scroll_interaction(&self, active: bool); + pub fn acknowledge_scroll_target(&self, post_number: u32); + pub fn clear_scroll_target(&self); + pub fn begin_reply_typing(&self); + pub fn end_reply_typing(&self); + pub fn reload_ai_summary(&self, skip_age_check: bool); + pub fn load_reply_context(&self, post_id: u64); + pub async fn prepare_edit(&self, post_id: u64) -> Result; + pub async fn ensure_flag_types(&self) -> Result<(), FireCoreError>; + pub async fn submit_reply( + &self, + raw: String, + reply_to_post_number: Option, + scroll_to_created: bool, + ) -> Result<(), FireCoreError>; + pub async fn create_boost(&self, post_id: u64, raw: String) -> Result<(), FireCoreError>; + pub async fn delete_boost(&self, post_id: u64, boost_id: u64) -> Result<(), FireCoreError>; + pub async fn update_post( + &self, + post_id: u64, + raw: String, + edit_reason: Option, + ) -> Result<(), FireCoreError>; + pub async fn delete_post(&self, post_id: u64) -> Result<(), FireCoreError>; + pub async fn recover_post(&self, post_id: u64) -> Result<(), FireCoreError>; + pub async fn flag_post( + &self, + post_id: u64, + flag_type_id: u32, + message: Option, + ) -> Result<(), FireCoreError>; + pub async fn set_liked(&self, post_id: u64, liked: bool) -> Result<(), FireCoreError>; + pub async fn toggle_reaction( + &self, + post_id: u64, + reaction_id: String, + ) -> Result<(), FireCoreError>; + pub async fn vote_poll( + &self, + post_id: u64, + poll_name: String, + options: Vec, + ) -> Result<(), FireCoreError>; + pub async fn unvote_poll( + &self, + post_id: u64, + poll_name: String, + ) -> Result<(), FireCoreError>; + pub async fn vote_topic(&self, voted: bool) -> Result<(), FireCoreError>; + pub async fn accept_solution(&self, post_id: u64, accepted: bool) -> Result<(), FireCoreError>; + pub async fn create_bookmark( + &self, + bookmarkable_id: u64, + bookmarkable_type: String, + name: Option, + reminder_at: Option, + auto_delete_preference: Option, + ) -> Result<(), FireCoreError>; + pub async fn update_bookmark( + &self, + bookmark_id: u64, + name: Option, + reminder_at: Option, + auto_delete_preference: Option, + ) -> Result<(), FireCoreError>; + pub async fn delete_bookmark(&self, bookmark_id: u64) -> Result<(), FireCoreError>; + pub async fn set_notification_level(&self, level: i32) -> Result<(), FireCoreError>; + pub async fn update_topic( + &self, + title: String, + category_id: u64, + tags: Vec, + ) -> Result<(), FireCoreError>; + pub async fn report_timings(&self, topic_time_ms: u32, timings: Vec) -> Result; +} + +``` + +唯一的拉页实现(不是 `cfg(test)`,actor、兼容 RPC、测试共用): + +```rust +pub(crate) async fn load_topic_detail_source_snapshot( + core: &FireCore, + query: TopicDetailSourceQuery, +) -> Result; + +pub(crate) async fn load_topic_detail_page( + core: &FireCore, + query: TopicDetailSourceQuery, +) -> Result; + +pub(crate) async fn load_more_topic_detail_posts( + core: &FireCore, + query: LoadMoreTopicPostsQuery, +) -> Result; +``` + +`FireCore::fetch_topic_detail_source_snapshot` / `fetch_topic_detail_page` / `load_more_topic_posts` 只转发这三个函数。兼容路径无 observer、无 MessageBus 订阅、无预取任务、无 owner。它写入的 `TopicDetailSourceSession` 就是 `load_more` 用 `(topic_id, session_id)` 查找的那张表(今天的 `FireTopicDetailSourceRuntime.sessions_by_topic_id`)。query 上的 `initial_batch_size`、`load_more_batch_size`、`max_auto_*`、`force_load`、`track_visit`、`allow_suggested_unread_root`、`target_post_number` 原样生效。Android `TopicRepository` 仍传 40/40/3/120,运行时行为不变。actor 自己组 query:批量用会话常量,访问与未读根用 open/reload 契约,不读 Swift 传来的批量。 + +`prepare_edit` 是唯一允许的拉取:编辑器要预填 raw,raw 不是 cell 的 cooked HTML。读会话里已有 `TopicPost.raw`,没有再走现有 `fetch_post`。Swift 把字符串放进编辑草稿(本地 chrome),不写回行字典。 + +空正文拒绝在 Rust 再做一次(`FireCoreError`),Swift composer 仍可在点击前本地拦住。这是守卫,不是两套分页策略。 + +写命令 `async` 只为让 composer 拿到 `quickReplyError`。成功路径不返回帖。点赞在 HTTP 前推乐观快照。回复和 boost 不插占位行,见「回复插入与 boost」。`like` 无 body 时与今天一样:有 `PostReactionUpdate` 就覆盖,没有就在会话内再拉一页(`track_visit = false`),Swift 不参与。 + +`create_bookmark` 包装 `FireCore::create_bookmark`(`interactions.rs`),`bookmarkable_type` 为 `"Topic"` 或 `"Post"`,保留 `auto_delete_preference`。成功后把返回的 bookmark id 写到 header(话题)或行(帖)。话题书签抬 `chrome_revision`。帖书签改行上的 bookmark 字段,从而改变 `interaction_checksum`(`postContentToken` 收录 bookmark,`postLayoutContentToken` 不收录)。`update_bookmark` / `delete_bookmark` 同样包装现有函数。没有 `TopicBookmarkTarget`,也没有单独的 `clear_bookmark`。 + +`update_topic` 成功后更新 chrome 的 title / category / tags 并抬 `chrome_revision`。计数 patch 不带标题、分类、标签、摘要。Swift `FireAppViewModel.updateTopic` 在命令返回后仍调用现有 `refreshHomeFeedIfPossible(force: true)`。excerpt 在这次首页刷新返回前保持旧值,这是有意的。`delete_post` / `recover_post` / `flag_post` / `update_post` 的 Swift 转发在成功后仍调用现有 `refreshHomeFeedIfPossible(force: false)`,对齐 `performPostManagementMutation`。会话同时在 header 计数变化时发 home patch。 + +`bypass_cache` 与 `force_load` 分开,不从其中一个推断另一个。缓存短路只在 `open`,而且只在 `bypass_cache == false` 且已有 source 已包含目标楼时:重推快照,不打网。`reload` 永远打 HTTP。对账、MessageBus、书签、通知级别、帖子编辑器、改话题用的 reload 固定 `force_load = false`,`track_visit = false`,`allow_suggested_unread_root = false`。`reload_ai_summary` 不走这次 reload。Android 兼容 RPC 把 query 的 `force_load`、`track_visit`、`allow_suggested_unread_root` 原样传入 `load_topic_detail_page`,没有 `open` 的缓存短路。 + +调用点不再写 `loadTopicDetail(force:)`。三位是: + +| 调用 | bypass_cache | force_load | track_visit | +| --- | --- | --- | --- | +| 首次 `open`,调用方 force == false(`viewDidAppear` 那条 `loadTopicDetail`) | false | false(仅当这次真的打网) | true | +| 下拉刷新 `performRefresh` | true | true | true | +| 信息流错误重试 `onLoadTopicDetail`(`FireTopicDetailFeedCellFactory` 的重试按钮) | true | true | true | +| Android `TopicDetailViewModel.loadTopicDetail` → `open` | true | true | true | + +`allow_suggested_unread_root` 不在这张表里单独发明:iOS 仍是「无目标且没有 Ready 快照」。Android 保持今天的 `targetPostNumber == null && _detail.value == null`,不改。下拉刷新和错误重试的 `track_visit = true` 是有意的,和删掉的编辑器保存不同。这两处用同一个 owner 再 `open`,不是 `reload`,这样 `bypass_cache` 才存在。 + +`openAdvancedComposer` 与 `openQuoteComposer` 的 `onReplySubmitted` 不再 `loadTopicDetail`。`submit_reply` 已经用 `force_load = false`、`track_visit = false` 对账。引用回复传 `scroll_to_created = true`:会话把 `create_reply` 返回帖的 `post_number` 写成 `scroll_target`。这替换今天 `openQuoteComposer` 里跳到被引用帖 `post.postNumber` 的行为。高级回复传 `scroll_to_created = false`。 + +`report_timings` 不改变快照结构。失败吞掉并返回 `false`,对齐 `FireTopicInteractionService.reportTopicTimings`。 + +### 快照(UI 投影) + +`fire-models` 新文件。不含 `raw_stream_ids`、`TopicSourceCursor`、`loaded_ranges`、cooked `String`。 + +```rust +pub struct TopicDetailUiSnapshot { + pub topic_id: u64, + pub generation: u64, + pub phase: TopicDetailPhase, // Loading | Ready | Failed + pub load_error: Option, + pub notice: Option, + pub has_more: bool, + pub is_loading_more: bool, + pub load_more_error: Option, + pub scroll_target_post_number: Option, + pub collection_revision: u64, + pub chrome_revision: u64, + pub sidecar_revision: u64, + pub interaction_revision: u64, + pub chrome: TopicDetailChrome, + pub composer: TopicDetailComposerModel, + pub sidecar: TopicDetailSidecarModel, + pub rows: Vec, + pub focused_reply_context: Option, + pub flag_types: Vec, + pub home_row_patch: Option, +} + +pub struct TopicDetailUiRow { + pub post_id: u64, + pub post_number: u32, + pub root_post_number: u32, + pub parent_post_number: Option, + pub depth: u16, + pub has_children: bool, + pub is_last_sibling: bool, + pub descendant_count: u32, + pub author: TopicDetailAuthorDisplay, + pub presentation: AttachedPresentation, // FFI 层换成 RenderDocumentHandle + pub layout_checksum: u64, + pub interaction_checksum: u64, + pub created_at: Option, + pub reply_count: u32, + pub reply_to_username: Option, + pub like_count: u32, + pub reactions: Vec, + pub current_reaction_id: Option, + pub polls: Vec, + pub boosts: Vec, + pub accepted_answer: bool, + pub can_accept_answer: bool, + pub can_unaccept_answer: bool, + pub can_edit: bool, + pub can_delete: bool, + pub can_recover: bool, + pub can_boost: bool, + pub bookmarked: bool, + pub bookmark_id: Option, + pub hidden: bool, + pub is_mutating: bool, + pub is_loading_reply_context: bool, + pub is_original_post: bool, +} + +pub struct TopicDetailReactionChip { + pub id: String, + pub count: u32, + pub selected: bool, +} + +pub struct TopicHomeRowCountPatch { + pub topic_id: u64, + pub posts_count: u32, + pub reply_count: u32, + pub views: u32, + pub last_read_post_number: Option, + pub highest_post_number: u32, + pub unread: TopicHomeUnreadDecision, +} +``` + +没有 `like_count`。`patchedTopicRow` 不拷贝它。 + +### 嵌套显示结构 + +字段来自 `TopicPost`、`TopicPostAuthorMetadata`、`TopicPostBoost`、`Poll`、`TopicHeader`。boost 与正文用 `RenderDocumentHandle`,cooked 字符串不出 FFI。 + +`TopicDetailAuthorDisplay`:`username`,`name`,`avatar_template`,`user_id`,`user_title`,`primary_group_name`,`flair_url`,`flair_name`,`flair_bg_color`,`flair_color`,`flair_group_id`,`moderator`,`admin`,`group_moderator`,`user_status_emoji`,`user_status_description`。 + +`TopicDetailPollDisplay`:`id`,`name`,`kind`,`status`,`results`,`voters`,`user_votes`。选项:`id`,`html`,`plain_text`,`votes`。选项 html 是投票控件要画的,不是帖子 cooked。 + +`TopicDetailBoostDisplay`:`id`,`display_text`,`user`(`id`,`username`,`name`,`avatar_template`),`can_delete`,`can_flag`,`user_flag_status`,`available_flags`,`presentation: RenderDocumentHandle`。没有 `cooked`。 + +`TopicDetailChrome`:`title`,`slug`,`archetype`,`bookmarked`,`bookmark_id`,`bookmark_name`,`bookmark_reminder_at`,`notification_level`,`can_edit`,`category_id`,`tags`(`TopicTag` 的 name),`views`,`posts_count`,`reply_count`,`like_count`(话题赞,给统计行,不进首页 patch),`vote_count`,`user_voted`,`can_vote`,`has_accepted_answer`,`created_at`,`highest_post_number`,`last_read_post_number`。参与者:`user_id`,`username`,`name`。 + +`TopicDetailComposerModel`:`typing_users`(`id`,`username`,`avatar_template`),`is_submitting`。没有草稿、没有最短回复长度、没有 `canWrite`。 + +`TopicDetailSidecarModel`:`summarized_text`,`algorithm`,`outdated`,`can_regenerate`,`new_posts_since_summary`,`updated_at`,`is_loading`,`error`。没有 `isTopicAiSummaryExpanded`。 + +`TopicDetailReplyContext`:`root_post_id`,已并入主行的 `appended_post_ids`,`history_rows: Vec`。 + +行上另外要有:`updated_at`,`post_type`,`reply_to_user`(`username`,`name`,`avatar_template`),`bookmark_name`,`bookmark_reminder_at`。`can_boost` 已在行上。 + +VC 继续从 `SessionState` 读,不拷进话题快照,也不要在改 builder 时删掉: + +- `canWriteInteractions` = `FireAppViewModel.canStartAuthenticatedMutation` +- `baseURLString` = `session.bootstrap.baseUrl`,空则 `https://linux.do` +- `minimumReplyLength` = `FireTopicPresentation.minimumReplyLength`,私信用 `minPersonalMessagePostLength`,否则 `minPostLength` +- 是否私信线程用 chrome 的 `archetype`,经现有 `FireTopicPresentation.isPrivateMessageArchetype` + +### Checksum + +Rust 只哈希服务端字段。Swift builder 把本地 chrome 折进去。验收标准是今天的 `postLayoutContentToken`(`FireTopicDetailRuntimeSnapshotBuilder.swift` 418–430 行),字段为: + +- `post.id` +- `FirePostAuthorMetadataDisplay.contentToken` +- `renderContent?.signature.token ?? "pending"` +- `pollsContentToken` +- `FirePostBoostDisplay.contentToken`(id、用户、displayText、presentation plain text、canDelete、canFlag,不是条数) +- `String(!post.reactions.isEmpty)`(空与非空,不是完整反应列表) +- `String(replyShortcutCount != nil)` +- `String(isReplyThreadExpanded)` +- `String(isReactionPickerExpanded)` +- `String(textExpansionState.isExpanded)` +- `String(textExpansionState.isCollapsible)` + +`layout_checksum` 只覆盖其中的服务端部分:post id、作者 metadata、presentation checksum、poll token、boost token、`reactions.is_empty()`。回复快捷方式是否为 nil、回复树展开、表情条展开、正文展开,留在 Swift。 + +`interaction_checksum` 覆盖 `postContentToken` 里的服务端部分:楼层号、用户名、头像、created/updated、like count、reply count、完整反应列表(id、kind、count、can_undo)、current reaction id、accepted / can_edit / can_delete / can_recover / hidden、bookmark 三字段加 bookmarked、`is_mutating`、`is_loading_reply_context`。搜索高亮、`canWriteInteractions`、正文展开、表情条展开留在 Swift。 + +builder 组 token,而不是赋值: + +- layout token = `layout_checksum` + 上面四项本地 chrome(shortcut、回复树、表情条、正文展开) +- in-place token = `interaction_checksum` + layout token 里 Swift 已折入的本地项 + `isSearchHighlighted` + `canWriteInteractions` +- 摘要卡再把 `isTopicAiSummaryExpanded` 折进该卡的 layout token + +禁止 `contentToken = layout_checksum` 或 `inPlaceUpdateToken = interaction_checksum`。首枚反应让 `reactions.is_empty()` 翻转,layout token 变,走可见行 relayout。之后的续赞只变 `interaction_checksum`,走 in-place。正文展开不进 `FireTopicDetailFeedInvalidationToken`(今天也没有 `expandedPostTextIDs`),靠 `applyLocalInteractionSnapshot` 里 layout token 变化 relayout。搜索高亮留在 in-place token;`activeSearchPostID` 仍在 invalidation token 上。 + +`collection_revision`:插删行、分页、首屏替换、加载/错误/has_more 变化。`interaction_revision`:只改表情或 mutating,且 layout checksum 不变。`chrome_revision`:标题、话题书签、通知级别、投票数。`sidecar_revision`:AI 摘要与 notice。展开回复树不在 Rust revision 里,VC 把 `expandedReplyRootPostIDs` 放进自己的 invalidation token,继续走 collection diff。 + +行集合是已加载树的前序,含楼主。二级楼默认隐藏仍由 Swift `makeReplyDisplayPlan` 用 `expandedReplyRootPostIDs` 过滤。Rust 不接收展开集合。 + +`focused_reply_context` 在 `load_reply_context` 后填充:已并入主行的子楼 id,加历史行(今天的 `postReplyHistoryByPostID`)。`applyReplyContextRowsIfPossible` 的并树进会话,用现有 `TopicTreeRow` 规则,不在 Swift 改 parent/depth。 + +`load_error` 枚举:`Network`、`LoginRequired`、`Unrecoverable { message }`。VC 只展示,不 `switch` 后重试。 + +### 会话私有状态 + +```rust +struct SessionInner { + source: TopicDetailSourceSession, // 现有私有结构 + tree: TopicTreePresentation, + generation: u64, + scroll_target: Option, + scroll_target_exhausted: bool, + window: TopicWindow, // 现 FireTopicDetailWindowState 的语义 + scroll_active: bool, + deferred_refresh: DeferredRefresh, // None | Pending | Ready(snapshot) + owners: HashMap>, + optimistic: HashMap, // 回滚用,不对 Swift 暴露 +} +``` + +`note_visible_posts` 在 120ms debounce 后,坐标是楼层号,不是列表下标: + +- 可见楼层距已加载窗口边 ≤ `PREFETCH_THRESHOLD`(10)时,按 `FORWARD_EXPANSION`(60)与 `HYDRATION_PAGE`(30)补 `fetch_topic_posts`,最多 `HYDRATION_ITERS`(8)。等价 `expandRequestedRangeIfNeeded` + `hydrateTopicPostsToTargetIfNeeded`。 +- 有未完成 `scroll_target` 时沿用 `nextRequestedRangeForUnresolvedTarget` 的跳转,直到命中或 `scrollTargetIsExhausted`。窗口上限仍是今天的 `FireTopicDetailWindowState.maxWindowSize`(200),私有,不进 FFI。命中前快照带 `scroll_target_post_number`。VC `acknowledge_scroll_target` 后清空。 + +`note_filtered_feed_tail` 的坐标是 `makeReplyDisplayPlan` 隐藏二级回复之后的列表下标,不是快照全序行。谓词与 `fireTopicDetailShouldLoadMore` 相同:`item_count > 0`,`visible_max_item` 为 Some,且 `item_count - visible_max_item <= 5`,并且 `has_more`。满足则跑与 `load_more_topic_posts` 相同的连批停止条件。Swift 删掉 `fireTopicDetailShouldLoadMore`,避免两份阈值。协调器只上报两个整数。 + +`load_more` 是用户点 footer 的一拍,同一停止条件,不看尾阈值。 + +### 回复插入与 boost + +`submit_reply` 不在 HTTP 前插占位行。`create_reply` 返回 `TopicPost` 之后,按 `applyCreatedReply`(`+Mutations.swift` 537–581 行): + +- id 不在 `raw_stream_ids` 则 append +- 合并进 `posts_by_id` +- `posts_count = max(old + 1, stream_len)`,`reply_count = max(old + 1, posts_count.saturating_sub(1))` +- `highest_post_number = max(highest, post_number)`,`last_read = max(last_read.unwrap_or(0), post_number)` +- 若窗口 `requested_range.upper_bound >= 插入前的 stream_len`,把上界伸到新的 stream 末尾 +- 重建树,推快照。header 计数变了才带 `home_row_patch` +- 再 `reload(target: None, force_load: false, track_visit: false, allow_suggested_unread_root: false)` 对账。这一步必须打网,不能因为帖已经在 source 里就短路。 + +`create_boost` 成功后:该 id 不在列表则 append,`can_boost = false`。boost token 变,`layout_checksum` 变,抬 `collection_revision`(高度变,不是 in-place)。然后同一套 `track_visit = false` 的 reload。 + +### 恢复 + +- CF:请求继续走 foreground profile,现有 `retry_after_cloudflare_challenge`。会话不调用 Swift。 +- cookie:现有 `cookie_self_healing_handler`。 +- `StaleSessionResponse`:再打一次 HTTP,`force_load = true`,`track_visit` 保持这次加载的原值。这是服务端 query 位,不是缓存短路。仍失败才 `load_error`。 +- `LoginRequired`:不写 `FireAuthRecoveryHint`,不发明轮换原因。`FireAuthRecoveryHintReason` 仍只有 `TOnlyRotation` 与 `ForumSessionOnlyRotation`。`runAuthenticatedWritePreflight` 的 hint epoch 判断不动。 + +唤醒字段不进持久化信封。权威副本在 `FireSessionRuntimeState`,和 `auth_recovery_hint` 一样。`SessionSnapshot` 若为了 `SessionState::from_snapshot` 带上它,必须 `#[serde(skip)]`,而且 `update_session_persistence_revisions` 比较时忽略这一字段,不能单凭它增加 `snapshot_revision`。`export_session_json` / `PersistedSessionEnvelope` 因此写不进去。`restore_session_json` 在清 `auth_recovery_hint` 的同一处把 runtime 上的请求清掉(`persistence.rs` 第 39 行旁边)。 + +```rust +pub struct ReadPathLoginRequest { + pub generation: u64, + pub operation: String, +} + +// FireSessionRuntimeState +pub(crate) read_path_login_request: Option, + +// SessionSnapshot,只出现在 notify 推出去的副本上 +#[serde(skip)] +pub read_path_login_request: Option, +``` + +`request_read_path_login(operation) -> u64` 写 runtime 字段。已有未完成的 generation 时,后来的 LoginRequired 加入这一代,不换号。`notify_session` 把该字段拷到推送副本上。`DebouncedEmitter` 仍是 100ms 取最新快照,未完成的请求留在 runtime 上,所以窗口里后到的快照仍带着它。不增加 epoch。 + +`applySession` 看到新 generation 时,不调用 `runReadPathLoginRecovery`。那只是 cookie 重放,没有 single-flight,也没有 headless。要跑的是 `attemptReadPathLoginRecovery` 去掉 `LoginRequired` 类型守卫之后的函数体,operation 用 `ReadPathLoginRequest.operation`: + +1. `attemptHostCookieResyncRecovery(operation:)`。同一 epoch 已有任务则 join。 +2. 只有它返回 false,才 `attemptMidSessionHeadlessReauth(operation:)`。 + +首页 store 继续自己调用带守卫的 `attemptReadPathLoginRecovery`,不改。 + +返回后 `applySession` 调 `FireSessionHandle::complete_read_path_login(generation, succeeded)`。实现在 `FireCore` 里走 registry,叫醒这一代的全部 waiter。不新增话题 observer。`succeeded == true` 时每个 waiter `reload(force_load: true, track_visit: 这次加载的原值, allow_suggested_unread_root: false)` 一次。`reload` 必打网。`succeeded == false` 时这些快照停在 `LoginRequired`,不第二次。无关 epoch 变化不触发。 + +### 三种会话过渡 + +`FireTopicDetailStore.applySession` 保留,只转发 readiness。`FireAppViewModel.applySession` 继续调用它。 + +| 过渡 | 条件 | 行为 | +| --- | --- | --- | +| 完整登出 | `!hasLoginCookie && !hasCurrentUser` | 每个 handle `close`(只释放自己的 owner)。registry 无 owner 后拆会话。Swift 清空 `snapshots` | +| 短暂不可读 | `!canReadAuthenticatedApi` 且不是完整登出 | `cancel_inflight_http`。保留 owner 和最后一帧 Ready 快照。不推空快照 | +| 读路径恢复成功 | `complete_read_path_login(succeeded: true)` | `reload(force_load: true)`,`track_visit` 不变,必打网。先不推空快照。失败则停在 `LoginRequired` | + +`canReadAuthenticatedApi == true` 时 `applySession` 立即 return。cookie / CSRF 造成的 epoch 增加不走登出分支。 + +乐观更新:`set_liked` / `toggle_reaction` 在 actor 里克隆帖、改 count 与 current reaction、推 interaction 快照、置 `is_mutating`。失败恢复克隆。成功用 `PostReactionUpdate` 覆盖。与 `applyOptimisticReactionChange` 同一规则(heart id `"heart"`,再点同一 reaction 即取消)。 + +MessageBus:`TopicDetail` 与 `TopicReaction` 走 1.5s debounce 后 `reload(target: None, force_load: false, track_visit: false, allow_suggested_unread_root: false)`,必打网。`detail_event_type == "polls"` 走同一条,不新增 kind。滚动中:请求还没结束记 `Pending`;请求已结束则把快照放进 `Ready`,对齐 `deferredTopicDetailRefreshPayloads`。`note_scroll_interaction(false)` 若是 `Ready`,直接推这帧,不再请求;若是 `Pending`,再 reload。`presence` 读 `topic_reply_presence_state`,滤掉当前用户,写入 composer。Swift 不再滤。 + +AI 摘要:首包后若 `summarizable` 且无摘要,会话调用现有 `fetch_topic_ai_summary`。loading 不抬 `collection_revision`(今天 `setLoadingTopicAiSummary` 的注释:避免空 chrome 抖动)。失败只抬 sidecar。 + +### FFI + +```rust +// fire-uniffi-topics/src/session.rs + +#[uniffi::export(with_foreign)] +pub trait TopicDetailObserver: Send + Sync { + fn on_snapshot(&self, snapshot: TopicDetailUiSnapshotState); +} + +#[derive(uniffi::Object)] +pub struct TopicDetailSessionHandle { + inner: Arc, + topic_id: u64, + owner_token: String, +} + +#[uniffi::export] +impl FireTopicsHandle { + pub fn open_topic_detail( + &self, + request: TopicDetailOpenRequestState, + observer: Arc, + ) -> Result, FireUniFfiError>; +} + +#[uniffi::export] +impl TopicDetailSessionHandle { + /// Handle stores the owner token from open. close calls + /// registry.release(topic_id, owner_token) for that owner only. + pub fn close(&self); + /// Always HTTP. `force_load` is `TopicDetailSourceQuery.force_load`, not a cache bypass. + pub fn reload( + &self, + target_post_number: Option, + force_load: bool, + track_visit: bool, + allow_suggested_unread_root: bool, + ); + pub fn load_more(&self); + pub fn note_visible_posts(&self, post_numbers: Vec); + pub fn note_filtered_feed_tail(&self, item_count: u32, visible_max_item: Option); + pub fn note_scroll_interaction(&self, active: bool); + pub fn acknowledge_scroll_target(&self, post_number: u32); + pub fn clear_scroll_target(&self); + pub fn begin_reply_typing(&self); + pub fn end_reply_typing(&self); + pub fn reload_ai_summary(&self, skip_age_check: bool); + pub fn load_reply_context(&self, post_id: u64); + pub async fn prepare_edit(&self, post_id: u64) -> Result; + pub async fn submit_reply(&self, raw: String, reply_to_post_number: Option, scroll_to_created: bool) -> Result<(), FireUniFfiError>; + pub async fn create_boost(&self, post_id: u64, raw: String) -> Result<(), FireUniFfiError>; + pub async fn delete_boost(&self, post_id: u64, boost_id: u64) -> Result<(), FireUniFfiError>; + pub async fn update_post(&self, post_id: u64, raw: String, edit_reason: Option) -> Result<(), FireUniFfiError>; + pub async fn delete_post(&self, post_id: u64) -> Result<(), FireUniFfiError>; + pub async fn recover_post(&self, post_id: u64) -> Result<(), FireUniFfiError>; + pub async fn flag_post(&self, post_id: u64, flag_type_id: u32, message: Option) -> Result<(), FireUniFfiError>; + pub async fn ensure_flag_types(&self) -> Result<(), FireUniFfiError>; + pub async fn set_liked(&self, post_id: u64, liked: bool) -> Result<(), FireUniFfiError>; + pub async fn toggle_reaction(&self, post_id: u64, reaction_id: String) -> Result<(), FireUniFfiError>; + pub async fn vote_poll(&self, post_id: u64, poll_name: String, options: Vec) -> Result<(), FireUniFfiError>; + pub async fn unvote_poll(&self, post_id: u64, poll_name: String) -> Result<(), FireUniFfiError>; + pub async fn vote_topic(&self, voted: bool) -> Result<(), FireUniFfiError>; + pub async fn accept_solution(&self, post_id: u64, accepted: bool) -> Result<(), FireUniFfiError>; + pub async fn create_bookmark(&self, bookmarkable_id: u64, bookmarkable_type: String, name: Option, reminder_at: Option, auto_delete_preference: Option) -> Result<(), FireUniFfiError>; + pub async fn update_bookmark(&self, bookmark_id: u64, name: Option, reminder_at: Option, auto_delete_preference: Option) -> Result<(), FireUniFfiError>; + pub async fn delete_bookmark(&self, bookmark_id: u64) -> Result<(), FireUniFfiError>; + pub async fn set_notification_level(&self, level: i32) -> Result<(), FireUniFfiError>; + pub async fn update_topic(&self, title: String, category_id: u64, tags: Vec) -> Result<(), FireUniFfiError>; + pub async fn report_timings(&self, topic_time_ms: u32, timings: Vec) -> Result; +} +``` + +适配器: + +```rust +struct FfiTopicDetailObserver { + inner: Arc, +} + +impl fire_core::TopicDetailObserver for FfiTopicDetailObserver { + fn on_snapshot(&self, snapshot: fire_core::TopicDetailUiSnapshot) { + self.inner.on_snapshot(TopicDetailUiSnapshotState::from_core(snapshot)); + } +} +``` + +`from_core` 只做字段拷贝,并把 `AttachedPresentation` 交给已有 `intern_presented_handle`。禁止在这里决定预取、重试、未读。 + +兼容包装(删之前): + +```rust +impl FireTopicsHandle { + pub async fn fetch_topic_detail_page(...) -> Result { + // load_topic_detail_page(query.into())。batch、force、track_visit、 + // allow_suggested_unread_root 都保留。无 observer、无订阅、无预取、无 owner。 + } + pub async fn fetch_topic_detail_source_snapshot(...) -> Result { + // load_topic_detail_source_snapshot。同一张 session 表。 + } + pub async fn load_more_topic_posts(...) -> Result { + // load_more_topic_detail_posts。cursor.session_id 必须命中刚才写入的 source session。 + } +} +``` + +`fetch_topic_posts`、`like_post` 等非详情屏幕也会用的 RPC 保持原样,直到 Android 详情不再通过它们改本地帖。详情屏幕的 iOS 路径停止调用 `fetchTopicDetailPage` / `loadMoreTopicPosts`。 + +晚到快照:`generation` 单调。Swift 丢弃更旧的 generation。 + +### Swift 之后的 store 与 VC + +```swift +@MainActor +final class FireTopicDetailStore: ObservableObject { + @Published private(set) var snapshots: [UInt64: TopicDetailUiSnapshot] = [:] + + func open(topicId: UInt64, ownerToken: String, slug: String?, targetPostNumber: UInt32?, bypassCache: Bool, forceLoad: Bool, trackVisit: Bool, allowSuggestedUnreadRoot: Bool) + func close(topicId: UInt64, ownerToken: String) + func reload(topicId: UInt64, targetPostNumber: UInt32?, forceLoad: Bool, trackVisit: Bool, allowSuggestedUnreadRoot: Bool) + func loadMore(topicId: UInt64) + func noteVisiblePosts(topicId: UInt64, postNumbers: Set) + func noteFilteredFeedTail(topicId: UInt64, itemCount: Int, visibleMaxItem: Int?) + func applySession(_ session: SessionState) + func noteScrollInteraction(topicId: UInt64, active: Bool) + func acknowledgeScrollTarget(topicId: UInt64, postNumber: UInt32) + func clearScrollTarget(topicId: UInt64) + func beginReplyTyping(topicId: UInt64) + func endReplyTyping(topicId: UInt64) async + func reloadAiSummary(topicId: UInt64, skipAgeCheck: Bool) + func loadReplyContext(topicId: UInt64, postId: UInt64) + func prepareEdit(topicId: UInt64, postId: UInt64) async throws -> String + func submitReply(topicId: UInt64, raw: String, replyToPostNumber: UInt32?, scrollToCreated: Bool) async throws + func setPostLiked(topicId: UInt64, postId: UInt64, liked: Bool) async throws + func togglePostReaction(topicId: UInt64, postId: UInt64, reactionId: String) async throws + func votePoll(topicId: UInt64, postId: UInt64, pollName: String, options: [String]) async throws + func unvotePoll(topicId: UInt64, postId: UInt64, pollName: String) async throws + func voteTopic(topicId: UInt64, voted: Bool) async throws + func updatePost(topicId: UInt64, postId: UInt64, raw: String, editReason: String?) async throws + func deletePost(topicId: UInt64, postId: UInt64) async throws + func recoverPost(topicId: UInt64, postId: UInt64) async throws + func flagPost(topicId: UInt64, postId: UInt64, flagTypeId: UInt32, message: String?) async throws + func ensureFlagTypes(topicId: UInt64) async throws + func createBookmark(topicId: UInt64, bookmarkableId: UInt64, bookmarkableType: String, name: String?, reminderAt: String?, autoDeletePreference: Int32?) async throws + func updateBookmark(topicId: UInt64, bookmarkId: UInt64, name: String?, reminderAt: String?, autoDeletePreference: Int32?) async throws + func deleteBookmark(topicId: UInt64, bookmarkId: UInt64) async throws + func setNotificationLevel(topicId: UInt64, level: Int32) async throws + func updateTopic(topicId: UInt64, title: String, categoryId: UInt64, tags: [String]) async throws + func acceptSolution(topicId: UInt64, postId: UInt64, accepted: Bool) async throws + func reportTimings(topicId: UInt64, topicTimeMs: UInt32, timings: [UInt32: UInt32]) async -> Bool + func reset() + + func snapshot(for topicId: UInt64) -> TopicDetailUiSnapshot? { snapshots[topicId] } +} + +final class FireTopicDetailSnapshotSink: TopicDetailObserver, @unchecked Sendable { + func onSnapshot(snapshot: TopicDetailUiSnapshot) { + Task { @MainActor in store.apply(snapshot) } + } +} +``` + +`apply`:若 `generation` 不旧于已应用值,替换 `snapshots[id]`;若 `homeRowPatch != nil`,调 `FireAppViewModel.applyHomeRowCountPatch`。不合并行。 + +`FireHomeFeedStore.applyHomeRowCountPatch` 替换 `patchTopicCounts`。同一 PR 删除 `patchedTopicRow` 与 `patchTopicCounts`。`FireTopicDetailModalRouter.presentBookmarkEditor` 的话题详情 `onReload` 不再调用 `loadTopicDetail`;保存和删除改走 store 的 create / update / delete bookmark。`presentTopicBookmarkEditor` / `presentPostBookmarkEditor` 同样改。 + +VC `buildCurrentFeedState` 改为读 `snapshot.rows`、`phase`、`hasMore`、`collectionRevision`、`scrollTarget`。`buildCurrentInteractionState` 只保留三个 expanded 集合。`mutating` / reply-context loading 来自行字段。`canWriteInteractions`、`baseURLString`、`minimumReplyLength` 仍从 session / bootstrap 读。Combine 从多个 revision 字典改成 `$snapshots` 按 `collection` / `chrome` / `sidecar` / `interaction` 去重。本地展开仍走 `applyLocalInteractionSnapshot`,主线程,不经 Rust。 + +`FireTopicDetailRuntimeConfiguration` 丢掉 `detail: TopicDetailState?` 与 `postLookup`。builder 用行 DTO,再把本地 chrome 折进 token。禁止把 `contentToken` 或 `inPlaceUpdateToken` 设成裸的 Rust checksum。管道 `apply` 的三档判断不改。 + +分页协调器:`fireTopicDetailShouldLoadMore` 删除。过滤后的 `itemCount` / `visibleMaxItem` 经 `noteFilteredFeedTail` 上报。footer 仍 `loadMore`。可见楼层号仍由 `FireTopicDetailVisibilityCoordinator.publishIfChanged` 上报。 + +### 错误与线程 + +| 错误 | 会话行为 | Swift 话题详情 | +| --- | --- | --- | +| Network | 快照 `Failed` + 文案 | 展示 | +| CF challenge | 网络层已弹 WebView 并重试 | 无感知 | +| cookie healing | 网络层已重试 | 无感知 | +| StaleSessionResponse | 内部 force 再读一次 | 无感知 | +| LoginRequired | 同一代请求。成功则 `force_load` reload 一次,`track_visit` 不变 | 只展示。`applySession` 先 `attemptHostCookieResyncRecovery`,失败再 `attemptMidSessionHeadlessReauth`。不调用 `runReadPathLoginRecovery` | +| Http 429 | 网络层已退避 | 最终失败才展示 | +| 写失败 | 回滚乐观快照,`Err` 给 composer | `quickReplyError` 本地 | + +禁止在主线程 `wait` UniFFI。`open` / `note_*` / `load_more` 是同步入队。写命令的 `async` 只 await 已在 runtime 上的 actor,Swift 侧在 `Task` 里调用。 + +## Phased Implementation + +每阶段结束工作区可编译。阶段内不要长期双源。iOS 在 Android ViewModel 迁移之前达到「store 只有快照 + VC 只有本地 chrome」。 + +### Phase 1 — Rust 会话 + 兼容投影 + +新文件: + +- `rust/crates/fire-models/src/topic_detail_ui.rs` +- `rust/crates/fire-core/src/core/topic_detail_session.rs` +- `rust/crates/fire-core/src/core/topic_detail_project.rs` +- `rust/crates/fire-uniffi-topics/src/session.rs` + +改: + +- `fire-models/src/lib.rs` 导出新类型 +- `fire-core/src/core/mod.rs`:`topic_detail_source` 换成 `topic_detail_sessions` +- `fire-core/src/core/topics.rs`:`fetch_topic_detail_page` / `load_more_topic_posts` / `fetch_topic_detail_source_snapshot` 只转发 `load_topic_detail_*`,不调用 `Registry.open`。无 observer、无 MessageBus 订阅、无预取、无 owner +- `fire-core/src/core/messagebus.rs`:内部 listener 列表,poll 分发处(现有 host sender 旁边)再送一份 +- `FireSessionRuntimeState` 持有 `ReadPathLoginRequest`。推送用的 `SessionSnapshot` 字段 `#[serde(skip)]`,不进 `snapshot_revision`。`restore_session_json` 清掉它。`SessionState::from_snapshot` 能看见推送副本。`FireSessionHandle::complete_read_path_login` 走 registry 叫醒 waiter +- `fire-core/src/core/mod.rs`:`request_read_path_login` / `complete_read_path_login`。不碰 `FireAuthRecoveryHint` +- `fire-store`:`topic_list_cache_list_pages` +- `fire-uniffi-topics/src/lib.rs`:`open_topic_detail`。旧 `fetch_topic_detail_source_snapshot` / `fetch_topic_detail_page` / `load_more_topic_posts` 把 query 原样委托给 `load_topic_detail_*`。不忽略 batch +- `fire-uniffi-topics/src/records.rs`:`TopicDetailUiSnapshotState::from_core` 与行记录。不写分支 + +iOS / Android 调用点不动。旧 RPC 仍返回原来的记录,并且仍遵守 query 的 batch、`force_load`、`track_visit`、`allow_suggested_unread_root`。 + +测试: + +- `topics.rs` 现有树 / 游标单测保持,改 `super` 路径即可 +- `tests/network.rs` 的自定义 batch(`initial_batch_size` 10、3、1,以及 cursor `batch_size == 10`)继续打 `FireCore::fetch_topic_detail_page` / `fetch_topic_detail_source_snapshot`,因为这两个方法就是 `load_topic_detail_*`。断言不变,包括 `fetch_topic_detail_page_auto_extends_to_first_unread_root`、`skips_unread_root_auto_extend_when_not_allowed`、全部 `fetch_topic_detail_source_snapshot_*` +- 新测:同一 owner 再 open 是替换不是第二个 observer;最后 `release` 取消订阅;`note_visible_posts` 在阈值内才 append;`note_filtered_feed_tail` 用过滤后的下标;`StaleSessionResponse` 只 force 一次且 `track_visit` 不变;乐观 like 失败回滚;滚动中已完成的 reload 在松手时直接推、不再请求;`WhenLastReadMissing` 在 `has_unread == false` 时清零;compat 调用不注册 observer、不订阅 MessageBus + +`cargo test -p fire-core -p fire-uniffi-topics` 与 Android 现有编译是本阶段门槛。 + +### Phase 2 — iOS 改吃快照(一个 PR,结束时编译) + +这是行为切换。不要先留 `topicDetails` 再合成快照。 + +顺序(同一 PR): + +1. 生成 UniFFI(现有 `native/ios-app/scripts/sync_uniffi_bindings.sh`) +2. 改 `FireTopicDetailStore` 为上一节签名。删除 `+Load` 里的合并 / 窗口 / 重试。`+Mutations` / `+Reactions` / `+Presence` 只留转发 +3. `FireTopicDetailSnapshotSink` 放在 store 文件 +4. 改 `FireTopicDetailPageState`、`FeedModels`、`RuntimeSnapshotBuilder`、`SnapshotAssembler`、`ViewController` 的 `buildCurrent*` 与 revision sink +5. `PaginationCoordinator` 改为 `noteFilteredFeedTail`;`VisibilityCoordinator` 回调改 `noteVisiblePosts`。删除 `fireTopicDetailShouldLoadMore` +6. `FireTopicInteractionService` 的话题写操作改 store 转发。`voteTopic` 不再 `refreshTopicDetailAfterMutation` +7. `FireAppViewModel.submitReply` / `updatePost` 去掉返回帖。`updateTopic` 改为会话命令,成功后仍 `refreshHomeFeedIfPossible(force: true)`,不再 `refreshTopicDetailAfterMutation`。`patchHomeTopicCounts` 改为 `applyHomeRowCountPatch`,并删除 `patchedTopicRow`。`handleMessageBusEvent` 去掉话题分支。`applySession` 看到新 generation 时先 `attemptHostCookieResyncRecovery(operation:)`,返回 false 再 `attemptMidSessionHeadlessReauth(operation:)`,然后 `complete_read_path_login`。不调用 `runReadPathLoginRecovery`。话题 store 的 `applySession` 只转发登出 / 短暂不可读 +8. `presentBookmarkEditor`、`presentTopicBookmarkEditor`、`presentPostBookmarkEditor` 的 `onReload` 不再 `loadTopicDetail`。改调 create / update / delete bookmark。`presentPostEditor` 的 `onSaved`、`presentTopicEditor` 的 `onSaved`、`updateTopicNotificationLevel` 同样禁止 `loadTopicDetail(force: true)`,改为对应会话命令。对账是命令内部的 `reload(force_load: false, track_visit: false)`,必打网。去掉今天这第二发 `trackVisit: true` 是有意的。`recoveryOriginURL` 用 `open` 已经传入的 slug,不调用删掉的 `topicCloudflareRecoveryURL` +9. `performRefresh` 与 `onLoadTopicDetail`(`FireTopicDetailFeedCellFactory` 重试)改为 `open(bypass_cache: true, force_load: true, track_visit: true)`。这次记访问是有意的。`openAdvancedComposer` / `openQuoteComposer` 的 `onReplySubmitted` 不再 `loadTopicDetail`。引用回复 `submitReply(..., scrollToCreated: true)`,由会话把新帖楼层写成 `scroll_target` +10. 六个额外 store 构造改为使用 root store。含 `FireAppRoutePresentationTests` 里的临时 store +11. 详情路径停止调用 `FireSessionStore.fetchTopicDetailPage` / `loadMoreTopicPosts` + +门槛:见 PR-B 审查清单。话题 store 不再以 `TopicDetailState` 为成员。 + +### Phase 3 — Android ViewModel(独立 PR,方法级) + +`TopicDetailViewModel.kt`: + +| 方法 | 动作 | +| --- | --- | +| `prepareForTopicLoad` | 换 topic id 时 `close` 上一个 owner,再 `open` 下一个。清本地展开与渲染缓存 | +| `loadTopicDetail` | `open(bypass_cache: true, force_load: true, track_visit: true)`。`allow_suggested_unread_root` 仍是 `targetPostNumber == null && _detail.value == null`。不要把 `bypass_cache` 留成 false,否则第二次打开会跳过今天这发 HTTP | +| `fetchTopicDetailPagePayload` / `applyFetchedPayload` / `mergeLoadMore` / `applyReactionUpdate` / `applyPollUpdate` | 删 | +| `refreshCurrentTopic` | 删。通知级别、改话题、书签、删帖、恢复改走会话命令。命令内部 `track_visit = false`、`force = false` 对账。禁止留下对 `fetchTopicDetailPage` 的调用 | +| `replacePost` | 删。乐观写入在 actor 内 | +| `maintainTopicDetailMessageBus` / `scheduleTopicDetailRefresh` / `refreshTopicDetailFromMessageBus` / `releaseTopicDetailMessageBus` / `drainDeferredMessageBusRefreshIfNeeded` | 删 | +| `loadMorePosts` / `loadMorePostsPage` | `load_more` | +| `scrollToPostWhenLoaded` / `hasLoadedPostNumber` | 删。滚动目标交给会话的窗口算法(`maxWindowSize = 200`,`nextRequestedRangeForUnresolvedTarget`)。不要在 Kotlin 再写 20 页循环(`TARGET_HYDRATION_PAGE_LIMIT`) | +| `setTopicDetailScrollInteractionActive` | `note_scroll_interaction` | +| `reloadTopicAiSummary` / `loadTopicAiSummaryIfNeeded` | 命令 / 删 | +| `toggleHeart` / `toggleReaction` / `votePoll` / `unvotePoll` / `toggleTopicVote` / `deletePost` / `recoverPost` / `updatePost` / 书签 / `setTopicNotificationLevel` / `updateTopic` | 会话命令 | +| `expandReplyThread` | 留本地 | +| `projectRows` / `postRow` / `searchMatches` / `usesBoostBarrage` | 输入改快照行。`uniqueTreeRows`、`postsById`、`postsForDetail`、`initialScrollTargetPostNumber` 删 | +| `getRenderContent` / `preloadRenderContent` | 改 `RenderDocumentHandle` | +| `onCleared` | `close`(只释放本屏 owner) | + +`TopicRepository.fetchTopicDetailPage` / `loadMoreTopicPosts` 此 PR 不再被 ViewModel 调用,方法先留着,避免别的调用点断编译。`FireSessionStore.fetchTopicDetailPage` 同理。 + +### Phase 4 — 删除旧 RPC + +两端都不再调用之后: + +- 删 `FireTopicsHandle::fetch_topic_detail_source_snapshot`、`fetch_topic_detail_page`、`load_more_topic_posts` +- 删 FFI `TopicDetailSourceQueryState` 的 batch 字段,或整个 query 记录若无引用 +- 删 Android `TopicRepository.fetchTopicDetailPage`、`loadMoreTopicPosts`、`fetchTopicDetailSourceSnapshot` +- 删 Android `FireSessionStore.fetchTopicDetailPage`、`loadMoreTopicPosts`、`fetchTopicDetailSourceSnapshot` +- 删 iOS `FireSessionStore.fetchTopicDetailPage`、`loadMoreTopicPosts`、`fetchTopicDetailSourceSnapshot` +- 删 `FireCore` 上这三个公开包装。`load_topic_detail_page` 仍是 `pub(crate)`,给测试和 actor 用,不是第二套逻辑 +- 详情屏幕不再使用的 `TopicDetailState` 合成路径删除。其它屏幕若仍要单帖,继续用 `fetch_post` + +## Architectural Notes + +与 `fire-native-architecture.md` 的偏差要在实现时改文档,而不是改代码去迎合过期句子: + +- §1.3 把 `topic_detail_feed` 写成 `FireAppCore` 全局推送边界。落地是每会话 observer。不要给 `StateObserver` 加第四个方法。 +- §2.4 当前稳定边界仍是 session / topic list / notification center。本设计不改变这三条。 +- §2.5 `StaleSessionResponse`「平台无感知」今天并未做到:`FireTopicDetailStore.loadTopicDetail` 仍 `case StaleSessionResponse` 后 `force` 重试。会话补上这一跳。 +- §2.5 LoginRequired 写的是「展示失败,不自动 logout」。Headless 重登今天从话题 store 解析 `FireUniFfiError.LoginRequired` 进入。改成 `SessionSnapshot.read_path_login_request` 唤醒 `applySession`,话题详情不再解析错误。失败则快照停在 `LoginRequired`,不自动 logout。 + +三档更新必须保住(`2026-09-19-ios-topic-detail-local-updates.md`)。比较的是 Swift 组出来的 token,不是裸 Rust checksum: + +1. layout token 不变且 in-place token 变:复用 + `applyVisibleNodeUpdates`。续赞停在这档(`reactions.is_empty()` 仍为 true 方向上的非空,like 只进 `interaction_checksum`)。 +2. layout token 变且行可见:relayout。首枚反应翻转 `reactions.is_empty()`。正文展开、表情条、回复树展开、摘要展开由 Swift 折进 layout token,不要求 Rust checksum 变化。 +3. 行身份集合变化(分页、展开回复树):collection diff。展开回复树的身份变化来自 Swift 过滤,不是 Rust revision。`FireTopicDetailFeedInvalidationToken` 仍不含 `expandedPostTextIDs`。 + +`is_mutating` 只进表情 alpha,不禁用回复 / boost / overflow / 投票。chip 签名不含 mutating,避免打断 bounce。overflow 仍是 cell 本地,relayout 不得写回 `false`。 + +`FireTopicDetailWindowState`(`FireAppViewModelSupport.swift`)随窗口逻辑删除。`maxWindowSize = 200` 进会话私有窗口,不进 FFI。 + +Kyc `FaceSessionHost` 持有会话并在 `releaseSession` 拆掉。Fire 的对应物是 store 的 `close(ownerToken:)`,不是一个全局 `FireAppCore` 替身。`FireTopicsHandle` 继续从 `FireAppCore.topics()` 拿。 + +风险: + +- 离开详情即丢会话。今天 `endTopicDetailLifecycle` 在首页仍可见时保留详情。按屏幕 refcount 后,返回同一话题会重新 `open`。只有 `bypass_cache == false` 且 source 已含目标楼才不打网。最后 owner 的 `close` 会拆掉会话。这是有意行为变化,避免首页可见集变成第二套保留策略。 +- 多 store 若漏改,会各开一个 owner。`close` 只释放该 handle 记住的 owner,最后一个才拆会话。同一 token 再 open 是替换。Phase 2 仍把 `FireTopicDetailStore` 的公开 init 收成内部,只允许 root 构造。 +- 兼容 RPC 若忽略 batch,`tests/network.rs` 里 batch 为 1/3/10 的 source snapshot 用例会按 40 失败,Android 若将来传入非 40 也会变。所以 compat 保留 query 批量。actor 自己的打开路径才用常量。 +- 乐观表情与 MessageBus 刷新并发:actor 单写。刷新开始时若该帖 `is_mutating`,跳过覆盖该帖,等命令结束再对齐。 +- observer 若在 Swift 主线程同步做全量快照构建会死锁或卡滚动。sink 只赋值 `snapshots`,重的 `buildSnapshot` 仍走现有 `Task.detached`。 +- 首页 patch 在话题不在 `topicEntities` 时无效果。与今天相同。不要为此去拉首页。 + +## File Change Summary + +| 文件 | 阶段 | 动作 | +| --- | --- | --- | +| `rust/crates/fire-models/src/topic_detail_ui.rs` | 1 | 新增快照与 home patch | +| `rust/crates/fire-models/src/lib.rs` | 1 | 导出 | +| `rust/crates/fire-core/src/core/topic_detail_session.rs` | 1 | 会话、registry、常量、命令 | +| `rust/crates/fire-core/src/core/topic_detail_project.rs` | 1 | 私有 source+tree -> 快照;compat -> `TopicDetailPage` | +| `rust/crates/fire-core/src/core/topics.rs` | 1 | source session 留私有;公开 fetch 变包装 | +| `FireSessionRuntimeState`、`SessionSnapshot`(`#[serde(skip)]`)、`SessionState` | 1 | `ReadPathLoginRequest` 不进信封、不抬 `snapshot_revision`。restore 时清掉。不改 `FireAuthRecoveryHint` | +| `rust/crates/fire-core/src/core/mod.rs` | 1 | registry;`request_read_path_login` / `complete_read_path_login` | +| `rust/crates/fire-store/src/lib.rs` | 1 | `topic_list_cache_list_pages` | +| `rust/crates/fire-core/src/core/messagebus.rs` | 1 | 内部 listener | +| `rust/crates/fire-uniffi-topics/src/session.rs` | 1 | Handle、observer 适配 | +| `rust/crates/fire-uniffi-topics/src/lib.rs` | 1 | `open_topic_detail`。旧 RPC 只转发 `load_topic_detail_*`,不 `Registry.open` | +| `rust/crates/fire-uniffi-topics/src/records.rs` | 1 | `from_core` 记录 | +| `rust/crates/fire-core/tests/network.rs` | 1 | 仍走公开 `fetch_*`,确认委托后断言不变 | +| `native/ios-app/App/ViewModels/FireAppViewModel.swift` | 2 | 去掉话题错误重试。`applySession` 走 cookie resync,失败再 headless。`updateTopic` 仍刷新首页 | +| `native/ios-app/App/Stores/FireTopicDetailStore*.swift` | 2 | 快照持有 + 转发 | +| `native/ios-app/App/TopicDetail/**` | 2 | 消费快照;管道留 | +| `native/ios-app/App/Services/FireTopicInteractionService.swift` | 2 | 写操作转发 | +| `native/ios-app/App/Stores/FireHomeFeedStore.swift` | 2 | `applyHomeRowCountPatch`。删除 `patchedTopicRow` / `patchTopicCounts` | +| `native/ios-app/App/Core/FireRootCoordinator.swift` | 2 | 仍拥有唯一 store | +| 六个额外 store 构造点 | 2 | 改用 root store | +| `native/ios-app/Tests/Unit/FireTopicDetailStoreTests.swift` | 2 | 窗口断言删除或改读 Rust;UI 无关用例保留 | +| `native/ios-app/Tests/Unit/FireTopicDetailRuntimeTests.swift` | 2 | fixture 改快照行 | +| `docs/architecture/fire-native-architecture.md` §1.3 §2.4 §2.5 | 2 | 写成每会话 observer | +| `docs/architecture/2026-09-19-ios-topic-detail-local-updates.md` | 2 | 写明 Rust checksum 与 Swift 折入的本地 chrome | +| `TopicRepository.kt`、两端 `FireSessionStore` | 4 | 删除 `fetchTopicDetailPage`、`loadMoreTopicPosts`、`fetchTopicDetailSourceSnapshot` | +| `native/android-app/.../TopicDetailViewModel.kt` | 3 | 方法表 | +| `FireTopicsHandle` 三个分页方法 | 4 | 删除。含 `fetch_topic_detail_source_snapshot` | + +## Key Decisions + +- 话题详情是 `fire-uniffi-topics` 上的一个对象,不是新的 UniFFI crate,也不是全应用一个 session。 +- 全局 `StateObserver` 不增加话题详情。 +- Swift store 不做页合并、不算区间、不解析 `FireUniFfiError` 重试。 +- 新会话的批量是常量 40/40/3/120。预取 10、前向 60、hydration 页 30、迭代 8、过滤后列表尾 5、回复上下文 20、可见 debounce 120ms、刷新 1.5s、presence 30s、请求超时 30s、窗口 200。旧 RPC 在 Phase 4 前仍尊重宿主 query 的批量。 +- 用户「加载更多」是 `load_more`。楼层预取是 `note_visible_posts`。列表尾预取是 `note_filtered_feed_tail`,用过滤后的 item 下标。 +- 点赞在 HTTP 前乐观更新。回复在 `create_reply` 返回后按 `applyCreatedReply` 插入并伸窗口,不插占位行。Swift 不改帖。 +- 展开、草稿、键盘、搜索高亮、滚动偏移、overflow 留在 VC / cell,并折进 Swift token。 +- 首页补丁是 `TopicHomeRowCountPatch`,无 `like_count`。未读三态对齐 `patchedTopicRow`,含 `lastRead == nil` 且 `hasUnreadPosts == false` 时清零。只在计数会变时发出。不广播 topic list。标题 / 分类 / 标签仍靠现有 `refreshHomeFeedIfPossible`。 +- 旧 RPC 只转发 `load_topic_detail_*`,不进 `Registry.open`。无 observer、无订阅、无预取、无 owner。Android 早期运行时行为不变。 +- `open` 的缓存短路和 query 的 `force_load` 是两位。`reload` 永远打网。对账用 `force_load = false`、`track_visit = false`。 +- `close` / `release(topic_id, owner_token)` 只释放该 owner。 +- 书签是 `create_bookmark` / `update_bookmark` / `delete_bookmark` 的薄包装,带 `bookmarkable_type` 与 `auto_delete_preference`。 +- 详情状态只由屏幕 owner 保持。首页可见不再充当隐式 owner。 +- 编辑 raw 用 `prepare_edit` 单次读取,不把 raw 放进每一行。 + +## Alternatives Considered + +- 继续在 `FireTopicsHandle` 上加参数,让 Swift 少传 batch。拒绝。控制流仍在 Swift,违反 §1.1。 +- 把话题快照塞进 `StateObserver`。拒绝。多话题会把全局 observer 变成第二总线,且与「分页不要广播全表」同一类问题。 +- 一个进程级 `TopicDetailController` 仿 `FaceVerifySession` 包掉整个 App。拒绝。用户约束:只学模块内 API,Fire 多通道保持。 +- 专用 `topic-detail` OS 线程 + 同步 `call`。拒绝。会把 UI 挂在 HTTP 上。Kyc 的帧回路不适用于帖子流。 +- Swift 暂留 `TopicDetailState` 由快照反推。拒绝。那是第二真相源。 +- 首页未读改由话题 stream 重算 `unreadPosts`。拒绝。今天的公式是清零或保留,重算会改产品语义,也超出首页范围。 +- `notify_topic_list` 推一页被改过的列表。拒绝。`fetch_topic_list` 已写明宿主自己应用分页,广播会把一页当成全表。 +- 展开回复树改成 Rust 命令。拒绝。该状态是本地 chrome,文档要求留在 Swift。 +- Phase 2 双写 `topicDetails` 与快照直到 Android 完成。拒绝。iOS 必须先到达单源,双写会把合并逻辑留下。 + +## PR Plan + +1. **PR-A Rust 会话与兼容 RPC。** Phase 1。iOS/Android 行为不变。审查点:actor 不阻塞;observer 不进 `StateObserver`;compat 无订阅、无预取、无 owner,且保留 batch / `force_load` / `track_visit` / `allow_suggested_unread_root`;`tests/network.rs` 自定义 batch 断言仍绿;`release` 只拆一个 owner。 +2. **PR-B iOS 单源。** Phase 2。一个 PR,中间可以不编译,不拆双源的中间步。审查不通过,如果下面任一条成立: + - `TopicDetailState` 仍是 store 成员 + - 详情路径仍 `switch` `FireUniFfiError` 来决定重试 + - `contentToken` 或 `inPlaceUpdateToken` 被赋成裸的 Rust checksum + - `FireAppViewModel.updateTopic` 仍调用 `refreshTopicDetailAfterMutation`,或丢掉 `refreshHomeFeedIfPossible(force: true)` + - `presentBookmarkEditor` / `presentTopicBookmarkEditor` / `presentPostBookmarkEditor` 的 `onReload`,或 `presentPostEditor` / `presentTopicEditor` 的 `onSaved`,或 `updateTopicNotificationLevel` 仍调用 `loadTopicDetail` + - `performRefresh`、`onLoadTopicDetail`、`openAdvancedComposer.onReplySubmitted`、`openQuoteComposer.onReplySubmitted` 仍调用 `loadTopicDetail(force:)`。前两个必须是 `bypass_cache = true`、`force_load = true`、`track_visit = true`。后两个不得再拉页;引用回复必须 `scroll_to_created` + - Android `open` 不是 `bypass_cache = true`、`force_load = true`、`track_visit = true`(`allow_suggested_unread_root` 除外,那条保持原公式)。这条在 PR-C 落地,PR-B 审查时对照契约表,避免 iOS 表和 Android 行各写一套 + - `patchedTopicRow` 还在 + - 详情路径仍调用 `fetchTopicDetailPage` / `loadMoreTopicPosts` +3. **PR-C Android ViewModel。** Phase 3。方法表含 `prepareForTopicLoad`、`scrollToPostWhenLoaded`、`refreshCurrentTopic`、`replacePost`。Repository 方法先留。PR 结束后 ViewModel 不得再调用 `fetchTopicDetailPage`。 +4. **PR-D 删除旧 RPC。** Phase 4。删三个分页 FFI,以及两端 `FireSessionStore` 和 `TopicRepository` 上的 `fetchTopicDetailPage`、`loadMoreTopicPosts`、`fetchTopicDetailSourceSnapshot`。单独审查,便于回滚。 + +文档更新放在 PR-B(iOS 行为已变)和 PR-D(RPC 消失)。不要在 PR-A 把架构文档改成「Swift 已不再合并」——那时 Swift 还在合并。 + +## Open Questions + +- `fetchReactionUsers` / `fetchTopicVoters` 是 sheet 列表,不是帖树。保持一次性 RPC。若产品要它们也进快照,另开任务。 +- 被动掉登录时 `applySession` 里已有的 `scheduleMidSessionReauthAfterPassiveDeauth` 保持原样。它看的是 readiness 从已登录变成未登录,和 `ReadPathLoginRequest` 不是一条路径。不要把二者合成一个 hint。 + +## Goals & Non-Goals + +目标: + +- Rust 是话题详情唯一数据源和唯一逻辑处理器。 +- Swift 只渲染 UI 快照,外加纯本地 chrome。 +- 一个会话对象,命令进、快照出,含后台刷新。 +- 源游标、stream、批量、未读自动延伸、乐观对账、预取、MessageBus 刷新策略全部私有。 +- iOS 先于 Android 到达该形状。每阶段可编译。旧 RPC 最后删除。 +- 三档就地更新行为保持。 +- 首页行计数仍然正确,且首页 store 不再做未读比较。 + +非目标: + +- 合并 UniFFI 通道,或做全应用单一 session。 +- 改首页、搜索、通知、聊天的架构。 +- 重做 Texture 管道、动画、overflow 的 cell 本地状态。 +- 把展开正文 / 回复树 / 表情条 / 草稿 / 键盘 / 搜索高亮放进 Rust。 +- 在话题详情增加新的平台决策回调。 +- 用 `FrameTick`、专用线程或同步 HTTP 阻塞 UI。 +- 从 stream 重算首页未读条数。 +- Phase 1–2 修改 Android ViewModel 行为。 diff --git a/docs/architecture/fire-native-architecture.md b/docs/architecture/fire-native-architecture.md index 5a222962..1768e3fe 100644 --- a/docs/architecture/fire-native-architecture.md +++ b/docs/architecture/fire-native-architecture.md @@ -34,7 +34,7 @@ | Session state | iOS Store holds extensive `@Published` state | Rust remains the source of truth for session snapshots; platforms consume pushed snapshot copies plus explicit command results | | Pagination / cache policy | iOS Store orchestrates logic | Rust fully orchestrates, platforms receive paginated results | | Error handling | Platforms classify errors and decide retries | Rust classifies and auto-retries, platforms only receive final outcomes | -| State updates | Platforms pull after refresh/message events | `FireAppCore` pushes immutable snapshots on the current stable boundaries (`session`, `topic_list`, `topic_detail_feed`, `notification_center`) while explicit pagination and screen commands remain platform-owned | +| State updates | Platforms pull after refresh/message events | `FireAppCore` pushes immutable snapshots on the stable global boundaries (`session`, `topic_list`, `notification_center`). Topic detail is a per-topic session observer, not a fourth `StateObserver` method | --- @@ -151,6 +151,8 @@ The pushed boundaries are intentionally explicit and finite: - `TopicListState` - `NotificationCenterState` +Topic detail is not one of these global boundaries. Each open topic has its own `TopicDetailSession` and `TopicDetailObserver`. The host keeps one snapshot per topic and does not merge pages, cursors, or post trees. + ``` Rust Core Platform │ │ @@ -178,8 +180,8 @@ Rust automatically handles retries, backoff, and session refresh. Platforms only Rust FireCoreError → FireUniFfiError → Platform behavior ─────────────────────────────────────────────────────────────────────────────────── Network → Network → Show network error -LoginRequired → LoginRequired → Surface request failure; no automatic logout/reset -StaleSessionResponse → StaleSessionResponse → Rust auto-retry, platform unaware +LoginRequired → LoginRequired → Topic detail publishes `ReadPathLoginRequest` on the session snapshot. The host runs cookie resync, then headless reauth, then `complete_read_path_login`. Failure stays on the topic snapshot as `LoginRequired`; there is no automatic logout +StaleSessionResponse → (not surfaced) → The topic-detail session retries once with `force_load = true` and the original `track_visit`. The platform does not see this error CloudflareChallenge → CloudflareChallenge → Foreground-capable hosts may complete a platform-owned challenge WebView and let Rust retry once; otherwise surface the request failure HttpStatus(429) → HttpStatus → Rust auto-backoff-retry Storage → Storage → Degrade to no-cache mode diff --git a/native/android-app/src/main/java/com/fire/app/data/repository/TopicRepository.kt b/native/android-app/src/main/java/com/fire/app/data/repository/TopicRepository.kt index baef5f9d..80d5bbe3 100644 --- a/native/android-app/src/main/java/com/fire/app/data/repository/TopicRepository.kt +++ b/native/android-app/src/main/java/com/fire/app/data/repository/TopicRepository.kt @@ -45,66 +45,6 @@ class TopicRepository(private val sessionStore: FireSessionStore) { ) } - suspend fun fetchTopicDetailSourceSnapshot( - topicId: ULong, - targetPostNumber: UInt? = null, - forceLoad: Boolean = true, - trackVisit: Boolean = true, - allowSuggestedUnreadRoot: Boolean = false, - initialBatchSize: UShort = 40u, - loadMoreBatchSize: UShort = 40u, - maxAutoBatchesPerGesture: UByte = 3u, - maxAutoPostsPerGesture: UShort = 120u, - ): TopicDetailSourceSnapshotState = withContext(Dispatchers.Default) { - sessionStore.fetchTopicDetailSourceSnapshot( - TopicDetailSourceQueryState( - topicId = topicId, - targetPostNumber = targetPostNumber, - allowSuggestedUnreadRoot = allowSuggestedUnreadRoot, - trackVisit = trackVisit, - forceLoad = forceLoad, - initialBatchSize = initialBatchSize, - loadMoreBatchSize = loadMoreBatchSize, - maxAutoBatchesPerGesture = maxAutoBatchesPerGesture, - maxAutoPostsPerGesture = maxAutoPostsPerGesture, - ), - ) - } - - suspend fun fetchTopicDetailPage( - topicId: ULong, - targetPostNumber: UInt? = null, - forceLoad: Boolean = true, - trackVisit: Boolean = true, - allowSuggestedUnreadRoot: Boolean = false, - initialBatchSize: UShort = 40u, - loadMoreBatchSize: UShort = 40u, - maxAutoBatchesPerGesture: UByte = 3u, - maxAutoPostsPerGesture: UShort = 120u, - ): TopicDetailPageState = withContext(Dispatchers.Default) { - sessionStore.fetchTopicDetailPage( - TopicDetailSourceQueryState( - topicId = topicId, - targetPostNumber = targetPostNumber, - allowSuggestedUnreadRoot = allowSuggestedUnreadRoot, - trackVisit = trackVisit, - forceLoad = forceLoad, - initialBatchSize = initialBatchSize, - loadMoreBatchSize = loadMoreBatchSize, - maxAutoBatchesPerGesture = maxAutoBatchesPerGesture, - maxAutoPostsPerGesture = maxAutoPostsPerGesture, - ), - ) - } - - suspend fun loadMoreTopicPosts( - cursor: TopicSourceCursorState, - ): TopicLoadMoreOutcomeState = withContext(Dispatchers.Default) { - sessionStore.loadMoreTopicPosts( - LoadMoreTopicPostsQueryState(cursor = cursor), - ) - } - suspend fun fetchTopicAiSummary( topicId: ULong, skipAgeCheck: Boolean = false, diff --git a/native/android-app/src/main/java/com/fire/app/session/FireSessionStore.kt b/native/android-app/src/main/java/com/fire/app/session/FireSessionStore.kt index 32097c33..3e483a04 100644 --- a/native/android-app/src/main/java/com/fire/app/session/FireSessionStore.kt +++ b/native/android-app/src/main/java/com/fire/app/session/FireSessionStore.kt @@ -739,22 +739,15 @@ class FireSessionStore( response } - suspend fun fetchTopicDetailSourceSnapshot( - query: TopicDetailSourceQueryState, - ): TopicDetailSourceSnapshotState = withContext(Dispatchers.IO) { - core.topics().fetchTopicDetailSourceSnapshot(query) + fun openTopicDetail( + request: uniffi.fire_uniffi_topics.TopicDetailOpenRequestState, + observer: uniffi.fire_uniffi_topics.TopicDetailObserver, + ): uniffi.fire_uniffi_topics.TopicDetailSessionHandle { + return core.topics().openTopicDetail(request, observer) } - suspend fun fetchTopicDetailPage( - query: TopicDetailSourceQueryState, - ): TopicDetailPageState = withContext(Dispatchers.IO) { - core.topics().fetchTopicDetailPage(query) - } - - suspend fun loadMoreTopicPosts( - query: LoadMoreTopicPostsQueryState, - ): TopicLoadMoreOutcomeState = withContext(Dispatchers.IO) { - core.topics().loadMoreTopicPosts(query) + fun completeReadPathLogin(generation: ULong, succeeded: Boolean) { + core.session().completeReadPathLogin(generation, succeeded) } suspend fun startMessageBus(handler: MessageBusEventHandler): String = withContext(Dispatchers.IO) { diff --git a/native/android-app/src/main/java/com/fire/app/ui/home/HomeTopicDetailPatch.kt b/native/android-app/src/main/java/com/fire/app/ui/home/HomeTopicDetailPatch.kt index be43b7f7..92570e2d 100644 --- a/native/android-app/src/main/java/com/fire/app/ui/home/HomeTopicDetailPatch.kt +++ b/native/android-app/src/main/java/com/fire/app/ui/home/HomeTopicDetailPatch.kt @@ -2,7 +2,8 @@ package com.fire.app.ui.home import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow -import uniffi.fire_uniffi_topics.TopicDetailState +import uniffi.fire_uniffi_topics.TopicHomeRowCountPatchState +import uniffi.fire_uniffi_topics.TopicHomeUnreadDecision import uniffi.fire_uniffi_types.TopicRowState data class HomeTopicDetailPatch( @@ -12,16 +13,18 @@ data class HomeTopicDetailPatch( val views: UInt, val lastReadPostNumber: UInt?, val highestPostNumber: UInt, + val unread: TopicHomeUnreadDecision = TopicHomeUnreadDecision.STILL_UNREAD, ) { companion object { - fun from(detail: TopicDetailState): HomeTopicDetailPatch { + fun from(patch: TopicHomeRowCountPatchState): HomeTopicDetailPatch { return HomeTopicDetailPatch( - topicId = detail.id, - postsCount = detail.postsCount, - replyCount = detail.replyCount, - views = detail.views, - lastReadPostNumber = detail.lastReadPostNumber, - highestPostNumber = detail.highestPostNumber, + topicId = patch.topicId, + postsCount = patch.postsCount, + replyCount = patch.replyCount, + views = patch.views, + lastReadPostNumber = patch.lastReadPostNumber, + highestPostNumber = patch.highestPostNumber, + unread = patch.unread, ) } } @@ -31,8 +34,8 @@ object HomeTopicDetailPatchRepository { private val _patches = MutableStateFlow>(emptyMap()) val patches = _patches.asStateFlow() - fun publish(detail: TopicDetailState) { - publishPatch(HomeTopicDetailPatch.from(detail)) + fun publish(patch: TopicHomeRowCountPatchState) { + publishPatch(HomeTopicDetailPatch.from(patch)) } fun publishPatch(patch: HomeTopicDetailPatch) { @@ -46,11 +49,31 @@ object HomeTopicDetailPatcher { return null } val topic = row.topic - val nextHasUnreadPosts = patch.lastReadPostNumber - ?.let { it < patch.highestPostNumber } - ?: row.hasUnreadPosts - val nextUnreadPosts = if (nextHasUnreadPosts) topic.unreadPosts else 0u - val nextNewPosts = if (nextHasUnreadPosts) topic.newPosts else 0u + val nextUnreadPosts: UInt + val nextNewPosts: UInt + val nextHasUnreadPosts: Boolean + when (patch.unread) { + TopicHomeUnreadDecision.WHEN_LAST_READ_MISSING -> { + nextHasUnreadPosts = row.hasUnreadPosts + if (row.hasUnreadPosts) { + nextUnreadPosts = topic.unreadPosts + nextNewPosts = topic.newPosts + } else { + nextUnreadPosts = 0u + nextNewPosts = 0u + } + } + TopicHomeUnreadDecision.CAUGHT_UP -> { + nextUnreadPosts = 0u + nextNewPosts = 0u + nextHasUnreadPosts = false + } + TopicHomeUnreadDecision.STILL_UNREAD -> { + nextUnreadPosts = topic.unreadPosts + nextNewPosts = topic.newPosts + nextHasUnreadPosts = true + } + } if (topic.postsCount == patch.postsCount && topic.replyCount == patch.replyCount && topic.views == patch.views && diff --git a/native/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity.kt b/native/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity.kt index 1ae0a1d4..7850265e 100644 --- a/native/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity.kt +++ b/native/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailActivity.kt @@ -345,7 +345,6 @@ class TopicDetailActivity : AppCompatActivity() { vm.detail.collectLatest { detail -> headerAdapter.detail = detail if (detail != null) { - HomeTopicDetailPatchRepository.publish(detail) pinnedTopicTitle = detail.title.trim() if (toolbarTitlePinned) { binding.topicDetailToolbar.title = pinnedTopicTitle diff --git a/native/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailViewModel.kt b/native/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailViewModel.kt index 0ccab9d6..da0536fe 100644 --- a/native/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailViewModel.kt +++ b/native/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailViewModel.kt @@ -93,8 +93,18 @@ class TopicDetailViewModel( private var subscribedTopicId: ULong? = null private var subscribedOwnerToken: String? = null private val expandedReplyRootPostIds = mutableSetOf() + private var sessionHandle: uniffi.fire_uniffi_topics.TopicDetailSessionHandle? = null + private var sessionOwnerToken: String? = null + private val sessionObserver = object : uniffi.fire_uniffi_topics.TopicDetailObserver { + override fun onSnapshot(snapshot: uniffi.fire_uniffi_topics.TopicDetailUiSnapshotState) { + viewModelScope.launch(Dispatchers.Main) { + applyUiSnapshot(snapshot) + } + } + } - val hasMorePosts: Boolean get() = sourceCursor != null + private var snapshotHasMore = false + val hasMorePosts: Boolean get() = snapshotHasMore private val renderCache = LruCache, FireRichTextContent>(64) @@ -107,23 +117,21 @@ class TopicDetailViewModel( prepareForTopicLoad(topicId) try { val shouldUseSuggestedUnreadRootTarget = targetPostNumber == null && _detail.value == null - val payload = fetchTopicDetailPagePayload( - topicId = topicId, - targetPostNumber = targetPostNumber, - forceLoad = true, - trackVisit = true, - allowSuggestedUnreadRoot = shouldUseSuggestedUnreadRootTarget, - ) - val scrollTargetPostNumber = TopicDetailPostRows.initialScrollTargetPostNumber( - explicitTargetPostNumber = targetPostNumber, - suggestedUnreadRootPostNumber = payload.treePresentation.firstUnreadRootPostNumber, - shouldUseSuggestedUnreadRootTarget = shouldUseSuggestedUnreadRootTarget, + val owner = "android.topic-detail.$topicId" + sessionOwnerToken = owner + sessionHandle = sessionStore.openTopicDetail( + uniffi.fire_uniffi_topics.TopicDetailOpenRequestState( + topicId = topicId, + ownerToken = owner, + slugHint = null, + targetPostNumber = targetPostNumber, + bypassCache = true, + forceLoad = true, + trackVisit = true, + allowSuggestedUnreadRoot = shouldUseSuggestedUnreadRootTarget, + ), + sessionObserver, ) - val allPosts = applyFetchedPayload(payload, focusedPostNumber = scrollTargetPostNumber) - preloadRenderContent(allPosts) - loadTopicAiSummaryIfNeeded(topicId, _detail.value) - maintainTopicDetailMessageBus(topicId, payload.sourceSnapshot.header.messageBusLastId) - scrollTargetPostNumber?.let { scrollToPostWhenLoaded(it) } } catch (e: CancellationException) { throw e } catch (e: Exception) { @@ -146,7 +154,11 @@ class TopicDetailViewModel( } private fun prepareForTopicLoad(topicId: ULong) { - val previousTopicId = sourceSnapshot?.header?.topicId ?: _detail.value?.id + val previousTopicId = sourceSnapshot?.header?.topicId ?: _detail.value?.id ?: subscribedTopicId + if (previousTopicId != null && previousTopicId != topicId) { + sessionHandle?.close() + sessionHandle = null + } if (previousTopicId == null || previousTopicId == topicId) { return } @@ -169,27 +181,8 @@ class TopicDetailViewModel( } fun setTopicDetailScrollInteractionActive(active: Boolean) { - val changed = isScrollInteractionActive != active isScrollInteractionActive = active - if (changed && !active) { - drainDeferredMessageBusRefreshIfNeeded() - } - } - - private suspend fun fetchTopicDetailPagePayload( - topicId: ULong, - targetPostNumber: UInt? = null, - forceLoad: Boolean, - trackVisit: Boolean, - allowSuggestedUnreadRoot: Boolean = false, - ): TopicDetailPageState { - return topicRepository.fetchTopicDetailPage( - topicId = topicId, - targetPostNumber = targetPostNumber, - forceLoad = forceLoad, - trackVisit = trackVisit, - allowSuggestedUnreadRoot = allowSuggestedUnreadRoot, - ) + sessionHandle?.noteScrollInteraction(active) } private fun applyFetchedPayload( @@ -324,40 +317,13 @@ class TopicDetailViewModel( } private suspend fun refreshTopicDetailFromMessageBus(topicId: ULong) { - if (_isLoading.value) return - if (isScrollInteractionActive) { - deferredMessageBusRefreshTopicId = topicId - return - } - try { - val payload = fetchTopicDetailPagePayload( - topicId = topicId, - targetPostNumber = null, - forceLoad = false, - trackVisit = false, - ) - if (isScrollInteractionActive) { - deferredMessageBusRefreshTopicId = topicId - deferredMessageBusPayloadTopicId = topicId - deferredMessageBusPayload = payload - return - } - deferredMessageBusRefreshTopicId = null - deferredMessageBusPayloadTopicId = null - deferredMessageBusPayload = null - val allPosts = applyFetchedPayload(payload) - preloadRenderContent(allPosts) - loadTopicAiSummaryIfNeeded(topicId, _detail.value) - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - val reported = FireErrorReporter.report( - operation = "topic_detail.messagebus.refresh", - error = e, - sessionStore = sessionStore, - ) - _actionError.tryEmit(reported.displayMessage) - } + sessionHandle?.reload( + targetPostNumber = null, + forceLoad = false, + trackVisit = false, + allowSuggestedUnreadRoot = false, + ) + if (topicId == 0uL) return } private fun drainDeferredMessageBusRefreshIfNeeded() { @@ -407,14 +373,11 @@ class TopicDetailViewModel( fun loadMorePosts() { if (_isLoadingMore.value) return - viewModelScope.launch { - loadMorePostsPage() - } + sessionHandle?.loadMore() } fun reloadTopicAiSummary() { - val topicId = sourceSnapshot?.header?.topicId ?: _detail.value?.id ?: return - loadTopicAiSummaryIfNeeded(topicId, _detail.value, force = true) + sessionHandle?.reloadAiSummary(skipAgeCheck = true) } fun expandReplyThread(post: TopicPostState) { @@ -469,15 +432,11 @@ class TopicDetailViewModel( if (trimmedTitle.isEmpty()) return viewModelScope.launch { try { - sessionStore.updateTopic( - TopicUpdateRequestState( - topicId = detail.id, - title = trimmedTitle, - categoryId = categoryId, - tags = tags.map { it.trim() }.filter { it.isNotEmpty() }, - ), + sessionHandle?.updateTopic( + title = trimmedTitle, + categoryId = categoryId, + tags = tags.map { it.trim() }.filter { it.isNotEmpty() }, ) - refreshCurrentTopic() } catch (e: Exception) { handleActionError(e, "话题编辑失败") } @@ -488,8 +447,7 @@ class TopicDetailViewModel( if (options.isEmpty()) return viewModelScope.launch { try { - val updated = sessionStore.votePoll(post.id, poll.name, options) - applyPollUpdate(post.id, updated) + sessionHandle?.votePoll(post.id, poll.name, options) } catch (e: Exception) { handleActionError(e, "投票更新失败") } @@ -499,8 +457,7 @@ class TopicDetailViewModel( fun unvotePoll(post: TopicPostState, poll: PollState) { viewModelScope.launch { try { - val updated = sessionStore.unvotePoll(post.id, poll.name) - applyPollUpdate(post.id, updated) + sessionHandle?.unvotePoll(post.id, poll.name) } catch (e: Exception) { handleActionError(e, "投票更新失败") } @@ -574,16 +531,8 @@ class TopicDetailViewModel( fun toggleHeart(post: TopicPostState) { viewModelScope.launch { try { - val update = if (post.currentUserReaction?.id == HEART_REACTION_ID) { - sessionStore.unlikePost(post.id) - } else { - sessionStore.likePost(post.id) - } - if (update != null) { - applyReactionUpdate(post.id, update) - } else { - refreshCurrentTopic(post.postNumber) - } + val liked = post.currentUserReaction?.id != HEART_REACTION_ID + sessionHandle?.setLiked(post.id, liked) } catch (e: Exception) { handleActionError(e, "点赞状态更新失败") } @@ -605,8 +554,7 @@ class TopicDetailViewModel( viewModelScope.launch { try { - val update = sessionStore.togglePostReaction(post.id, trimmedReactionId) - applyReactionUpdate(post.id, update) + sessionHandle?.toggleReaction(post.id, trimmedReactionId) } catch (e: Exception) { handleActionError(e, "表情回应更新失败") } @@ -619,7 +567,7 @@ class TopicDetailViewModel( if (post.bookmarked) { val bookmarkId = post.bookmarkId if (bookmarkId != null) { - sessionStore.deleteBookmark(bookmarkId) + sessionHandle?.deleteBookmark(bookmarkId) _bookmarkEvents.tryEmit( BookmarkEvent.Deleted( bookmarkableId = post.id, @@ -628,9 +576,14 @@ class TopicDetailViewModel( ) } } else { - sessionStore.createBookmark(post.id, "Post") + sessionHandle?.createBookmark( + bookmarkableId = post.id, + bookmarkableType = "Post", + name = null, + reminderAt = null, + autoDeletePreference = null, + ) } - refreshCurrentTopic(post.postNumber) } catch (e: Exception) { handleActionError(e, "书签更新失败") } @@ -650,17 +603,19 @@ class TopicDetailViewModel( val normalizedName = name?.trim()?.takeIf { it.isNotEmpty() } val normalizedReminder = reminderAt?.trim()?.takeIf { it.isNotEmpty() } if (bookmarkId != null) { - sessionStore.updateBookmark( + sessionHandle?.updateBookmark( bookmarkId = bookmarkId, name = normalizedName, reminderAt = normalizedReminder, + autoDeletePreference = null, ) } else { - sessionStore.createBookmark( + sessionHandle?.createBookmark( bookmarkableId = bookmarkableId, bookmarkableType = bookmarkableType, name = normalizedName, reminderAt = normalizedReminder, + autoDeletePreference = null, ) } _bookmarkEvents.tryEmit( @@ -670,7 +625,6 @@ class TopicDetailViewModel( reminderAt = normalizedReminder, ), ) - refreshCurrentTopic(targetPostNumber) } catch (e: Exception) { handleActionError(e, "书签更新失败") } @@ -685,14 +639,13 @@ class TopicDetailViewModel( ) { viewModelScope.launch { try { - sessionStore.deleteBookmark(bookmarkId) + sessionHandle?.deleteBookmark(bookmarkId) _bookmarkEvents.tryEmit( BookmarkEvent.Deleted( bookmarkableId = bookmarkableId, bookmarkableType = bookmarkableType, ), ) - refreshCurrentTopic(targetPostNumber) } catch (e: Exception) { handleActionError(e, "书签删除失败") } @@ -702,8 +655,7 @@ class TopicDetailViewModel( fun deletePost(post: TopicPostState) { viewModelScope.launch { try { - sessionStore.deletePost(post.id) - refreshCurrentTopic(post.postNumber) + sessionHandle?.deletePost(post.id) } catch (e: Exception) { handleActionError(e, "帖子删除失败") } @@ -713,8 +665,7 @@ class TopicDetailViewModel( fun recoverPost(post: TopicPostState) { viewModelScope.launch { try { - sessionStore.recoverPost(post.id) - refreshCurrentTopic(post.postNumber) + sessionHandle?.recoverPost(post.id) } catch (e: Exception) { handleActionError(e, "帖子恢复失败") } @@ -726,15 +677,12 @@ class TopicDetailViewModel( if (trimmedRaw.isEmpty()) return viewModelScope.launch { try { - val updated = sessionStore.updatePost( - PostUpdateRequestState( - postId = post.id, - raw = trimmedRaw, - editReason = editReason?.trim()?.takeIf { it.isNotEmpty() }, - ), + sessionHandle?.updatePost( + postId = post.id, + raw = trimmedRaw, + editReason = editReason?.trim()?.takeIf { it.isNotEmpty() }, ) renderCache.remove(renderCacheKey(post)) - replacePost(post.id) { updated } } catch (e: Exception) { handleActionError(e, "帖子编辑失败") } @@ -777,38 +725,8 @@ class TopicDetailViewModel( } private suspend fun loadMorePostsPage(focusedPostNumber: UInt? = null): Boolean { - val currentCursor = sourceCursor ?: return false - if (_isLoadingMore.value) return false - _isLoadingMore.value = true - return try { - val outcome = topicRepository.loadMoreTopicPosts(currentCursor) - if (sourceCursor != currentCursor) return false - - val previousLoadedPostIds = sourceSnapshot - ?.loadedPosts - ?.mapTo(LinkedHashSet()) { it.id } - ?: linkedSetOf() - val merged = mergeLoadMore(outcome) ?: return false - val allPosts = applyFetchedPayload( - merged, - focusedPostNumber = focusedPostNumber, - ) - preloadRenderContent(allPosts) - outcome.appendedPosts.any { !previousLoadedPostIds.contains(it.id) } - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - val reported = FireErrorReporter.report( - operation = "topic_detail.load_more", - error = e, - sessionStore = sessionStore, - fallbackMessage = "加载更多帖子失败", - ) - _actionError.tryEmit(reported.displayMessage) - false - } finally { - _isLoadingMore.value = false - } + sessionHandle?.loadMore() + return focusedPostNumber == null || sourceCursor != null } private fun projectedPostRows( @@ -885,15 +803,12 @@ class TopicDetailViewModel( } private suspend fun refreshCurrentTopic(targetPostNumber: UInt? = null) { - val topicId = _detail.value?.id ?: return - val payload = fetchTopicDetailPagePayload( - topicId = topicId, + sessionHandle?.reload( targetPostNumber = targetPostNumber, forceLoad = false, trackVisit = false, + allowSuggestedUnreadRoot = false, ) - val allPosts = applyFetchedPayload(payload) - preloadRenderContent(allPosts) } private fun replacePost( @@ -943,8 +858,187 @@ class TopicDetailViewModel( _actionError.tryEmit(reported.displayMessage) } + private fun rowToPost(row: uniffi.fire_uniffi_topics.TopicDetailUiRowState): TopicPostState { + val author = row.author + return TopicPostState( + id = row.postId, + username = author.username, + name = author.name, + avatarTemplate = author.avatarTemplate, + authorMetadata = uniffi.fire_uniffi_topics.TopicPostAuthorMetadataState( + userId = author.userId, + userTitle = author.userTitle, + primaryGroupName = author.primaryGroupName, + flairUrl = author.flairUrl, + flairName = author.flairName, + flairBgColor = author.flairBgColor, + flairColor = author.flairColor, + flairGroupId = author.flairGroupId, + moderator = author.moderator, + admin = author.admin, + groupModerator = author.groupModerator, + userStatusEmoji = author.userStatusEmoji, + userStatusDescription = author.userStatusDescription, + ), + presentation = row.presentation, + raw = null, + postNumber = row.postNumber, + postType = row.postType, + createdAt = row.createdAt, + updatedAt = row.updatedAt, + likeCount = row.likeCount, + replyCount = row.replyCount, + replyToPostNumber = row.parentPostNumber, + replyToUser = row.replyToUser?.let { + uniffi.fire_uniffi_topics.TopicReplyToUserState(it.username, it.name, it.avatarTemplate) + }, + bookmarked = row.bookmarked, + bookmarkId = row.bookmarkId, + bookmarkName = row.bookmarkName, + bookmarkReminderAt = row.bookmarkReminderAt, + reactions = row.reactions.map { + uniffi.fire_uniffi_topics.TopicReactionState(it.id, it.kind, it.count, it.canUndo) + }, + currentUserReaction = row.currentReactionId?.let { id -> + row.reactions.firstOrNull { it.id == id }?.let { + uniffi.fire_uniffi_topics.TopicReactionState(it.id, it.kind, it.count, it.canUndo) + } + }, + boosts = row.boosts.map { boost -> + uniffi.fire_uniffi_topics.TopicPostBoostState( + id = boost.id, + presentation = boost.presentation, + displayText = boost.displayText, + user = uniffi.fire_uniffi_topics.TopicPostBoostUserState( + boost.user.id, + boost.user.username, + boost.user.name, + boost.user.avatarTemplate, + ), + canDelete = boost.canDelete, + canFlag = boost.canFlag, + userFlagStatus = boost.userFlagStatus, + availableFlags = boost.availableFlags, + ) + }, + canBoost = row.canBoost, + polls = row.polls, + acceptedAnswer = row.acceptedAnswer, + canAcceptAnswer = row.canAcceptAnswer, + canUnacceptAnswer = row.canUnacceptAnswer, + canEdit = row.canEdit, + canDelete = row.canDelete, + canRecover = row.canRecover, + hidden = row.hidden, + ) + } + + private fun rowToTreeRow(row: uniffi.fire_uniffi_topics.TopicDetailUiRowState): TopicTreeRowState { + return TopicTreeRowState( + postId = row.postId, + postNumber = row.postNumber, + rootPostNumber = row.rootPostNumber, + parentPostNumber = row.parentPostNumber, + depth = row.depth, + preorderIndex = 0u, + hasChildren = row.hasChildren, + descendantCount = row.descendantCount, + siblingIndex = 0.toUShort(), + isLastSibling = row.isLastSibling, + ) + } + + private fun detailFromSnapshot( + snapshot: uniffi.fire_uniffi_topics.TopicDetailUiSnapshotState, + posts: List, + ): TopicDetailState { + val chrome = snapshot.chrome + return TopicDetailState( + id = snapshot.topicId, + messageBusLastId = null, + title = chrome.title, + slug = chrome.slug, + postsCount = chrome.postsCount, + replyCount = chrome.replyCount, + categoryId = chrome.categoryId, + tags = chrome.tags.map { uniffi.fire_uniffi_types.TopicTagState(id = null, name = it, slug = null) }, + views = chrome.views, + likeCount = chrome.likeCount, + createdAt = chrome.createdAt, + highestPostNumber = chrome.highestPostNumber, + lastReadPostNumber = chrome.lastReadPostNumber, + bookmarks = emptyList(), + bookmarked = chrome.bookmarked, + bookmarkId = chrome.bookmarkId, + bookmarkName = chrome.bookmarkName, + bookmarkReminderAt = chrome.bookmarkReminderAt, + acceptedAnswer = false, + hasAcceptedAnswer = chrome.hasAcceptedAnswer, + canVote = chrome.canVote, + voteCount = chrome.voteCount, + userVoted = chrome.userVoted, + summarizable = chrome.summarizable, + hasCachedSummary = snapshot.sidecar.summarizedText != null, + hasSummary = snapshot.sidecar.summarizedText != null, + archetype = chrome.archetype, + postStream = TopicPostStreamState(posts = posts, stream = posts.map { it.id }), + details = uniffi.fire_uniffi_topics.TopicDetailMetaState( + notificationLevel = chrome.notificationLevel, + canEdit = chrome.canEdit, + createdBy = null, + participants = chrome.participants.map { + uniffi.fire_uniffi_types.TopicParticipantState( + userId = it.userId, + username = it.username, + name = it.name, + avatarTemplate = null, + ) + }, + ), + ) + } + + private fun applyUiSnapshot(snapshot: uniffi.fire_uniffi_topics.TopicDetailUiSnapshotState) { + _isLoading.value = snapshot.phase == uniffi.fire_uniffi_topics.TopicDetailPhaseState.LOADING + _isLoadingMore.value = snapshot.isLoadingMore + _errorMessage.value = when (val error = snapshot.loadError) { + is uniffi.fire_uniffi_topics.TopicDetailLoadErrorState.Unrecoverable -> error.message + uniffi.fire_uniffi_topics.TopicDetailLoadErrorState.Network -> "网络错误" + uniffi.fire_uniffi_topics.TopicDetailLoadErrorState.LoginRequired -> "需要登录" + null -> null + } + snapshotHasMore = snapshot.hasMore + snapshot.scrollTargetPostNumber?.let { _scrollTargetPostNumber.tryEmit(it) } + snapshot.homeRowPatch?.let { com.fire.app.ui.home.HomeTopicDetailPatchRepository.publish(it) } + val posts = snapshot.rows.map { rowToPost(it) } + val detail = detailFromSnapshot(snapshot, posts) + _detail.value = detail + sourceSnapshot = null + treePresentation = null + _postRows.value = TopicDetailPostRows.projectRows( + rows = snapshot.rows.filter { !it.isOriginalPost }.map { rowToTreeRow(it) }, + postsById = posts.associateBy { it.id }, + expandedReplyRootPostIds = expandedReplyRootPostIds, + focusedPostNumber = snapshot.scrollTargetPostNumber, + ) + _topicAiSummary.value = snapshot.sidecar.summarizedText?.let { text -> + TopicAiSummaryState( + summarizedText = text, + algorithm = snapshot.sidecar.algorithm, + outdated = snapshot.sidecar.outdated, + canRegenerate = snapshot.sidecar.canRegenerate, + newPostsSinceSummary = snapshot.sidecar.newPostsSinceSummary, + updatedAt = snapshot.sidecar.updatedAt, + ) + } + _isLoadingTopicAiSummary.value = snapshot.sidecar.isLoading + _topicAiSummaryError.value = snapshot.sidecar.error + } + override fun onCleared() { topicAiSummaryJob?.cancel() + sessionHandle?.close() + sessionHandle = null releaseTopicDetailMessageBus() super.onCleared() } diff --git a/native/android-app/src/test/java/com/fire/app/ui/home/HomeTopicDetailPatcherTest.kt b/native/android-app/src/test/java/com/fire/app/ui/home/HomeTopicDetailPatcherTest.kt index ff106371..7b65639b 100644 --- a/native/android-app/src/test/java/com/fire/app/ui/home/HomeTopicDetailPatcherTest.kt +++ b/native/android-app/src/test/java/com/fire/app/ui/home/HomeTopicDetailPatcherTest.kt @@ -3,6 +3,7 @@ package com.fire.app.ui.home import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Test +import uniffi.fire_uniffi_topics.TopicHomeUnreadDecision import uniffi.fire_uniffi_types.TopicRowState import uniffi.fire_uniffi_types.TopicSummaryState @@ -81,6 +82,7 @@ class HomeTopicDetailPatcherTest { views = 321u, lastReadPostNumber = 9u, highestPostNumber = 9u, + unread = TopicHomeUnreadDecision.CAUGHT_UP, ), ) diff --git a/native/ios-app/App/Core/SessionState+Helpers.swift b/native/ios-app/App/Core/SessionState+Helpers.swift index 7bc11a42..9d40be36 100644 --- a/native/ios-app/App/Core/SessionState+Helpers.swift +++ b/native/ios-app/App/Core/SessionState+Helpers.swift @@ -54,7 +54,8 @@ extension SessionState { hasLoginSession: false, browserUserAgent: nil, profileDisplayName: "未登录", - loginPhaseLabel: "未登录" + loginPhaseLabel: "未登录", + readPathLoginRequest: nil ) } diff --git a/native/ios-app/App/ListKit/TopicDetail/FirePostCellNode+Body.swift b/native/ios-app/App/ListKit/TopicDetail/FirePostCellNode+Body.swift index c3bd3541..a0faddc2 100644 --- a/native/ios-app/App/ListKit/TopicDetail/FirePostCellNode+Body.swift +++ b/native/ios-app/App/ListKit/TopicDetail/FirePostCellNode+Body.swift @@ -16,6 +16,72 @@ extension FirePostCellNode { configureBodyContent(payload: payload) } + func applyImageBand(payload: FirePostCellRenderPayload) { + let imageSegments = payload.renderContent.segments.filter { segment in + segment.isImage || segment.isOnebox + } + guard !imageSegments.isEmpty else { + if contentSegmentNodes.contains(where: { $0 is FirePostImageNode || $0 is FireTopicOneboxNode }) { + configureBodyContent(payload: payload) + } + return + } + if payload.textExpansionState.isCollapsed { + configureImageOnlySegmentNodes(payload: payload) + return + } + let nextSignature = imageSegments.map(\.signatureToken) + let currentImages = contentSegmentNodes.compactMap { node -> String? in + if node is FirePostImageNode || node is FireTopicOneboxNode { + return "kept" + } + return nil + } + if currentImages.count == imageSegments.count, contentSegmentSignature == payload.renderContent.segments.map(\.signatureToken) { + updateContentSegmentNodes(payload.renderContent.segments, renderSizes: imageRenderSizes(payload: payload), kinds: [.image, .onebox]) + return + } + if nextSignature.joined() == imageSegments.map(\.signatureToken).joined(), + contentSegmentNodes.contains(where: { $0 is FirePostImageNode || $0 is FireTopicOneboxNode }) { + updateContentSegmentNodes(payload.renderContent.segments, renderSizes: imageRenderSizes(payload: payload), kinds: [.image, .onebox]) + return + } + configureBodyContent(payload: payload) + } + + func applyTextBand(payload: FirePostCellRenderPayload) { + let hasStructuredText = payload.renderContent.segments.contains { segment in + if case .text = segment { return true } + return false + } + if !hasStructuredText || payload.textExpansionState.isCollapsed { + configureBodyText(payload: payload) + return + } + updateContentSegmentNodes( + payload.renderContent.segments, + renderSizes: imageRenderSizes(payload: payload), + kinds: [.text] + ) + } + + func imageRenderSizes(payload: FirePostCellRenderPayload) -> [CGSize?] { + let availableWidth = Self.availableContentWidth( + totalWidth: payload.layoutWidth, + depth: currentDepth, + avatarSize: currentAvatarSize, + avatarSpacing: currentAvatarSpacing + ) + return payload.renderContent.segments.map { segment -> CGSize? in + guard case .image(let image) = segment else { return nil } + return FirePostCellLayoutCalculator.imageRenderSize( + for: image, + availableWidth: availableWidth, + depth: currentDepth + ) + } + } + func configureBodyContent(payload: FirePostCellRenderPayload) { let usesStructuredSegments = payload.renderContent.segments.contains { segment in segment.isImage || segment.isOnebox @@ -219,13 +285,18 @@ extension FirePostCellNode { func updateContentSegmentNodes( _ segments: [FireTopicPostRenderSegment], - renderSizes: [CGSize?] + renderSizes: [CGSize?], + kinds: Set? = nil ) { for (index, node) in contentSegmentNodes.enumerated() { guard index < segments.count else { break } - switch (node, segments[index]) { + let segment = segments[index] + if let kinds, !kinds.contains(segment.kind) { + continue + } + switch (node, segment) { case (let textNode as FireSelectableRichTextNode, .text(let attributedText)): let traits = currentPayload?.colorTraits ?? .current textNode.attributedText = FireTextureAttributedText.resolvingDynamicColors( diff --git a/native/ios-app/App/ListKit/TopicDetail/FirePostCellNode.swift b/native/ios-app/App/ListKit/TopicDetail/FirePostCellNode.swift index 64742418..75475396 100644 --- a/native/ios-app/App/ListKit/TopicDetail/FirePostCellNode.swift +++ b/native/ios-app/App/ListKit/TopicDetail/FirePostCellNode.swift @@ -471,6 +471,65 @@ final class FirePostCellNode: ASCellNode, UIGestureRecognizerDelegate { configureDivider(shows: showsDivider) } + /// Updates only the bands that changed. `relayout` is for a height change + /// inside body, reactions, or the thread shortcut. + func applyBands( + _ bands: Set, + payload: FirePostCellRenderPayload, + callbacks: FirePostCellCallbacks, + showsThreadLine: Bool, + relayout: Bool + ) { + guard !bands.isEmpty else { return } + currentPayload = payload + currentCallbacks = callbacks + currentShowsThreadLine = showsThreadLine + currentShowsDivider = payload.showsDivider + if relayout { + currentLayoutWidth = payload.layoutWidth + currentResolvedLayout = payload.layout + } + if bands.contains(.author) { + configureAvatar(payload: payload, avatarSize: currentAvatarSize) + configureMeta(payload: payload) + } + if bands.contains(.quote) { + configureQuote(payload: payload) + } + if bands.contains(.images) { + applyImageBand(payload: payload) + } + if bands.contains(.text) { + applyTextBand(payload: payload) + configurePolls(payload: payload) + boostAnimationsEnabled = payload.boostAnimationsEnabled + configureBoosts(payload: payload) + } + if bands.contains(.showMore) { + configureBodyContent(payload: payload) + configureReplyShortcut(payload: payload) + } + if bands.contains(.actions) { + applyInPlaceActionMutatingState(payload) + configureSearchHighlight(payload.isSearchHighlighted) + } + if bands.contains(.reactions) { + configureReactionPicker(payload: payload) + if relayout { + configureReactions(payload: payload) + } else { + applyInPlaceReactions(payload) + } + } + if bands.contains(.thread) { + configureThreadLine(shows: currentShowsThreadLine) + configureDivider(shows: payload.showsDivider) + } + if relayout { + setNeedsLayout() + } + } + /// Count / selection / mutating updates. Does not rebuild the row or reset overflow. func applyInPlaceInteraction( payload: FirePostCellRenderPayload, @@ -562,6 +621,21 @@ final class FirePostCellNode: ASCellNode, UIGestureRecognizerDelegate { } } + func configureQuote(payload: FirePostCellRenderPayload) { + if let replyContext = payload.replyContext, + let targetPN = payload.replyTargetPostNumber, targetPN > 0 { + replyContextNode.isHidden = false + let replyContextFont = UIFont.preferredFont(forTextStyle: .caption1) + replyContextNode.setAttributedTitle(NSAttributedString( + string: replyContext, + attributes: [.font: replyContextFont, .foregroundColor: Self.accentTextColor] + ), for: .normal) + } else { + replyContextNode.isHidden = true + replyContextNode.setAttributedTitle(nil, for: .normal) + } + } + func configureThreadLine(shows: Bool) { threadLineNode.isHidden = !shows threadLineNode.style.preferredSize = CGSize(width: 1, height: shows ? 1 : 0) @@ -621,19 +695,7 @@ final class FirePostCellNode: ASCellNode, UIGestureRecognizerDelegate { ) } - if let replyContext = payload.replyContext, - let targetPN = payload.replyTargetPostNumber, targetPN > 0 { - replyContextNode.isHidden = false - // Caption weight keeps "回复 @user" secondary to the display name on the same row. - let replyContextFont = UIFont.preferredFont(forTextStyle: .caption1) - replyContextNode.setAttributedTitle(NSAttributedString( - string: replyContext, - attributes: [.font: replyContextFont, .foregroundColor: Self.accentTextColor] - ), for: .normal) - } else { - replyContextNode.isHidden = true - replyContextNode.setAttributedTitle(nil, for: .normal) - } + configureQuote(payload: payload) timestampNode.attributedText = NSAttributedString( string: FireTopicPresentation.compactTimestamp(payload.post.createdAt) ?? "", diff --git a/native/ios-app/App/Routing/FireAppRouteDestinationView.swift b/native/ios-app/App/Routing/FireAppRouteDestinationView.swift index 1e8cf223..200f7789 100644 --- a/native/ios-app/App/Routing/FireAppRouteDestinationView.swift +++ b/native/ios-app/App/Routing/FireAppRouteDestinationView.swift @@ -56,7 +56,7 @@ struct FirePublicProfileControllerHost: UIViewControllerRepresentable { ) { self.viewModel = viewModel self.username = username - self.topicDetailStore = FireTopicDetailStore(appViewModel: viewModel) + self.topicDetailStore = viewModel.topicDetailStore ?? FireTopicDetailStore(appViewModel: viewModel) self.topicRoutePresenter = topicRoutePresenter } diff --git a/native/ios-app/App/Services/FireTopicInteractionService.swift b/native/ios-app/App/Services/FireTopicInteractionService.swift index bcce2a2f..19382557 100644 --- a/native/ios-app/App/Services/FireTopicInteractionService.swift +++ b/native/ios-app/App/Services/FireTopicInteractionService.swift @@ -49,18 +49,18 @@ final class FireTopicInteractionService { pollName: String, options: [String], recoveryOriginURL: URL? = nil - ) async throws -> PollState { + ) async throws { + _ = recoveryOriginURL guard let topicDetailStore = host.topicDetailStore else { throw FireTopicInteractionError.unavailable } do { host.clearErrorMessage() - return try await topicDetailStore.votePoll( + try await topicDetailStore.votePoll( topicId: topicID, postId: postID, pollName: pollName, - options: options, - recoveryOriginURL: recoveryOriginURL + options: options ) } catch { _ = await host.handleInteractionError(error) @@ -73,17 +73,17 @@ final class FireTopicInteractionService { postID: UInt64, pollName: String, recoveryOriginURL: URL? = nil - ) async throws -> PollState { + ) async throws { + _ = recoveryOriginURL guard let topicDetailStore = host.topicDetailStore else { throw FireTopicInteractionError.unavailable } do { host.clearErrorMessage() - return try await topicDetailStore.unvotePoll( + try await topicDetailStore.unvotePoll( topicId: topicID, postId: postID, - pollName: pollName, - recoveryOriginURL: recoveryOriginURL + pollName: pollName ) } catch { _ = await host.handleInteractionError(error) @@ -110,7 +110,7 @@ final class FireTopicInteractionService { try await sessionStore.unvoteTopic(topicID: topicID) } } - await host.topicDetailStore?.refreshTopicDetailAfterMutation(topicId: topicID) + try? await host.topicDetailStore?.voteTopic(topicId: topicID, voted: voted) return response } catch { _ = await host.handleInteractionError(error) diff --git a/native/ios-app/App/Stores/FireHomeFeedStore.swift b/native/ios-app/App/Stores/FireHomeFeedStore.swift index f7f0c19a..109cffd5 100644 --- a/native/ios-app/App/Stores/FireHomeFeedStore.swift +++ b/native/ios-app/App/Stores/FireHomeFeedStore.swift @@ -95,41 +95,57 @@ final class FireHomeFeedStore: ObservableObject { candidateVisibleTopicIDs.intersection(currentTopicIDs) } - static func patchedTopicRow( + static func applyHomeRowCountPatch( _ row: FireTopicRowPresentation, - from detail: TopicDetailState + patch: TopicHomeRowCountPatchState ) -> FireTopicRowPresentation? { - guard row.topic.id == detail.id else { + guard row.topic.id == patch.topicId else { return nil } - let nextHasUnreadPosts = detail.lastReadPostNumber.map { lastReadPostNumber in - lastReadPostNumber < detail.highestPostNumber - } ?? row.hasUnreadPosts - let nextUnreadPosts = nextHasUnreadPosts ? row.topic.unreadPosts : 0 - let nextNewPosts = nextHasUnreadPosts ? row.topic.newPosts : 0 - guard row.topic.postsCount != detail.postsCount - || row.topic.replyCount != detail.replyCount - || row.topic.views != detail.views - || row.topic.lastReadPostNumber != detail.lastReadPostNumber - || row.topic.highestPostNumber != detail.highestPostNumber - || row.topic.unreadPosts != nextUnreadPosts - || row.topic.newPosts != nextNewPosts - || row.hasUnreadPosts != nextHasUnreadPosts else { + let (unreadPosts, newPosts, hasUnreadPosts) = unreadCounts( + hasUnreadPosts: row.hasUnreadPosts, + decision: patch.unread, + unreadPosts: row.topic.unreadPosts, + newPosts: row.topic.newPosts + ) + guard row.topic.postsCount != patch.postsCount + || row.topic.replyCount != patch.replyCount + || row.topic.views != patch.views + || row.topic.lastReadPostNumber != patch.lastReadPostNumber + || row.topic.highestPostNumber != patch.highestPostNumber + || row.topic.unreadPosts != unreadPosts + || row.topic.newPosts != newPosts + || row.hasUnreadPosts != hasUnreadPosts else { return nil } - var patched = row - patched.topic.postsCount = detail.postsCount - patched.topic.replyCount = detail.replyCount - patched.topic.views = detail.views - patched.topic.lastReadPostNumber = detail.lastReadPostNumber - patched.topic.highestPostNumber = detail.highestPostNumber - patched.topic.unreadPosts = nextUnreadPosts - patched.topic.newPosts = nextNewPosts - patched.hasUnreadPosts = nextHasUnreadPosts + patched.topic.postsCount = patch.postsCount + patched.topic.replyCount = patch.replyCount + patched.topic.views = patch.views + patched.topic.lastReadPostNumber = patch.lastReadPostNumber + patched.topic.highestPostNumber = patch.highestPostNumber + patched.topic.unreadPosts = unreadPosts + patched.topic.newPosts = newPosts + patched.hasUnreadPosts = hasUnreadPosts return patched } + private static func unreadCounts( + hasUnreadPosts: Bool, + decision: TopicHomeUnreadDecisionState, + unreadPosts: UInt32, + newPosts: UInt32 + ) -> (UInt32, UInt32, Bool) { + switch decision { + case .whenLastReadMissing: + return hasUnreadPosts ? (unreadPosts, newPosts, hasUnreadPosts) : (0, 0, hasUnreadPosts) + case .caughtUp: + return (0, 0, false) + case .stillUnread: + return (unreadPosts, newPosts, true) + } + } + func updateVisibleTopicIDs(_ topicIDs: Set) { visibleTopicIDs = Self.sanitizedVisibleTopicIDs( currentTopicIDs: topicRows.map(\.topic.id), @@ -187,17 +203,16 @@ final class FireHomeFeedStore: ObservableObject { } @discardableResult - func patchTopicCounts(from detail: TopicDetailState) -> Bool { - guard let row = topicEntities.entity(for: detail.id), - let patched = Self.patchedTopicRow(row, from: detail) else { + func applyHomeRowCountPatch(_ patch: TopicHomeRowCountPatchState) -> Bool { + guard let row = topicEntities.entity(for: patch.topicId), + let patched = Self.applyHomeRowCountPatch(row, patch: patch) else { return false } topicEntities.upsert([patched], id: \.topic.id) let rows = topicEntities.orderedValues(for: topicOrder) topicRows = rows - // Single-row patch is cheap; keep it synchronous on main. - topicRowContentTokensByID[detail.id] = Self.makeTopicRowContentToken( + topicRowContentTokensByID[patch.topicId] = Self.makeTopicRowContentToken( patched, category: categoryPresentation(for: patched.topic.categoryId) ) diff --git a/native/ios-app/App/Stores/FireTopicDetailStore+Load.swift b/native/ios-app/App/Stores/FireTopicDetailStore+Load.swift index ce10f948..fecc4ab4 100644 --- a/native/ios-app/App/Stores/FireTopicDetailStore+Load.swift +++ b/native/ios-app/App/Stores/FireTopicDetailStore+Load.swift @@ -1,1393 +1 @@ import Foundation - -@MainActor -extension FireTopicDetailStore { - func loadTopicDetail( - topicId: UInt64, - topicSlug: String? = nil, - targetPostNumber: UInt32? = nil, - force: Bool = false - ) async { - rememberTopicRecoverySlug(topicSlug, topicId: topicId) - if loadingTopicIDs.contains(topicId) { - appViewModel.topicDetailLogger()?.debug( - "topic detail load ignored already loading topic_id=\(topicId) force=\(force) target_post=\(targetPostNumber.map(String.init) ?? "nil")" - ) - return - } - if !appViewModel.session.readiness.canReadAuthenticatedApi { - appViewModel.topicDetailLogger()?.notice( - "topic detail load paused unauthenticated topic_id=\(topicId) force=\(force) target_post=\(targetPostNumber.map(String.init) ?? "nil")" - ) - applySession(appViewModel.session) - return - } - - if let targetPostNumber { - setPendingScrollTarget(targetPostNumber, topicId: topicId) - } - - var currentForce = force - let allowsSuggestedUnreadRootScrollTarget = targetPostNumber == nil && topicDetails[topicId] == nil - while true { - if !currentForce, - topicSourceSnapshots[topicId] != nil, - targetPostNumber == nil || detailContainsPostNumber(topicId: topicId, postNumber: targetPostNumber) { - appViewModel.topicDetailLogger()?.debug( - "topic detail load using cached source topic_id=\(topicId) target_post=\(targetPostNumber.map(String.init) ?? "nil")" - ) - updateTopicErrorMessage(nil, topicId: topicId) - return - } - - appViewModel.topicDetailLogger()?.debug( - "loading topic detail source topic_id=\(topicId) force=\(currentForce) target_post=\(String(describing: targetPostNumber))" - ) - do { - setLoadingTopic(true, topicId: topicId) - defer { setLoadingTopic(false, topicId: topicId) } - let sessionStore = try await appViewModel.sessionStoreValue() - updateTopicErrorMessage(nil, topicId: topicId) - let payload = try await fetchTopicDetailPagePayload( - topicId: topicId, - targetPostNumber: targetPostNumber, - trackVisit: true, - forceLoad: currentForce || force, - allowsSuggestedUnreadRootScrollTarget: allowsSuggestedUnreadRootScrollTarget, - sessionStore: sessionStore, - tracksInitialLoadAPM: true - ) - await applyTopicDetailPagePayload( - payload, - detailNotice: nil, - topicId: topicId, - allowsSuggestedUnreadRootScrollTarget: allowsSuggestedUnreadRootScrollTarget - ) - appViewModel.topicDetailLogger()?.debug( - "loaded topic detail source topic_id=\(topicId) loaded_posts=\(payload.sourceSnapshot.loadedPosts.count) reply_rows=\(payload.treePresentation.replyRows.count) source_cursor_present=\(payload.sourceSnapshot.sourceCursor != nil)" - ) - return - } catch { - appViewModel.topicDetailLogger()?.error( - "topic detail load failed topic_id=\(topicId) error=\(error.localizedDescription)" - ) - if await appViewModel.attemptReadPathLoginRecovery( - operation: "加载话题详情", - error: error - ) { - currentForce = true - continue - } - if !currentForce, - case FireUniFfiError.StaleSessionResponse = error { - appViewModel.topicDetailLogger()?.notice( - "retrying stale topic detail response topic_id=\(topicId)" - ) - currentForce = true - continue - } - if await appViewModel.handleRecoverableSessionErrorIfNeeded(error) { - if topicDetails[topicId] == nil { - updateTopicErrorMessage(error.localizedDescription, topicId: topicId) - } - return - } - updateTopicErrorMessage(error.localizedDescription, topicId: topicId) - return - } - } - } - - func fetchTopicDetailPagePayload( - topicId: UInt64, - targetPostNumber: UInt32?, - trackVisit: Bool, - forceLoad: Bool, - allowsSuggestedUnreadRootScrollTarget: Bool = false, - sessionStore: FireSessionStore, - tracksInitialLoadAPM: Bool - ) async throws -> FireTopicDetailPagePayload { - let operation = tracksInitialLoadAPM ? "加载话题详情" : "刷新话题详情" - let recoveryURL = topicCloudflareRecoveryURL(topicId: topicId) - return try await performWithTimeout(30, operation: operation) { [appViewModel] in - let fetchOperation = { - try await appViewModel.performWithCloudflareRecovery( - operation: operation, - originURL: recoveryURL - ) { - let fetchStartedAt = Date() - let page = try await sessionStore.fetchTopicDetailPage( - query: TopicDetailSourceQueryState( - topicId: topicId, - targetPostNumber: targetPostNumber, - allowSuggestedUnreadRoot: allowsSuggestedUnreadRootScrollTarget, - trackVisit: trackVisit, - forceLoad: forceLoad, - initialBatchSize: Self.topicDetailInitialBatchSize, - loadMoreBatchSize: Self.topicDetailLoadMoreBatchSize, - maxAutoBatchesPerGesture: 3, - maxAutoPostsPerGesture: 120 - ) - ) - appViewModel.topicDetailLogger()?.debug( - "topic detail page ffi topic_id=\(topicId) ffi_page_ms=\(Self.elapsedMilliseconds(since: fetchStartedAt)) source_loaded_posts=\(page.sourceSnapshot.loadedPosts.count) body_post_included=true tree_total_loaded_post_count=\(page.treePresentation.totalLoadedPostCount) reply_rows=\(page.treePresentation.replyRows.count) cooked_byte_count=\(Self.cookedByteCount(sourceSnapshot: page.sourceSnapshot))" - ) - return FireTopicDetailPagePayload( - sourceSnapshot: page.sourceSnapshot, - treePresentation: page.treePresentation - ) - } - } - if tracksInitialLoadAPM { - return try await FireAPMManager.shared.withSpan( - .topicDetailInitialLoad, - metadata: ["topic_id": String(topicId)] - ) { - try await fetchOperation() - } - } - return try await fetchOperation() - } - } - - func detailContainsPostNumber(topicId: UInt64, postNumber: UInt32?) -> Bool { - guard let postNumber else { return true } - return topicDetails[topicId]?.postStream.posts.contains(where: { $0.postNumber == postNumber }) == true - } - - func rememberTopicRecoverySlug(_ topicSlug: String?, topicId: UInt64) { - let trimmedSlug = topicSlug?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" - guard !trimmedSlug.isEmpty else { - return - } - topicRecoverySlugsByTopic[topicId] = trimmedSlug - } - - func bestKnownTopicRecoverySlug(topicId: UInt64) -> String? { - let candidates = [ - topicSourceSnapshots[topicId]?.header.slug, - topicDetails[topicId]?.slug, - topicRecoverySlugsByTopic[topicId], - ] - for candidate in candidates { - let trimmedSlug = candidate?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" - if !trimmedSlug.isEmpty { - return trimmedSlug - } - } - return nil - } - - func topicCloudflareRecoveryURL(topicId: UInt64) -> URL { - appViewModel.cloudflareRecoveryTopicURL( - topicId: topicId, - topicSlug: bestKnownTopicRecoverySlug(topicId: topicId) - ) - } - - func synthesizedTopicDetail( - sourceSnapshot: TopicDetailSourceSnapshotState, - treePresentation: TopicTreePresentationState - ) -> TopicDetailState { - Self.synthesizedTopicDetail( - sourceSnapshot: sourceSnapshot, - treePresentation: treePresentation - ) - } - - /// Pure topic-detail synthesis — safe to run off the main actor. - nonisolated static func synthesizedTopicDetail( - sourceSnapshot: TopicDetailSourceSnapshotState, - treePresentation: TopicTreePresentationState - ) -> TopicDetailState { - let replyRows = FireTopicPresentation - .uniqueTreeRowsPreservingOrder(treePresentation.replyRows) - .filter { row in - row.postId != sourceSnapshot.body.post.id - } - let postsByID = FireTopicPresentation.topicPostsByID( - [sourceSnapshot.body.post] + sourceSnapshot.loadedPosts - ) - let posts = FireTopicPresentation.uniqueTopicPostsPreservingOrder( - [sourceSnapshot.body.post] + replyRows.compactMap { postsByID[$0.postId] } - ) - return TopicDetailState( - id: sourceSnapshot.header.topicId, - messageBusLastId: sourceSnapshot.header.messageBusLastId, - title: sourceSnapshot.header.title, - slug: sourceSnapshot.header.slug, - postsCount: sourceSnapshot.header.postsCount, - replyCount: sourceSnapshot.header.replyCount, - categoryId: sourceSnapshot.header.categoryId, - tags: sourceSnapshot.header.tags, - views: sourceSnapshot.header.views, - likeCount: sourceSnapshot.header.likeCount, - createdAt: sourceSnapshot.header.createdAt, - highestPostNumber: sourceSnapshot.header.highestPostNumber, - lastReadPostNumber: sourceSnapshot.header.lastReadPostNumber, - bookmarks: sourceSnapshot.header.bookmarks, - bookmarked: sourceSnapshot.header.bookmarked, - bookmarkId: sourceSnapshot.header.bookmarkId, - bookmarkName: sourceSnapshot.header.bookmarkName, - bookmarkReminderAt: sourceSnapshot.header.bookmarkReminderAt, - acceptedAnswer: sourceSnapshot.header.acceptedAnswer, - hasAcceptedAnswer: sourceSnapshot.header.hasAcceptedAnswer, - canVote: sourceSnapshot.header.canVote, - voteCount: sourceSnapshot.header.voteCount, - userVoted: sourceSnapshot.header.userVoted, - summarizable: sourceSnapshot.header.summarizable, - hasCachedSummary: sourceSnapshot.header.hasCachedSummary, - hasSummary: sourceSnapshot.header.hasSummary, - archetype: sourceSnapshot.header.archetype, - postStream: TopicPostStreamState( - posts: posts, - stream: posts.map(\.id) - ), - details: sourceSnapshot.header.details - ) - } - - /// Dedup/filter tree rows + synthesize detail/lookup off-main so the main actor - /// only commits state and kicks render/UI work. - nonisolated static func prepareTopicDetailPagePayload( - _ payload: FireTopicDetailPagePayload, - allowsSuggestedUnreadRootScrollTarget: Bool - ) -> FirePreparedTopicDetailPage { - var treePresentation = payload.treePresentation - treePresentation.replyRows = FireTopicPresentation - .uniqueTreeRowsPreservingOrder(treePresentation.replyRows) - .filter { $0.postId != payload.sourceSnapshot.body.post.id } - - let detail = synthesizedTopicDetail( - sourceSnapshot: payload.sourceSnapshot, - treePresentation: treePresentation - ) - let postLookup = FireTopicPresentation.topicPostsByID(detail.postStream.posts) - - let suggestedUnreadRootPostNumber: UInt32? - if allowsSuggestedUnreadRootScrollTarget, - let suggestedTarget = treePresentation.firstUnreadRootPostNumber, - suggestedTarget > 1 { - suggestedUnreadRootPostNumber = suggestedTarget - } else { - suggestedUnreadRootPostNumber = nil - } - - return FirePreparedTopicDetailPage( - treePresentation: treePresentation, - detail: detail, - postLookup: postLookup, - suggestedUnreadRootPostNumber: suggestedUnreadRootPostNumber - ) - } - - func applyTopicDetailPagePayload( - _ payload: FireTopicDetailPagePayload, - detailNotice: FireTopicDetailStatusMessage?, - topicId: UInt64, - allowsSuggestedUnreadRootScrollTarget: Bool = false - ) async { - let applyStartedAt = Date() - let prepared = await Task.detached(priority: .userInitiated) { - Self.prepareTopicDetailPagePayload( - payload, - allowsSuggestedUnreadRootScrollTarget: allowsSuggestedUnreadRootScrollTarget - ) - }.value - - if let suggestedTarget = prepared.suggestedUnreadRootPostNumber, - topicDetailTargetPostNumbers[topicId] == nil { - setPendingScrollTarget(suggestedTarget, topicId: topicId) - } - rememberTopicRecoverySlug(payload.sourceSnapshot.header.slug, topicId: topicId) - updateTopicDetailNotice(detailNotice, topicId: topicId) - topicSourceSnapshots[topicId] = payload.sourceSnapshot - topicTreePresentations[topicId] = prepared.treePresentation - if let cursor = payload.sourceSnapshot.sourceCursor { - topicSourceCursorsByTopic[topicId] = cursor - } else { - topicSourceCursorsByTopic.removeValue(forKey: topicId) - } - setLoadMoreTopicPostsError(nil, topicId: topicId) - topicPostLookups[topicId] = prepared.postLookup - - appViewModel.topicDetailLogger()?.debug( - "topic detail page main apply topic_id=\(topicId) main_apply_ms=\(Self.elapsedMilliseconds(since: applyStartedAt)) source_loaded_posts=\(payload.sourceSnapshot.loadedPosts.count) body_post_included=true tree_total_loaded_post_count=\(prepared.treePresentation.totalLoadedPostCount) reply_rows=\(prepared.treePresentation.replyRows.count) cooked_byte_count=\(Self.cookedByteCount(sourceSnapshot: payload.sourceSnapshot))" - ) - _ = await buildTopicDetailRenderUpdate(detail: prepared.detail, topicId: topicId) - appViewModel.patchHomeTopicCounts(from: prepared.detail) - loadTopicAiSummaryIfNeeded(topicId: topicId, detail: prepared.detail) - } - - func loadNextTopicSourcePage( - topicId: UInt64, - cursor: TopicSourceCursorState - ) async { - guard let sessionStore = try? await appViewModel.sessionStoreValue() else { - return - } - - do { - let outcome = try await appViewModel.performWithCloudflareRecovery( - operation: "加载更多帖子", - originURL: topicCloudflareRecoveryURL(topicId: topicId) - ) { - try await sessionStore.loadMoreTopicPosts( - query: LoadMoreTopicPostsQueryState(cursor: cursor) - ) - } - guard topicSourceCursorsByTopic[topicId] == cursor else { - return - } - - setLoadMoreTopicPostsError(nil, topicId: topicId) - guard let currentSnapshot = topicSourceSnapshots[topicId] else { - return - } - await applyTopicDetailPagePayload( - FireTopicDetailPagePayload( - sourceSnapshot: Self.snapshotByAppending( - outcome.appendedPosts, - loadedRanges: outcome.loadedRanges, - sourceCursor: outcome.sourceCursor, - sourceExhausted: outcome.sourceExhausted, - onto: currentSnapshot - ), - treePresentation: outcome.treePresentation - ), - detailNotice: nil, - topicId: topicId - ) - } catch { - if await appViewModel.handleRecoverableSessionErrorIfNeeded(error) { - return - } - setLoadMoreTopicPostsError(error.localizedDescription, topicId: topicId) - } - } - - @discardableResult - func loadMoreTopicPostsIfNeeded(topicId: UInt64) -> Bool { - enqueueNextTopicSourcePageLoad(topicId: topicId) - } - - @discardableResult - func enqueueNextTopicSourcePageLoad(topicId: UInt64) -> Bool { - guard let cursor = topicSourceCursorsByTopic[topicId] else { - return false - } - guard Self.canStartNextTopicSourcePageLoad( - hasMoreTopicPosts: true, - isLoadingMoreTopicPosts: loadingMoreTopicPostIDs.contains(topicId), - hasPendingPreloadTask: topicPostPreloadTasks[topicId] != nil, - hasLoadedDetail: topicDetails[topicId] != nil - ) else { return false } - - setLoadMoreTopicPostsError(nil, topicId: topicId) - setLoadingMoreTopicPosts(true, topicId: topicId) - topicPostPreloadTasks[topicId] = Task { @MainActor [weak self] in - guard let self else { return } - defer { - self.topicPostPreloadTasks[topicId] = nil - self.setLoadingMoreTopicPosts(false, topicId: topicId) - } - await self.loadNextTopicSourcePage(topicId: topicId, cursor: cursor) - } - return true - } - - func handleVisiblePostNumbersChanged( - topicId: UInt64, - visiblePostNumbers: Set - ) { - guard !visiblePostNumbers.isEmpty else { return } - - guard topicWindowStates[topicId] != nil else { - return - } - - pendingVisiblePostNumbersByTopic[topicId] = visiblePostNumbers - topicVisibleRangeTasks[topicId]?.cancel() - topicVisibleRangeTasks[topicId] = Task { @MainActor [weak self] in - guard let self else { return } - do { - try await Task.sleep(for: Self.topicPostVisibleRangeDebounce) - } catch { - return - } - - let latestVisiblePostNumbers = - self.pendingVisiblePostNumbersByTopic.removeValue(forKey: topicId) - ?? visiblePostNumbers - self.topicVisibleRangeTasks[topicId] = nil - await self.expandRequestedRangeIfNeeded( - topicId: topicId, - visiblePostNumbers: latestVisiblePostNumbers - ) - } - } - - func needsAnchoredReload( - detail: TopicDetailState?, - anchorPostNumber: UInt32?, - window: FireTopicDetailWindowState? - ) -> Bool { - guard let anchorPostNumber else { return detail == nil } - guard detail != nil, let window else { return true } - return !window.loadedPostNumbers.contains(anchorPostNumber) - } - - func prepareTopicDetail( - _ detail: TopicDetailState, - topicId: UInt64 - ) -> TopicDetailState { - var preparedDetail = detail - let stream = FireTopicPresentation.uniqueTopicPostIDsPreservingOrder(detail.postStream.stream) - preparedDetail.postStream = TopicPostStreamState( - posts: FireTopicPresentation.mergeTopicPosts( - existing: detail.postStream.posts, - incoming: [], - orderedPostIDs: stream - ), - stream: stream - ) - topicPostLookups[topicId] = FireTopicPresentation.topicPostsByID( - preparedDetail.postStream.posts - ) - - return preparedDetail - } - - func cacheTopicDetail( - _ detail: TopicDetailState, - topicId: UInt64 - ) -> TopicDetailState { - let cachedDetail = prepareTopicDetail(detail, topicId: topicId) - _ = setTopicDetail(cachedDetail, topicId: topicId) - - scheduleTopicRenderCacheUpdate(detail: cachedDetail, topicId: topicId) - return cachedDetail - } - - @discardableResult - func setTopicDetail( - _ detail: TopicDetailState, - topicId: UInt64, - bumpRevision: Bool = true - ) -> Bool { - let feedToken = FireTopicDetailFeedContentToken(detail: detail) - let chromeToken = FireTopicDetailChromeContentToken(detail: detail) - let feedChanged = topicDetailFeedContentTokens[topicId] != feedToken - let chromeChanged = topicDetailChromeContentTokens[topicId] != chromeToken - let changed = feedChanged || chromeChanged - if changed { - topicDetails[topicId] = detail - topicDetailFeedContentTokens[topicId] = feedToken - topicDetailChromeContentTokens[topicId] = chromeToken - if bumpRevision, feedChanged { - bumpTopicCollectionRevision(topicId: topicId) - } - if chromeChanged { - bumpTopicChromeRevision(topicId: topicId) - } - } - return changed - } - - func rebuildTopicDetail( - sourceSnapshot: TopicDetailSourceSnapshotState, - treePresentation: TopicTreePresentationState, - topicId: UInt64 - ) -> TopicDetailState { - let detail = synthesizedTopicDetail( - sourceSnapshot: sourceSnapshot, - treePresentation: treePresentation - ) - topicPostLookups[topicId] = FireTopicPresentation.topicPostsByID( - detail.postStream.posts - ) - - return detail - } - - @discardableResult - func buildTopicDetailRenderUpdate( - detail: TopicDetailState, - topicId: UInt64 - ) async -> TopicDetailState { - let cachedDetail = prepareTopicDetail(detail, topicId: topicId) - let previousRenderCache = topicRenderCaches[topicId] - let baseURLString = renderBaseURLString - let generation = topicRenderGenerations[topicId, default: 0] &+ 1 - topicRenderGenerations[topicId] = generation - - topicRenderTasks[topicId]?.cancel() - let renderTask = Task { [weak self] in - let renderResult = await Task.detached(priority: .userInitiated) { - let renderStartedAt = Date() - let renderCache = FireTopicPresentation.detailRenderCache( - from: cachedDetail, - baseURLString: baseURLString, - previous: previousRenderCache - ) - return ( - renderCache: renderCache, - renderCacheMs: Self.elapsedMilliseconds(since: renderStartedAt) - ) - }.value - - guard !Task.isCancelled else { - return - } - - await self?.applyTopicDetailRenderUpdate( - detail: cachedDetail, - renderCache: renderResult.renderCache, - renderCacheMs: renderResult.renderCacheMs, - topicId: topicId, - generation: generation - ) - } - - topicRenderTasks[topicId] = renderTask - await renderTask.value - return cachedDetail - } - - func applyTopicDetailRenderUpdate( - detail: TopicDetailState, - renderCache: FireTopicDetailRenderCache, - renderCacheMs: Int64, - topicId: UInt64, - generation: UInt64 - ) { - guard topicRenderGenerations[topicId] == generation else { - return - } - - topicRenderTasks[topicId] = nil - - let previousRenderCache = topicRenderCaches[topicId] - let didUpdateDetail = setTopicDetail( - detail, - topicId: topicId, - bumpRevision: false - ) - let didRepairRenderState = !Self.renderStateCoversRowInputs( - topicRenderStates[topicId], - rowInputs: renderCache.rowInputs, - originalPostID: renderCache.rowInputs.first?.postID - ) && Self.renderStateCoversRowInputs( - renderCache.renderState, - rowInputs: renderCache.rowInputs, - originalPostID: renderCache.rowInputs.first?.postID - ) - let didUpdateRenderState = - previousRenderCache?.baseURLString != renderCache.baseURLString - || previousRenderCache?.rowInputs != renderCache.rowInputs - || previousRenderCache?.contentInputsByPostID != renderCache.contentInputsByPostID - || didRepairRenderState - - topicRenderCaches[topicId] = renderCache - if didUpdateRenderState { - topicRenderStates[topicId] = renderCache.renderState - } - if didUpdateDetail || didUpdateRenderState { - bumpTopicCollectionRevision(topicId: topicId) - } - appViewModel.topicDetailLogger()?.debug( - "topic detail render cache topic_id=\(topicId) render_cache_ms=\(renderCacheMs) row_input_count=\(renderCache.rowInputs.count) content_input_count=\(renderCache.contentInputsByPostID.count) did_update_detail=\(didUpdateDetail) did_update_render_state=\(didUpdateRenderState)" - ) - } - - func scheduleTopicRenderCacheUpdate( - detail: TopicDetailState, - topicId: UInt64 - ) { - let previousRenderCache = topicRenderCaches[topicId] - let baseURLString = renderBaseURLString - let generation = topicRenderGenerations[topicId, default: 0] &+ 1 - topicRenderGenerations[topicId] = generation - - topicRenderTasks[topicId]?.cancel() - topicRenderTasks[topicId] = Task { [weak self] in - let renderResult = await Task.detached(priority: .userInitiated) { - let renderStartedAt = Date() - let renderCache = FireTopicPresentation.detailRenderCache( - from: detail, - baseURLString: baseURLString, - previous: previousRenderCache - ) - return ( - renderCache: renderCache, - renderCacheMs: Self.elapsedMilliseconds(since: renderStartedAt) - ) - }.value - - guard !Task.isCancelled else { - return - } - - await self?.applyTopicRenderCache( - renderResult.renderCache, - renderCacheMs: renderResult.renderCacheMs, - topicId: topicId, - generation: generation - ) - } - } - - func applyTopicRenderCache( - _ renderCache: FireTopicDetailRenderCache, - renderCacheMs: Int64, - topicId: UInt64, - generation: UInt64 - ) { - guard topicRenderGenerations[topicId] == generation else { - return - } - - topicRenderTasks[topicId] = nil - - let previousRenderCache = topicRenderCaches[topicId] - topicRenderCaches[topicId] = renderCache - - let didRepairRenderState = !Self.renderStateCoversRowInputs( - topicRenderStates[topicId], - rowInputs: renderCache.rowInputs, - originalPostID: renderCache.rowInputs.first?.postID - ) && Self.renderStateCoversRowInputs( - renderCache.renderState, - rowInputs: renderCache.rowInputs, - originalPostID: renderCache.rowInputs.first?.postID - ) - let didUpdateRenderState = - previousRenderCache?.baseURLString != renderCache.baseURLString - || previousRenderCache?.rowInputs != renderCache.rowInputs - || previousRenderCache?.contentInputsByPostID != renderCache.contentInputsByPostID - || didRepairRenderState - if didUpdateRenderState { - topicRenderStates[topicId] = renderCache.renderState - bumpTopicCollectionRevision(topicId: topicId) - } - appViewModel.topicDetailLogger()?.debug( - "topic detail render cache topic_id=\(topicId) render_cache_ms=\(renderCacheMs) row_input_count=\(renderCache.rowInputs.count) content_input_count=\(renderCache.contentInputsByPostID.count) did_update_detail=false did_update_render_state=\(didUpdateRenderState)" - ) - } - - func applyTopicDetail( - _ incomingDetail: TopicDetailState, - topicId: UInt64, - seededExhaustedPostIDs: Set = [] - ) { - var detail = incomingDetail - if let previousDetail = topicDetails[topicId] { - detail.postStream.posts = FireTopicPresentation.mergeTopicPosts( - existing: previousDetail.postStream.posts, - incoming: detail.postStream.posts, - orderedPostIDs: detail.postStream.stream - ) - } - detail = cacheTopicDetail(detail, topicId: topicId) - - refreshTopicWindowState( - topicId: topicId, - detail: detail, - anchorPostNumber: activeAnchorPostNumber(topicId: topicId), - requestedRange: topicWindowStates[topicId]?.requestedRange, - pendingScrollTarget: topicWindowStates[topicId]?.pendingScrollTarget - ?? topicDetailTargetPostNumbers[topicId] - ) - - if !seededExhaustedPostIDs.isEmpty { - topicWindowStates[topicId]?.exhaustedPostIDs.formUnion(seededExhaustedPostIDs) - } - - if hasMissingPostsInRequestedRange(topicId: topicId) { - Task { - await hydrateTopicPostsToTargetIfNeeded(topicId: topicId) - } - } - - loadTopicAiSummaryIfNeeded(topicId: topicId, detail: detail) - } - - func reloadTopicAiSummary(topicId: UInt64) { - guard let detail = topicDetails[topicId] else { return } - loadTopicAiSummaryIfNeeded(topicId: topicId, detail: detail, force: true) - } - - func loadTopicAiSummaryIfNeeded( - topicId: UInt64, - detail: TopicDetailState, - force: Bool = false - ) { - guard detail.summarizable || detail.hasCachedSummary || detail.hasSummary else { - return - } - guard force - || topicAiSummaries[topicId] == nil - && !loadingTopicAiSummaryIDs.contains(topicId) - && !unavailableTopicAiSummaryIDs.contains(topicId) else { - return - } - - topicAiSummaryTasks[topicId]?.cancel() - _ = unavailableTopicAiSummaryIDs.remove(topicId) - _ = topicAiSummaryErrorsByTopicID.removeValue(forKey: topicId) - setLoadingTopicAiSummary(true, topicId: topicId) - - topicAiSummaryTasks[topicId] = Task { @MainActor [weak self] in - guard let self else { return } - defer { - self.setLoadingTopicAiSummary(false, topicId: topicId) - self.topicAiSummaryTasks.removeValue(forKey: topicId) - } - - do { - let sessionStore = try await self.appViewModel.sessionStoreValue() - let summary = try await self.appViewModel.performWithCloudflareRecovery( - operation: "加载 AI 摘要", - originURL: self.topicCloudflareRecoveryURL(topicId: topicId) - ) { - try await sessionStore.fetchTopicAiSummary( - topicID: topicId, - skipAgeCheck: false - ) - } - - if let summary, - !summary.summarizedText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { - let didChangeSummary = self.topicAiSummaries[topicId] != summary - self.topicAiSummaries[topicId] = summary - _ = self.unavailableTopicAiSummaryIDs.remove(topicId) - _ = self.topicAiSummaryErrorsByTopicID.removeValue(forKey: topicId) - // Only publish when a real summary card becomes available or changes. - if didChangeSummary { - self.bumpTopicSidecarRevision(topicId: topicId) - } - } else { - let removedSummary = self.topicAiSummaries.removeValue(forKey: topicId) != nil - _ = self.unavailableTopicAiSummaryIDs.insert(topicId) - // Missing summaries stay invisible; only bump if a previous card disappears. - if removedSummary { - self.bumpTopicSidecarRevision(topicId: topicId) - } - } - } catch { - if await self.appViewModel.handleRecoverableSessionErrorIfNeeded(error) { - self.appViewModel.topicDetailLogger()?.notice( - "recoverable session error swallowed during topic AI summary load topic_id=\(topicId)" - ) - return - } - // Failures stay silent in the feed to avoid layout jitter for the common no-summary path. - self.topicAiSummaryErrorsByTopicID[topicId] = error.localizedDescription - self.appViewModel.topicDetailLogger()?.error( - "topic AI summary load failed topic_id=\(topicId) error=\(error.localizedDescription)" - ) - } - } - } - - func prehydrateAnchoredContextBeforeDisplayIfNeeded( - detail: TopicDetailState, - topicId: UInt64, - anchorPostNumber: UInt32?, - previousWindow: FireTopicDetailWindowState?, - pendingScrollTarget: UInt32?, - sessionStore: FireSessionStore - ) async throws -> (detail: TopicDetailState, exhaustedPostIDs: Set) { - guard anchorPostNumber != nil || pendingScrollTarget != nil else { - return (detail, previousWindow?.exhaustedPostIDs ?? []) - } - - let window = resolvedTopicWindowState( - detail: detail, - previousWindow: previousWindow, - anchorPostNumber: anchorPostNumber, - requestedRange: previousWindow?.requestedRange, - pendingScrollTarget: pendingScrollTarget - ) - let missingPostIDs = FireTopicPresentation.missingPostIDs( - orderedPostIDs: detail.postStream.stream, - in: window.requestedRange, - loadedPostIDs: Set(detail.postStream.posts.map(\.id)), - excluding: window.exhaustedPostIDs - ) - guard !missingPostIDs.isEmpty else { - return (detail, window.exhaustedPostIDs) - } - - let recoveryURL = topicCloudflareRecoveryURL(topicId: topicId) - return try await Self.hydrateRequestedRange( - detail: detail, - window: window - ) { [appViewModel] batchPostIDs in - try await appViewModel.performWithCloudflareRecovery( - operation: "加载更多帖子", - originURL: recoveryURL - ) { - try await sessionStore.fetchTopicPosts( - topicID: topicId, - postIDs: batchPostIDs - ) - } - } - } - - func expandRequestedRangeIfNeeded( - topicId: UInt64, - visiblePostNumbers: Set - ) async { - guard let detail = topicDetails[topicId], - var window = topicWindowStates[topicId] else { - return - } - - let previousRange = window.requestedRange - let visibleIndices = visiblePostNumbers.compactMap { postNumber in - streamIndex(forPostNumber: postNumber, in: detail) - } - - if let minVisibleIndex = visibleIndices.min(), - let maxVisibleIndex = visibleIndices.max() { - let shouldExpandBackward = window.requestedRange.lowerBound > 0 - && minVisibleIndex <= window.requestedRange.lowerBound + Self.topicPostPrefetchThreshold - let shouldExpandForward = window.requestedRange.upperBound < detail.postStream.stream.count - && maxVisibleIndex >= max( - window.requestedRange.lowerBound, - window.requestedRange.upperBound - Self.topicPostPrefetchThreshold - 1 - ) - - if shouldExpandBackward || shouldExpandForward { - window.requestedRange = Self.expandedRequestedRange( - current: window.requestedRange, - totalCount: detail.postStream.stream.count, - expandBackward: shouldExpandBackward, - expandForward: shouldExpandForward, - anchorIndex: streamIndex(forPostNumber: window.activeAnchorPostNumber, in: detail) - ) - topicWindowStates[topicId] = window - } - } - - if topicWindowStates[topicId]?.requestedRange != previousRange - || hasMissingPostsInRequestedRange(topicId: topicId) { - await hydrateTopicPostsToTargetIfNeeded(topicId: topicId) - } - } - - func hydrateTopicPostsToTargetIfNeeded(topicId: UInt64) async { - guard let sessionStore = appViewModel.currentSessionStore() else { - return - } - guard !Task.isCancelled else { - return - } - guard !loadingMoreTopicPostIDs.contains(topicId) else { - return - } - guard hydratingTopicPostIDs.insert(topicId).inserted else { - return - } - defer { hydratingTopicPostIDs.remove(topicId) } - - await FireAPMManager.shared.withSpan( - .topicDetailHydration, - metadata: ["topic_id": String(topicId)] - ) { - var hydratedPosts: [TopicPostState] = [] - var hydratedPostIDs: Set = [] - var exhaustedPostIDs: Set = [] - var iterationCount = 0 - - while !Task.isCancelled { - iterationCount &+= 1 - if iterationCount > Self.topicPostHydrationIterationLimit { - if !hydratedPosts.isEmpty || !exhaustedPostIDs.isEmpty { - await applyHydratedTopicPostsIfNeeded( - topicId: topicId, - posts: hydratedPosts, - exhaustedPostIDs: exhaustedPostIDs - ) - } - appViewModel.topicDetailLogger()?.warning( - "topic post hydration hit iteration limit topic_id=\(topicId) iterations=\(iterationCount - 1)" - ) - return - } - - guard let detail = topicDetails[topicId], - let window = topicWindowStates[topicId] else { - return - } - - let missingPostIDs = FireTopicPresentation.missingPostIDs( - orderedPostIDs: detail.postStream.stream, - in: window.requestedRange, - loadedPostIDs: Set(detail.postStream.posts.map(\.id)).union(hydratedPostIDs), - excluding: window.exhaustedPostIDs.union(exhaustedPostIDs) - ) - guard !missingPostIDs.isEmpty else { - if !hydratedPosts.isEmpty || !exhaustedPostIDs.isEmpty { - await applyHydratedTopicPostsIfNeeded( - topicId: topicId, - posts: hydratedPosts, - exhaustedPostIDs: exhaustedPostIDs - ) - hydratedPosts.removeAll() - hydratedPostIDs.removeAll() - exhaustedPostIDs.removeAll() - continue - } - if advanceRequestedRangeTowardPendingScrollTargetIfNeeded( - topicId: topicId, - detail: detail, - window: window - ) { - continue - } - await applyHydratedTopicPostsIfNeeded( - topicId: topicId, - posts: hydratedPosts, - exhaustedPostIDs: exhaustedPostIDs - ) - return - } - - let batchPostIDs = Array(missingPostIDs.prefix(Self.topicPostPageSize)) - - do { - let fetchedPosts = try await appViewModel.performWithCloudflareRecovery( - operation: "加载更多帖子", - originURL: topicCloudflareRecoveryURL(topicId: topicId) - ) { - try await sessionStore.fetchTopicPosts( - topicID: topicId, - postIDs: batchPostIDs - ) - } - let returnedPostIDs = Set(fetchedPosts.map(\.id)) - exhaustedPostIDs.formUnion( - batchPostIDs.filter { !returnedPostIDs.contains($0) } - ) - hydratedPosts.append(contentsOf: fetchedPosts) - hydratedPostIDs.formUnion(returnedPostIDs) - } catch { - await applyHydratedTopicPostsIfNeeded( - topicId: topicId, - posts: hydratedPosts, - exhaustedPostIDs: exhaustedPostIDs - ) - if await appViewModel.handleRecoverableSessionErrorIfNeeded(error) { - return - } - updateTopicErrorMessage(error.localizedDescription, topicId: topicId) - return - } - } - - await applyHydratedTopicPostsIfNeeded( - topicId: topicId, - posts: hydratedPosts, - exhaustedPostIDs: exhaustedPostIDs - ) - } - } - - func advanceRequestedRangeTowardPendingScrollTargetIfNeeded( - topicId: UInt64, - detail: TopicDetailState, - window: FireTopicDetailWindowState - ) -> Bool { - guard let target = window.pendingScrollTarget, - !window.loadedPostNumbers.contains(target) else { - return false - } - - let loadedPostNumbersInWindow = loadedPostNumbers( - in: window.requestedRange, - detail: detail - ) - guard let nextRange = Self.nextRequestedRangeForUnresolvedTarget( - postNumber: target, - current: window.requestedRange, - totalCount: detail.postStream.stream.count, - loadedPostNumbersInCurrentRange: loadedPostNumbersInWindow - ), nextRange != window.requestedRange else { - return false - } - - topicWindowStates[topicId]?.requestedRange = nextRange - return true - } - - func loadedPostNumbers( - in range: Range, - detail: TopicDetailState - ) -> [UInt32] { - let stream = FireTopicPresentation.uniqueTopicPostIDsPreservingOrder(detail.postStream.stream) - let indexByPostID = Dictionary( - stream.enumerated().map { index, postID in - (postID, index) - }, - uniquingKeysWith: { first, _ in first } - ) - return detail.postStream.posts.compactMap { post in - guard let index = indexByPostID[post.id], - range.contains(index) else { - return nil - } - return post.postNumber - } - } - - func applyHydratedTopicPostsIfNeeded( - topicId: UInt64, - posts: [TopicPostState], - exhaustedPostIDs: Set - ) async { - guard !posts.isEmpty || !exhaustedPostIDs.isEmpty else { - return - } - guard var currentDetail = topicDetails[topicId], - let currentWindow = topicWindowStates[topicId] else { - return - } - - topicWindowStates[topicId]?.exhaustedPostIDs.formUnion(exhaustedPostIDs) - - guard !posts.isEmpty else { - if let target = topicWindowStates[topicId]?.pendingScrollTarget, - isScrollTargetExhausted(topicId: topicId, postNumber: target) { - markScrollTargetSatisfied(topicId: topicId, postNumber: target) - } - return - } - - currentDetail.postStream.posts = FireTopicPresentation.mergeTopicPosts( - existing: currentDetail.postStream.posts, - incoming: posts, - orderedPostIDs: currentDetail.postStream.stream - ) - let cachedDetail = await buildTopicDetailRenderUpdate( - detail: currentDetail, - topicId: topicId - ) - - refreshTopicWindowState( - topicId: topicId, - detail: cachedDetail, - anchorPostNumber: currentWindow.activeAnchorPostNumber, - requestedRange: currentWindow.requestedRange, - pendingScrollTarget: currentWindow.pendingScrollTarget - ) - - if let target = topicWindowStates[topicId]?.pendingScrollTarget, - isScrollTargetExhausted(topicId: topicId, postNumber: target) { - markScrollTargetSatisfied(topicId: topicId, postNumber: target) - } - } - - func hasMissingPostsInRequestedRange(topicId: UInt64) -> Bool { - guard let detail = topicDetails[topicId], - let window = topicWindowStates[topicId] else { - return false - } - - let missingPostIDs = FireTopicPresentation.missingPostIDs( - orderedPostIDs: detail.postStream.stream, - in: window.requestedRange, - loadedPostIDs: Set(detail.postStream.posts.map(\.id)), - excluding: window.exhaustedPostIDs - ) - return !missingPostIDs.isEmpty - } - - func refreshTopicWindowState( - topicId: UInt64, - detail: TopicDetailState, - anchorPostNumber: UInt32?, - requestedRange: Range?, - pendingScrollTarget: UInt32? - ) { - topicWindowStates[topicId] = resolvedTopicWindowState( - detail: detail, - previousWindow: topicWindowStates[topicId], - anchorPostNumber: anchorPostNumber, - requestedRange: requestedRange, - pendingScrollTarget: pendingScrollTarget - ) - } - - func resolvedTopicWindowState( - detail: TopicDetailState, - previousWindow: FireTopicDetailWindowState?, - anchorPostNumber: UInt32?, - requestedRange: Range?, - pendingScrollTarget: UInt32? - ) -> FireTopicDetailWindowState { - let loadedPostNumbers = Set(detail.postStream.posts.map(\.postNumber)) - let loadedPostIDs = Set(detail.postStream.posts.map(\.id)) - var loadedIndices = IndexSet() - for (index, postID) in detail.postStream.stream.enumerated() { - if loadedPostIDs.contains(postID) { - loadedIndices.insert(index) - } - } - - let resolvedAnchor = pendingScrollTarget ?? anchorPostNumber ?? previousWindow?.pendingScrollTarget - let anchorIndex = streamIndex(forPostNumber: resolvedAnchor, in: detail) - let anchorChanged = resolvedAnchor != previousWindow?.activeAnchorPostNumber - let resolvedRequestedRange = resolveRequestedRange( - requestedRange, - previousWindow: previousWindow, - totalCount: detail.postStream.stream.count, - anchorIndex: anchorIndex, - loadedIndices: loadedIndices, - anchorChanged: anchorChanged - ) - - return FireTopicDetailWindowState( - anchorPostNumber: resolvedAnchor, - requestedRange: resolvedRequestedRange, - loadedIndices: loadedIndices, - loadedPostNumbers: loadedPostNumbers, - exhaustedPostIDs: previousWindow?.exhaustedPostIDs ?? [], - pendingScrollTarget: pendingScrollTarget - ) - } - - func resolveRequestedRange( - _ requestedRange: Range?, - previousWindow: FireTopicDetailWindowState?, - totalCount: Int, - anchorIndex: Int?, - loadedIndices: IndexSet, - anchorChanged: Bool - ) -> Range { - guard totalCount > 0 else { - return 0..<0 - } - - if let requestedRange { - return clampedRequestedRange( - requestedRange, - totalCount: totalCount, - anchorIndex: anchorIndex, - loadedIndices: loadedIndices - ) - } - - if let previousWindow, !anchorChanged { - return clampedRequestedRange( - previousWindow.requestedRange, - totalCount: totalCount, - anchorIndex: anchorIndex, - loadedIndices: loadedIndices - ) - } - - return Self.initialRequestedRange( - totalCount: totalCount, - anchorIndex: anchorIndex, - loadedIndices: loadedIndices - ) - } - - func clampedRequestedRange( - _ requestedRange: Range, - totalCount: Int, - anchorIndex: Int?, - loadedIndices: IndexSet - ) -> Range { - let clamped = requestedRange.clamped(to: 0.. Int? { - guard let postNumber, - let postID = detail.postStream.posts.first(where: { $0.postNumber == postNumber })?.id else { - return nil - } - return detail.postStream.stream.firstIndex(of: postID) - } - - nonisolated static func scrollTargetIsExhausted( - postNumber: UInt32, - window: FireTopicDetailWindowState, - orderedPostIDs: [UInt64], - loadedPostIDs: Set - ) -> Bool { - if window.loadedPostNumbers.contains(postNumber) { - return false - } - - let hasMissingInWindow = !FireTopicPresentation.missingPostIDs( - orderedPostIDs: orderedPostIDs, - in: window.requestedRange, - loadedPostIDs: loadedPostIDs, - excluding: window.exhaustedPostIDs - ).isEmpty - if hasMissingInWindow { - return false - } - - let wholeStreamResolved = FireTopicPresentation.missingPostIDs( - orderedPostIDs: orderedPostIDs, - in: 0.., - totalCount: Int, - loadedPostNumbersInCurrentRange: [UInt32] - ) -> Range? { - guard totalCount > 0 else { - return nil - } - guard current.lowerBound > 0 || current.upperBound < totalCount else { - return nil - } - - let estimatedIndex = max(0, min(Int(postNumber) - 1, totalCount - 1)) - if !current.contains(estimatedIndex) { - return boundedRequestedRange( - lowerBound: estimatedIndex - (topicPostPageSize / 2), - upperBound: estimatedIndex + (topicPostPageSize / 2) + 1, - totalCount: totalCount, - anchorIndex: nil - ) - } - - let direction: FireTopicDetailSearchDirection - if let maxLoadedPostNumber = loadedPostNumbersInCurrentRange.max(), - postNumber > maxLoadedPostNumber { - direction = .forward - } else if let minLoadedPostNumber = loadedPostNumbersInCurrentRange.min(), - postNumber < minLoadedPostNumber { - direction = .backward - } else if totalCount - current.upperBound >= current.lowerBound { - direction = .forward - } else { - direction = .backward - } - - return nextDirectionalSearchRange( - current: current, - totalCount: totalCount, - direction: direction - ) - } - - nonisolated static func initialRequestedRange( - totalCount: Int, - anchorIndex: Int?, - loadedIndices: IndexSet - ) -> Range { - guard totalCount > 0 else { - return 0..<0 - } - - let loadedLowerBound = loadedIndices.first ?? anchorIndex ?? 0 - let loadedUpperBound = (loadedIndices.last.map { $0 + 1 }) ?? min(totalCount, loadedLowerBound + 1) - let desiredLowerBound: Int - if let anchorIndex { - desiredLowerBound = anchorIndex - (topicPostPageSize / 2) - } else { - desiredLowerBound = min(loadedLowerBound, loadedUpperBound - topicPostPageSize) - } - - return boundedRequestedRange( - lowerBound: min(desiredLowerBound, loadedLowerBound), - upperBound: max(loadedUpperBound, loadedLowerBound + topicPostPageSize), - totalCount: totalCount, - anchorIndex: anchorIndex - ) - } - - nonisolated static func expandedRequestedRange( - current: Range, - totalCount: Int, - expandBackward: Bool, - expandForward: Bool, - anchorIndex: Int? - ) -> Range { - let lowerBound = expandBackward ? current.lowerBound - topicPostPageSize : current.lowerBound - let upperBound = expandForward ? current.upperBound + topicPostForwardExpansionSize : current.upperBound - return boundedRequestedRange( - lowerBound: lowerBound, - upperBound: upperBound, - totalCount: totalCount, - anchorIndex: anchorIndex - ) - } - - nonisolated static func boundedRequestedRange( - lowerBound: Int, - upperBound: Int, - totalCount: Int, - anchorIndex: Int? - ) -> Range { - guard totalCount > 0 else { - return 0..<0 - } - - var lowerBound = max(0, min(lowerBound, totalCount)) - var upperBound = max(lowerBound, min(upperBound, totalCount)) - if lowerBound == upperBound { - upperBound = min(totalCount, lowerBound + 1) - } - - if upperBound - lowerBound <= FireTopicDetailWindowState.maxWindowSize { - return lowerBound.. TopicPostState { - let trimmedRaw = raw.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmedRaw.isEmpty else { - throw FireTopicInteractionError.emptyReply - } - - guard appViewModel.canStartAuthenticatedMutation else { - throw FireTopicInteractionError.requiresAuthenticatedWrite - } - if mutatingPostIDs.contains(postID) { - let sessionStore = try await appViewModel.sessionStoreValue() - return try await sessionStore.fetchPost(postID: postID) - } - - setMutatingPost(true, topicId: topicID, postId: postID) - defer { setMutatingPost(false, topicId: topicID, postId: postID) } - - do { - let sessionStore = try await appViewModel.sessionStoreValue() - updateTopicErrorMessage(nil, topicId: topicID) - let updatedPost = try await appViewModel.performWriteWithCloudflareRetry( - originURL: topicCloudflareRecoveryURL(topicId: topicID) - ) { - try await sessionStore.updatePost( - postID: postID, - raw: trimmedRaw, - editReason: editReason - ) - } - await appViewModel.syncSessionSnapshotIfAvailable(from: sessionStore) - try? await refreshTopicDetailAfterMutation(topicId: topicID, sessionStore: sessionStore) - await appViewModel.refreshHomeFeedIfPossible(force: false) - return updatedPost - } catch { - if await appViewModel.handleRecoverableSessionErrorIfNeeded(error) { - throw error - } - updateTopicErrorMessage(error.localizedDescription, topicId: topicID) - throw error - } - } - - func deletePost(topicID: UInt64, postID: UInt64) async throws { - try await performPostManagementMutation(topicID: topicID, postID: postID) { sessionStore in - try await sessionStore.deletePost(postID: postID) - } - } - - func recoverPost(topicID: UInt64, postID: UInt64) async throws { - try await performPostManagementMutation(topicID: topicID, postID: postID) { sessionStore in - try await sessionStore.recoverPost(postID: postID) - } - } - - func flagPost( - topicID: UInt64, - postID: UInt64, - flagTypeID: UInt32, - message: String? - ) async throws { - let trimmedMessage = message? - .trimmingCharacters(in: .whitespacesAndNewlines) - try await performPostManagementMutation(topicID: topicID, postID: postID) { sessionStore in - try await sessionStore.flagPost( - postID: postID, - flagTypeID: flagTypeID, - message: trimmedMessage?.isEmpty == true ? nil : trimmedMessage - ) - } - } - - func loadPostActionTypesIfNeeded(force: Bool = false) async { - if isLoadingPostActionTypes { - return - } - if hasLoadedPostActionTypes && !force { - return - } - - isLoadingPostActionTypes = true - defer { isLoadingPostActionTypes = false } - - guard let sessionStore = try? await appViewModel.sessionStoreValue() else { - return - } - - do { - let types = try await appViewModel.performWithCloudflareRecovery( - operation: "加载举报类型" - ) { - try await sessionStore.fetchPostActionTypes() - } - postActionTypes = types - hasLoadedPostActionTypes = true - } catch { - if await appViewModel.handleRecoverableSessionErrorIfNeeded(error) { - return - } - appViewModel.topicDetailLogger()?.warning( - "failed to load post action types: \(error.localizedDescription)" - ) - hasLoadedPostActionTypes = true - } - } - - func loadPostReplyContextIfNeeded( - topicID: UInt64, - post: TopicPostState, - force: Bool = false - ) async { - guard force - || postRepliesByPostID[post.id] == nil - || postReplyHistoryByPostID[post.id] == nil else { - return - } - guard !loadingPostReplyContextIDs.contains(post.id) else { - return - } - setLoadingPostReplyContext(true, topicId: topicID, postId: post.id) - setPostReplyContextError(nil, topicId: topicID, postId: post.id) - defer { setLoadingPostReplyContext(false, topicId: topicID, postId: post.id) } - - guard let sessionStore = try? await appViewModel.sessionStoreValue() else { - return - } - - do { - let recoveryURL = topicCloudflareRecoveryURL(topicId: topicID) - let replies = try await appViewModel.performWithCloudflareRecovery( - operation: "加载帖子回复", - originURL: recoveryURL - ) { - try await self.fetchReplyContextReplies( - topicID: topicID, - post: post, - sessionStore: sessionStore - ) - } - let replyHistory = try await appViewModel.performWithCloudflareRecovery( - operation: "加载回复来源", - originURL: recoveryURL - ) { - post.replyToPostNumber != nil - ? try await sessionStore.fetchPostReplyHistory(postID: post.id) - : [] - } - postRepliesByPostID[post.id] = replies - postReplyHistoryByPostID[post.id] = replyHistory - - let refreshedPosts = replies + replyHistory - if !refreshedPosts.isEmpty { - if let replyRows = applyReplyContextRowsIfPossible( - topicId: topicID, - rootPost: post, - contextPosts: refreshedPosts - ), - let sourceSnapshot = topicSourceSnapshots[topicID], - let treePresentation = topicTreePresentations[topicID] { - let detail = rebuildTopicDetail( - sourceSnapshot: sourceSnapshot, - treePresentation: treePresentation, - topicId: topicID - ) - _ = replyRows - await buildTopicDetailRenderUpdate(detail: detail, topicId: topicID) - } else { - await applyHydratedTopicPostsIfNeeded( - topicId: topicID, - posts: refreshedPosts, - exhaustedPostIDs: [] - ) - } - } - } catch { - if await appViewModel.handleRecoverableSessionErrorIfNeeded(error) { - return - } - setPostReplyContextError(error.localizedDescription, topicId: topicID, postId: post.id) - } - } - - func applyReplyContextRowsIfPossible( - topicId: UInt64, - rootPost: TopicPostState, - contextPosts: [TopicPostState] - ) -> [TopicTreeRowState]? { - guard var treePresentation = topicTreePresentations[topicId], - var sourceSnapshot = topicSourceSnapshots[topicId] else { - return nil - } - - let existingRows = treePresentation.replyRows - let mergedRows = Self.mergeReplyContextTreeRows( - existingRows: existingRows, - bodyPostNumber: sourceSnapshot.body.post.postNumber, - rootPost: rootPost, - contextPosts: contextPosts - ) - guard mergedRows != existingRows else { - return nil - } - - treePresentation.replyRows = mergedRows - sourceSnapshot.loadedPosts = FireTopicPresentation.mergeTopicPosts( - existing: sourceSnapshot.loadedPosts, - incoming: contextPosts, - orderedPostIDs: sourceSnapshot.rawStreamIds - ) - topicTreePresentations[topicId] = treePresentation - topicSourceSnapshots[topicId] = sourceSnapshot - return mergedRows - } - - func fetchReplyContextReplies( - topicID: UInt64, - post: TopicPostState, - sessionStore: FireSessionStore - ) async throws -> [TopicPostState] { - guard post.replyCount > 0 else { - return [] - } - - let replyIDs = orderedUniquePostIDs( - try await sessionStore.fetchPostReplyIds(postID: post.id) - ) - guard !replyIDs.isEmpty else { - return [] - } - - var replies: [TopicPostState] = [] - var startIndex = 0 - while startIndex < replyIDs.count { - let endIndex = min(startIndex + Self.replyContextPostBatchSize, replyIDs.count) - let batchIDs = Array(replyIDs[startIndex.. [UInt64] { - var seen: Set = [] - var result: [UInt64] = [] - for id in ids where id > 0 && !seen.contains(id) { - seen.insert(id) - result.append(id) - } - return result - } - - func votePoll( - topicId: UInt64, - postId: UInt64, - pollName: String, - options: [String], - recoveryOriginURL: URL? - ) async throws -> PollState { - guard appViewModel.canStartAuthenticatedMutation else { - throw FireTopicInteractionError.requiresAuthenticatedWrite - } - guard !mutatingPostIDs.contains(postId) else { - throw FireTopicInteractionError.unavailable - } - - setMutatingPost(true, topicId: topicId, postId: postId) - defer { setMutatingPost(false, topicId: topicId, postId: postId) } - - let sessionStore = try await appViewModel.sessionStoreValue() - updateTopicErrorMessage(nil, topicId: topicId) - do { - let poll = try await appViewModel.performWriteWithCloudflareRetry(originURL: recoveryOriginURL) { - try await sessionStore.votePoll( - postID: postId, - pollName: pollName, - options: options - ) - } - await appViewModel.syncSessionSnapshotIfAvailable(from: sessionStore) - try? await refreshTopicDetailAfterMutation(topicId: topicId, sessionStore: sessionStore) - return poll - } catch { - if await appViewModel.handleRecoverableSessionErrorIfNeeded(error) { - throw error - } - updateTopicErrorMessage(error.localizedDescription, topicId: topicId) - throw error - } - } - - func unvotePoll( - topicId: UInt64, - postId: UInt64, - pollName: String, - recoveryOriginURL: URL? - ) async throws -> PollState { - guard appViewModel.canStartAuthenticatedMutation else { - throw FireTopicInteractionError.requiresAuthenticatedWrite - } - guard !mutatingPostIDs.contains(postId) else { - throw FireTopicInteractionError.unavailable - } - - setMutatingPost(true, topicId: topicId, postId: postId) - defer { setMutatingPost(false, topicId: topicId, postId: postId) } - - let sessionStore = try await appViewModel.sessionStoreValue() - updateTopicErrorMessage(nil, topicId: topicId) - do { - let poll = try await appViewModel.performWriteWithCloudflareRetry(originURL: recoveryOriginURL) { - try await sessionStore.unvotePoll(postID: postId, pollName: pollName) - } - await appViewModel.syncSessionSnapshotIfAvailable(from: sessionStore) - try? await refreshTopicDetailAfterMutation(topicId: topicId, sessionStore: sessionStore) - return poll - } catch { - if await appViewModel.handleRecoverableSessionErrorIfNeeded(error) { - throw error - } - updateTopicErrorMessage(error.localizedDescription, topicId: topicId) - throw error - } - } - - func performPostManagementMutation( - topicID: UInt64, - postID: UInt64, - operation: @escaping (FireSessionStore) async throws -> Void - ) async throws { - guard appViewModel.canStartAuthenticatedMutation else { - throw FireTopicInteractionError.requiresAuthenticatedWrite - } - guard !mutatingPostIDs.contains(postID) else { - return - } - - setMutatingPost(true, topicId: topicID, postId: postID) - defer { setMutatingPost(false, topicId: topicID, postId: postID) } - - do { - let sessionStore = try await appViewModel.sessionStoreValue() - updateTopicErrorMessage(nil, topicId: topicID) - try await appViewModel.performWriteWithCloudflareRetry( - originURL: topicCloudflareRecoveryURL(topicId: topicID) - ) { - try await operation(sessionStore) - } - await appViewModel.syncSessionSnapshotIfAvailable(from: sessionStore) - try? await refreshTopicDetailAfterMutation(topicId: topicID, sessionStore: sessionStore) - await appViewModel.refreshHomeFeedIfPossible(force: false) - } catch { - if await appViewModel.handleRecoverableSessionErrorIfNeeded(error) { - throw error - } - updateTopicErrorMessage(error.localizedDescription, topicId: topicID) - throw error - } - } - - func refreshTopicDetailAfterMutation(topicId: UInt64) async { - guard let sessionStore = try? await appViewModel.sessionStoreValue() else { - return - } - try? await refreshTopicDetailAfterMutation(topicId: topicId, sessionStore: sessionStore) - } - - func refreshTopicDetailAfterMutation( - topicId: UInt64, - sessionStore: FireSessionStore - ) async throws { - let payload = try await fetchTopicDetailPagePayload( - topicId: topicId, - targetPostNumber: nil, - trackVisit: false, - forceLoad: false, - sessionStore: sessionStore, - tracksInitialLoadAPM: false - ) - await applyTopicDetailPagePayload( - payload, - detailNotice: nil, - topicId: topicId - ) - } - - func refreshTopicDetailPageFromNetwork( - topicId: UInt64, - targetPostNumber: UInt32?, - sessionStore: FireSessionStore - ) async throws -> FireTopicDetailPagePayload { - try await fetchTopicDetailPagePayload( - topicId: topicId, - targetPostNumber: targetPostNumber, - trackVisit: false, - forceLoad: false, - sessionStore: sessionStore, - tracksInitialLoadAPM: false - ) - } - - func applyCreatedBoost( - _ boost: TopicPostBoostState, - topicId: UInt64, - postId: UInt64 - ) { - guard var detail = topicDetails[topicId] else { return } - guard let postIndex = detail.postStream.posts.firstIndex(where: { $0.id == postId }) else { - return - } - - var post = detail.postStream.posts[postIndex] - if !post.boosts.contains(where: { $0.id == boost.id }) { - post.boosts.append(boost) - } - // Own boost consumes the create permission until a refresh restores it. - post.canBoost = false - detail.postStream.posts[postIndex] = post - - if var sourceSnapshot = topicSourceSnapshots[topicId] { - if sourceSnapshot.body.post.id == postId { - sourceSnapshot.body.post = post - } - if let loadedIndex = sourceSnapshot.loadedPosts.firstIndex(where: { $0.id == postId }) { - sourceSnapshot.loadedPosts[loadedIndex] = post - } - topicSourceSnapshots[topicId] = sourceSnapshot - } - - _ = cacheTopicDetail(detail, topicId: topicId) - bumpTopicCollectionRevision(topicId: topicId) - } - - func applyCreatedReply(_ reply: TopicPostState, topicId: UInt64) { - guard var detail = topicDetails[topicId] else { - return - } - - let isNewPost = !detail.postStream.stream.contains(reply.id) - if isNewPost { - detail.postStream.stream.append(reply.id) - } - - if let postIndex = detail.postStream.posts.firstIndex(where: { $0.id == reply.id }) { - detail.postStream.posts[postIndex] = reply - } else { - detail.postStream.posts.append(reply) - } - - if isNewPost { - detail.postsCount = max( - detail.postsCount + 1, - UInt32(detail.postStream.stream.count) - ) - detail.replyCount = max( - detail.replyCount + 1, - detail.postsCount > 0 ? detail.postsCount - 1 : 0 - ) - } - detail.highestPostNumber = max(detail.highestPostNumber, reply.postNumber) - detail.lastReadPostNumber = max(detail.lastReadPostNumber ?? 0, reply.postNumber) - - let previousStreamCount = detail.postStream.stream.count - detail = cacheTopicDetail(detail, topicId: topicId) - - var requestedRange = topicWindowStates[topicId]?.requestedRange - if let window = topicWindowStates[topicId], - window.requestedRange.upperBound >= previousStreamCount { - requestedRange = window.requestedRange.lowerBound.. - ) { - guard var owners = activeTopicDetailOwnerTokens[topicId] else { return } - guard owners.remove(ownerToken) != nil else { return } - - if owners.isEmpty { - activeTopicDetailOwnerTokens.removeValue(forKey: topicId) - } else { - activeTopicDetailOwnerTokens[topicId] = owners - } - - appViewModel.topicDetailLogger()?.debug( - "released topic detail lifecycle topic_id=\(topicId) owner_token=\(ownerToken) owner_count=\(owners.count)" - ) - - guard owners.isEmpty else { return } - topicDetailTargetPostNumbers.removeValue(forKey: topicId) - guard !visibleTopicIDs.contains(topicId) else { return } - evictTopicDetailState(topicId: topicId, reason: "detail view disappeared") - } - - func pruneInactiveTopicDetailState(retainingVisibleTopicIDs visibleTopicIDs: Set) { - let retainedTopicIDs = retainedTopicDetailIDs(visibleTopicIDs: visibleTopicIDs) - pruneInactiveTopicDetailState(retaining: retainedTopicIDs, visibleTopicIDs: visibleTopicIDs) - } - - func maintainTopicDetailSubscription(topicId: UInt64, ownerToken: String) async { - guard appViewModel.session.readiness.canOpenMessageBus else { return } - guard topicDetails[topicId] != nil else { - appViewModel.topicDetailLogger()?.debug( - "skipping topic detail subscription bootstrap topic_id=\(topicId) reason=detail not loaded" - ) - return - } - - guard let store = appViewModel.currentSessionStore() else { return } - - do { - let lastMessageId = topicSourceSnapshots[topicId]?.header.messageBusLastId - ?? topicDetails[topicId]?.messageBusLastId - try await store.subscribeTopicDetailChannel( - topicId: topicId, - ownerToken: ownerToken, - lastMessageId: lastMessageId - ) - try await store.subscribeTopicReactionChannel(topicId: topicId, ownerToken: ownerToken) - try await store.subscribeTopicPollsChannel(topicId: topicId, ownerToken: ownerToken) - } catch { - try? await store.unsubscribeTopicPollsChannel(topicId: topicId, ownerToken: ownerToken) - try? await store.unsubscribeTopicReactionChannel(topicId: topicId, ownerToken: ownerToken) - try? await store.unsubscribeTopicDetailChannel(topicId: topicId, ownerToken: ownerToken) - return - } - - do { - let presence = try await store.bootstrapTopicReplyPresence( - topicId: topicId, - ownerToken: ownerToken - ) - applyTopicPresenceState(presence) - } catch { - setTopicPresenceUsers([], topicId: topicId) - } - - defer { - Task { - await self.endTopicReplyPresence(topicId: topicId) - self.setTopicPresenceUsers([], topicId: topicId) - try? await store.unsubscribeTopicReplyPresenceChannel(topicId: topicId, ownerToken: ownerToken) - try? await store.unsubscribeTopicPollsChannel(topicId: topicId, ownerToken: ownerToken) - try? await store.unsubscribeTopicReactionChannel(topicId: topicId, ownerToken: ownerToken) - try? await store.unsubscribeTopicDetailChannel(topicId: topicId, ownerToken: ownerToken) - } - } - - await appViewModel.ensureMessageBusActiveIfPossible() - - while !Task.isCancelled { - do { - try await Task.sleep(for: .seconds(3600)) - } catch { - break - } - } - } - - func handleMessageBusEvent(_ event: MessageBusEventState) { - switch event.kind { - case .topicDetail, .topicReaction: - guard let topicId = event.topicId else { return } - guard topicDetails[topicId] != nil else { return } - scheduleTopicDetailRefresh(topicId: topicId) - case .presence: - guard let topicId = event.topicId else { return } - refreshTopicPresenceState(topicId: topicId) - default: - break - } - } - - func setTopicDetailScrollInteractionActive( - _ isActive: Bool, - topicId: UInt64, - drainDeferredRefresh: Bool = true - ) { - let previous = topicScrollInteractionStates[topicId] ?? false - if isActive { - topicScrollInteractionStates[topicId] = true - } else { - topicScrollInteractionStates.removeValue(forKey: topicId) - } - guard previous != isActive, !isActive, drainDeferredRefresh else { return } - - if let deferredPayload = deferredTopicDetailRefreshPayloads.removeValue(forKey: topicId) { - deferredTopicDetailRefreshTopicIDs.remove(topicId) - Task { @MainActor [weak self] in - await self?.applyTopicDetailPagePayload( - deferredPayload, - detailNotice: nil, - topicId: topicId - ) - } - return - } - - guard deferredTopicDetailRefreshTopicIDs.remove(topicId) != nil, - let store = appViewModel.currentSessionStore(), - topicDetails[topicId] != nil else { - return - } - - Task { @MainActor [weak self] in - await self?.refreshTopicDetailFromMessageBus(topicId: topicId, sessionStore: store) - } - } - - func beginTopicReplyPresence(topicId: UInt64) { - guard appViewModel.session.readiness.canOpenMessageBus else { return } - guard appViewModel.canStartAuthenticatedMutation else { return } - guard topicPresenceHeartbeatTasks[topicId] == nil else { return } - guard let store = appViewModel.currentSessionStore() else { return } - - topicPresenceHeartbeatTasks[topicId] = Task { [weak self] in - while !Task.isCancelled { - do { - try await store.updateTopicReplyPresence(topicId: topicId, active: true) - } catch { - return - } - - guard let self else { return } - guard self.topicPresenceHeartbeatTasks[topicId] != nil else { return } - - do { - try await Task.sleep(for: .seconds(30)) - } catch { - return - } - } - } - } - - func endTopicReplyPresence(topicId: UInt64) async { - let task = topicPresenceHeartbeatTasks.removeValue(forKey: topicId) - task?.cancel() - guard let store = appViewModel.currentSessionStore() else { return } - try? await store.updateTopicReplyPresence(topicId: topicId, active: false) - } - - func scheduleTopicDetailRefresh(topicId: UInt64) { - pendingTopicDetailRefreshTasks[topicId]?.cancel() - pendingTopicDetailRefreshTasks[topicId] = Task { [weak self] in - try? await Task.sleep(for: .seconds(1.5)) - guard !Task.isCancelled else { return } - guard let self, let store = self.appViewModel.currentSessionStore() else { return } - await self.refreshTopicDetailFromMessageBus(topicId: topicId, sessionStore: store) - } - } - - func refreshTopicDetailFromMessageBus( - topicId: UInt64, - sessionStore: FireSessionStore - ) async { - guard topicDetails[topicId] != nil else { return } - if topicScrollInteractionStates[topicId] == true { - deferredTopicDetailRefreshTopicIDs.insert(topicId) - return - } - - do { - let payload = try await refreshTopicDetailPageFromNetwork( - topicId: topicId, - targetPostNumber: nil, - sessionStore: sessionStore - ) - guard topicDetails[topicId] != nil else { return } - if topicScrollInteractionStates[topicId] == true { - deferredTopicDetailRefreshPayloads[topicId] = payload - deferredTopicDetailRefreshTopicIDs.insert(topicId) - return - } - deferredTopicDetailRefreshTopicIDs.remove(topicId) - deferredTopicDetailRefreshPayloads.removeValue(forKey: topicId) - await applyTopicDetailPagePayload( - payload, - detailNotice: nil, - topicId: topicId - ) - } catch { - if await appViewModel.handleRecoverableSessionErrorIfNeeded(error) { - appViewModel.topicDetailLogger()?.notice( - "recoverable session error swallowed during topic detail refresh topic_id=\(topicId)" - ) - return - } - appViewModel.topicDetailLogger()?.error( - "topic detail background refresh failed topic_id=\(topicId) error=\(error.localizedDescription)" - ) - } - } - - func refreshTopicPresenceState(topicId: UInt64) { - guard let store = appViewModel.currentSessionStore() else { return } - Task { [weak self] in - guard let self else { return } - guard let presence = try? await store.topicReplyPresenceState(topicId: topicId) else { - return - } - self.applyTopicPresenceState(presence) - } - } - - func applyTopicPresenceState(_ state: TopicPresenceState) { - let currentUserID = appViewModel.session.bootstrap.currentUserId - let filteredUsers = state.users.filter { user in - guard let currentUserID else { return true } - return user.id != currentUserID - } - setTopicPresenceUsers(filteredUsers, topicId: state.topicId) - } - - func retainedTopicDetailIDs(visibleTopicIDs: Set) -> Set { - let activeTopicIDs = activeTopicDetailOwnerTokens.compactMap { topicId, owners in - owners.isEmpty ? nil : topicId - } - return visibleTopicIDs.union(activeTopicIDs) - } - - func pruneInactiveTopicDetailState( - retaining retainedTopicIDs: Set, - visibleTopicIDs: Set - ) { - let trackedTopicIDs = Set(topicDetails.keys) - .union(topicWindowStates.keys) - .union(topicPresenceUsersByTopic.keys) - .union(errorMessagesByTopicID.keys) - .union(topicAiSummaries.keys) - .union(loadingTopicAiSummaryIDs) - .union(unavailableTopicAiSummaryIDs) - .union(topicAiSummaryErrorsByTopicID.keys) - .union(topicAiSummaryTasks.keys) - .union(topicChromeRevisions.keys) - .union(topicSidecarRevisions.keys) - .union(topicInteractionRevisions.keys) - .union(topicScrollInteractionStates.keys) - .union(deferredTopicDetailRefreshTopicIDs) - .union(deferredTopicDetailRefreshPayloads.keys) - .union(loadingTopicIDs) - .union(loadingMoreTopicPostIDs) - .union(topicPostPreloadTasks.keys) - .union(pendingTopicDetailRefreshTasks.keys) - .union(topicPresenceHeartbeatTasks.keys) - let inactiveTopicIDs = trackedTopicIDs.subtracting(retainedTopicIDs) - guard !inactiveTopicIDs.isEmpty else { - return - } - - let activeTopicIDs = retainedTopicIDs.subtracting(visibleTopicIDs) - appViewModel.topicDetailLogger()?.notice( - "pruning inactive topic detail state retained_active_topic_ids=\(Self.formattedTopicIDs(activeTopicIDs)) pruned_topic_ids=\(Self.formattedTopicIDs(inactiveTopicIDs))" - ) - - for topicId in inactiveTopicIDs.sorted() { - evictTopicDetailState(topicId: topicId, reason: "topic list refresh pruned inactive detail") - } - } - - func activeAnchorPostNumber(topicId: UInt64) -> UInt32? { - topicWindowStates[topicId]?.activeAnchorPostNumber - ?? topicDetailTargetPostNumbers[topicId] - } - - func clearTransientAnchor(topicId: UInt64) { - setPendingScrollTarget(nil, topicId: topicId) - if let window = topicWindowStates[topicId] { - topicWindowStates[topicId] = window.clearingTransientAnchor() - } - } - - func evictTopicDetailState(topicId: UInt64, reason: String) { - topicSourceSnapshots.removeValue(forKey: topicId) - topicDetailNoticesByTopic.removeValue(forKey: topicId) - topicRecoverySlugsByTopic.removeValue(forKey: topicId) - topicTreePresentations.removeValue(forKey: topicId) - topicSourceCursorsByTopic.removeValue(forKey: topicId) - topicPostLookups.removeValue(forKey: topicId) - pendingVisiblePostNumbersByTopic.removeValue(forKey: topicId) - topicScrollInteractionStates.removeValue(forKey: topicId) - deferredTopicDetailRefreshTopicIDs.remove(topicId) - deferredTopicDetailRefreshPayloads.removeValue(forKey: topicId) - topicDetailFeedContentTokens.removeValue(forKey: topicId) - topicDetailChromeContentTokens.removeValue(forKey: topicId) - let removedDetail = topicDetails.removeValue(forKey: topicId) != nil - let removedRenderState = topicRenderStates.removeValue(forKey: topicId) != nil - topicRenderCaches.removeValue(forKey: topicId) - topicRenderGenerations.removeValue(forKey: topicId) - let removedWindow = topicWindowStates.removeValue(forKey: topicId) != nil - let removedPresence = topicPresenceUsersByTopic.removeValue(forKey: topicId) != nil - let removedError = errorMessagesByTopicID.removeValue(forKey: topicId) != nil - let removedAiSummary = topicAiSummaries.removeValue(forKey: topicId) != nil - let removedAiSummaryUnavailable = unavailableTopicAiSummaryIDs.remove(topicId) != nil - let removedAiSummaryError = topicAiSummaryErrorsByTopicID.removeValue(forKey: topicId) != nil - topicCollectionRevisions.removeValue(forKey: topicId) - topicChromeRevisions.removeValue(forKey: topicId) - topicSidecarRevisions.removeValue(forKey: topicId) - topicInteractionRevisions.removeValue(forKey: topicId) - let removedLoadingTopic = loadingTopicIDs.remove(topicId) != nil - let removedLoadingMore = loadingMoreTopicPostIDs.remove(topicId) != nil - let removedLoadMoreError = loadMoreTopicPostErrorsByTopicID.removeValue(forKey: topicId) != nil - let removedLoadingAiSummary = loadingTopicAiSummaryIDs.remove(topicId) != nil - let refreshTask = pendingTopicDetailRefreshTasks.removeValue(forKey: topicId) - let presenceTask = topicPresenceHeartbeatTasks.removeValue(forKey: topicId) - let preloadTask = topicPostPreloadTasks.removeValue(forKey: topicId) - let visibleRangeTask = topicVisibleRangeTasks.removeValue(forKey: topicId) - let renderTask = topicRenderTasks.removeValue(forKey: topicId) - let aiSummaryTask = topicAiSummaryTasks.removeValue(forKey: topicId) - refreshTask?.cancel() - presenceTask?.cancel() - preloadTask?.cancel() - visibleRangeTask?.cancel() - renderTask?.cancel() - aiSummaryTask?.cancel() - - guard removedDetail - || removedRenderState - || removedWindow - || removedPresence - || removedError - || removedAiSummary - || removedAiSummaryUnavailable - || removedAiSummaryError - || removedLoadingTopic - || removedLoadingMore - || removedLoadMoreError - || removedLoadingAiSummary - || refreshTask != nil - || presenceTask != nil - || preloadTask != nil - || visibleRangeTask != nil - || renderTask != nil - || aiSummaryTask != nil - else { - return - } - - appViewModel.topicDetailLogger()?.notice( - "evicted topic detail state topic_id=\(topicId) reason=\(reason)" - ) - } -} diff --git a/native/ios-app/App/Stores/FireTopicDetailStore+Reactions.swift b/native/ios-app/App/Stores/FireTopicDetailStore+Reactions.swift index d1147981..fecc4ab4 100644 --- a/native/ios-app/App/Stores/FireTopicDetailStore+Reactions.swift +++ b/native/ios-app/App/Stores/FireTopicDetailStore+Reactions.swift @@ -1,250 +1 @@ import Foundation - -@MainActor -extension FireTopicDetailStore { - func setPostLiked( - topicId: UInt64, - postId: UInt64, - liked: Bool - ) async throws { - guard appViewModel.canStartAuthenticatedMutation else { - throw FireTopicInteractionError.requiresAuthenticatedWrite - } - guard !mutatingPostIDs.contains(postId) else { - // Another reaction for this post is already in-flight. - throw CancellationError() - } - - // Optimistic UI first — network settles in the background; revert on failure. - let rollback = captureReactionSnapshot(topicId: topicId, postId: postId) - applyOptimisticReactionChange( - topicId: topicId, - postId: postId, - desiredReactionID: liked ? "heart" : nil - ) - - setMutatingPost(true, topicId: topicId, postId: postId) - defer { setMutatingPost(false, topicId: topicId, postId: postId) } - - do { - let sessionStore = try await appViewModel.sessionStoreValue() - updateTopicErrorMessage(nil, topicId: topicId) - let update = try await appViewModel.performWriteWithCloudflareRetry( - originURL: topicCloudflareRecoveryURL(topicId: topicId) - ) { - if liked { - try await sessionStore.likePost(postID: postId) - } else { - try await sessionStore.unlikePost(postID: postId) - } - } - await appViewModel.syncSessionSnapshotIfAvailable(from: sessionStore) - if let update { - applyPostReactionUpdate(topicId: topicId, postId: postId, update: update) - } else { - try? await refreshTopicDetailAfterMutation(topicId: topicId, sessionStore: sessionStore) - } - } catch { - if let rollback { - restoreReactionSnapshot(rollback, topicId: topicId, postId: postId) - } - if await appViewModel.handleRecoverableSessionErrorIfNeeded(error) { - throw error - } - updateTopicErrorMessage(error.localizedDescription, topicId: topicId) - throw error - } - } - - func togglePostReaction( - topicId: UInt64, - postId: UInt64, - reactionId: String - ) async throws { - let trimmedReactionID = reactionId.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmedReactionID.isEmpty else { - return - } - - guard appViewModel.canStartAuthenticatedMutation else { - throw FireTopicInteractionError.requiresAuthenticatedWrite - } - guard !mutatingPostIDs.contains(postId) else { - throw CancellationError() - } - - let currentID = topicDetails[topicId]? - .postStream.posts - .first(where: { $0.id == postId })? - .currentUserReaction?.id - let desiredID = currentID == trimmedReactionID ? nil : trimmedReactionID - - // Optimistic UI first — network settles in the background; revert on failure. - let rollback = captureReactionSnapshot(topicId: topicId, postId: postId) - applyOptimisticReactionChange( - topicId: topicId, - postId: postId, - desiredReactionID: desiredID - ) - - setMutatingPost(true, topicId: topicId, postId: postId) - defer { setMutatingPost(false, topicId: topicId, postId: postId) } - - do { - let sessionStore = try await appViewModel.sessionStoreValue() - updateTopicErrorMessage(nil, topicId: topicId) - let update = try await appViewModel.performWriteWithCloudflareRetry( - originURL: topicCloudflareRecoveryURL(topicId: topicId) - ) { - try await sessionStore.togglePostReaction( - postID: postId, - reactionID: trimmedReactionID - ) - } - applyPostReactionUpdate(topicId: topicId, postId: postId, update: update) - } catch { - if let rollback { - restoreReactionSnapshot(rollback, topicId: topicId, postId: postId) - } - if await appViewModel.handleRecoverableSessionErrorIfNeeded(error) { - throw error - } - updateTopicErrorMessage(error.localizedDescription, topicId: topicId) - throw error - } - } - - func captureReactionSnapshot( - topicId: UInt64, - postId: UInt64 - ) -> ReactionSnapshot? { - guard let post = topicDetails[topicId]?.postStream.posts.first(where: { $0.id == postId }) else { - return nil - } - return ReactionSnapshot( - reactions: post.reactions, - currentUserReaction: post.currentUserReaction, - likeCount: post.likeCount - ) - } - - func restoreReactionSnapshot( - _ snapshot: ReactionSnapshot, - topicId: UInt64, - postId: UInt64 - ) { - applyPostReactionUpdate( - topicId: topicId, - postId: postId, - update: PostReactionUpdateState( - reactions: snapshot.reactions, - currentUserReaction: snapshot.currentUserReaction - ), - likeCountOverride: snapshot.likeCount - ) - } - - /// Immediately mirrors the desired reaction in local state so chips feel instant. - func applyOptimisticReactionChange( - topicId: UInt64, - postId: UInt64, - desiredReactionID: String? - ) { - guard let post = topicDetails[topicId]?.postStream.posts.first(where: { $0.id == postId }) else { - return - } - let currentID = post.currentUserReaction?.id - guard currentID != desiredReactionID else { return } - - var reactions = post.reactions - func adjustCount(for reactionID: String, delta: Int) { - if let index = reactions.firstIndex(where: { $0.id == reactionID }) { - let next = max(0, Int(reactions[index].count) + delta) - if next == 0 { - reactions.remove(at: index) - } else { - reactions[index] = TopicReactionState( - id: reactions[index].id, - kind: reactions[index].kind, - count: UInt32(next), - canUndo: reactions[index].canUndo - ) - } - } else if delta > 0 { - reactions.append( - TopicReactionState( - id: reactionID, - kind: nil, - count: UInt32(delta), - canUndo: true - ) - ) - } - } - - if let currentID { - adjustCount(for: currentID, delta: -1) - } - if let desiredReactionID { - adjustCount(for: desiredReactionID, delta: 1) - } - - let currentUserReaction = desiredReactionID.map { - TopicReactionState(id: $0, kind: nil, count: 1, canUndo: true) - } - let heartCount = reactions.first(where: { $0.id == "heart" })?.count ?? 0 - applyPostReactionUpdate( - topicId: topicId, - postId: postId, - update: PostReactionUpdateState( - reactions: reactions, - currentUserReaction: currentUserReaction - ), - likeCountOverride: heartCount - ) - } - - func applyPostReactionUpdate( - topicId: UInt64, - postId: UInt64, - update: PostReactionUpdateState, - likeCountOverride: UInt32? = nil - ) { - guard var detail = topicDetails[topicId] else { - return - } - guard let postIndex = detail.postStream.posts.firstIndex(where: { $0.id == postId }) else { - return - } - - var post = detail.postStream.posts[postIndex] - let previousHeartCount = post.reactions.first(where: { $0.id == "heart" })?.count - let updatedHeartCount = update.reactions.first(where: { $0.id == "heart" })?.count - - post.reactions = update.reactions - post.currentUserReaction = update.currentUserReaction - - if let likeCountOverride { - post.likeCount = likeCountOverride - } else if let updatedHeartCount { - post.likeCount = updatedHeartCount - } else if previousHeartCount != nil || post.currentUserReaction?.id == "heart" { - post.likeCount = 0 - } - - detail.postStream.posts[postIndex] = post - if var sourceSnapshot = topicSourceSnapshots[topicId] { - if sourceSnapshot.body.post.id == postId { - sourceSnapshot.body.post = post - } - if let loadedIndex = sourceSnapshot.loadedPosts.firstIndex(where: { $0.id == postId }) { - sourceSnapshot.loadedPosts[loadedIndex] = post - } - topicSourceSnapshots[topicId] = sourceSnapshot - } - topicDetails[topicId] = detail - topicPostLookups[topicId] = FireTopicPresentation.topicPostsByID(detail.postStream.posts) - topicDetailFeedContentTokens[topicId] = FireTopicDetailFeedContentToken(detail: detail) - bumpTopicInteractionRevision(topicId: topicId) - } -} diff --git a/native/ios-app/App/Stores/FireTopicDetailStore.swift b/native/ios-app/App/Stores/FireTopicDetailStore.swift index 4330fe1d..56ed68cf 100644 --- a/native/ios-app/App/Stores/FireTopicDetailStore.swift +++ b/native/ios-app/App/Stores/FireTopicDetailStore.swift @@ -1,1227 +1,357 @@ import Foundation - -enum FireTopicDetailSearchDirection { - case backward - case forward -} - -struct FireTopicDetailPagePayload: Sendable { - let sourceSnapshot: TopicDetailSourceSnapshotState - let treePresentation: TopicTreePresentationState -} - -/// Pure data product of a topic-detail page payload, prepared off the main actor. -struct FirePreparedTopicDetailPage: Sendable { - let treePresentation: TopicTreePresentationState - let detail: TopicDetailState - let postLookup: [UInt64: TopicPostState] - let suggestedUnreadRootPostNumber: UInt32? -} - -struct FireTopicDetailFeedContentToken: Equatable { - let header: FireTopicDetailFeedHeaderToken - let stream: [UInt64] - let posts: [FireTopicPostContentToken] - - init(detail: TopicDetailState) { - header = FireTopicDetailFeedHeaderToken(detail: detail) - stream = detail.postStream.stream - posts = detail.postStream.posts.map(FireTopicPostContentToken.init(post:)) - } -} - -struct FireTopicDetailFeedHeaderToken: Equatable { - let id: UInt64 - let messageBusLastId: Int64? - let title: String - let postsCount: UInt32 - let categoryId: UInt64? - let tagNames: [String] - let views: UInt32 - let likeCount: UInt32 - let createdAt: String? - let lastReadPostNumber: UInt32? - let bookmarks: [UInt64] - let acceptedAnswer: Bool - let hasAcceptedAnswer: Bool - let canVote: Bool - let voteCount: Int32 - let userVoted: Bool - let summarizable: Bool - let hasCachedSummary: Bool - let hasSummary: Bool - let archetype: String? - let participants: [FireTopicParticipantContentToken] - - init(detail: TopicDetailState) { - id = detail.id - messageBusLastId = detail.messageBusLastId - title = detail.title - postsCount = detail.postsCount - categoryId = detail.categoryId - tagNames = detail.tags.map(\.name) - views = detail.views - likeCount = detail.likeCount - createdAt = detail.createdAt - lastReadPostNumber = detail.lastReadPostNumber - bookmarks = detail.bookmarks - acceptedAnswer = detail.acceptedAnswer - hasAcceptedAnswer = detail.hasAcceptedAnswer - canVote = detail.canVote - voteCount = detail.voteCount - userVoted = detail.userVoted - summarizable = detail.summarizable - hasCachedSummary = detail.hasCachedSummary - hasSummary = detail.hasSummary - archetype = detail.archetype - participants = detail.details.participants.map(FireTopicParticipantContentToken.init(participant:)) - } -} - -struct FireTopicDetailChromeContentToken: Equatable { - let id: UInt64 - let title: String - let slug: String - let bookmarked: Bool - let bookmarkId: UInt64? - let bookmarkName: String? - let bookmarkReminderAt: String? - let notificationLevel: Int32? - let canEdit: Bool - let archetype: String? - - init(detail: TopicDetailState) { - id = detail.id - title = detail.title - slug = detail.slug - bookmarked = detail.bookmarked - bookmarkId = detail.bookmarkId - bookmarkName = detail.bookmarkName - bookmarkReminderAt = detail.bookmarkReminderAt - notificationLevel = detail.details.notificationLevel - canEdit = detail.details.canEdit - archetype = detail.archetype - } -} - -struct FireTopicParticipantContentToken: Equatable { - let userId: UInt64 - let username: String? - let name: String? - - init(participant: TopicParticipantState) { - userId = participant.userId - username = participant.username - name = participant.name - } -} - -struct FireTopicPostContentToken: Equatable { - let id: UInt64 - let username: String - let name: String? - let avatarTemplate: String? - let presentationLength: Int - let presentationChecksum: UInt64 - let rawLength: Int - let rawChecksum: UInt64 - let postNumber: UInt32 - let postType: Int32 - let createdAt: String? - let updatedAt: String? - let replyCount: UInt32 - let replyToPostNumber: UInt32? - let replyToUsername: String? - let bookmarked: Bool - let bookmarkId: UInt64? - let bookmarkName: String? - let bookmarkReminderAt: String? - let polls: [FireTopicPollContentToken] - let acceptedAnswer: Bool - let canAcceptAnswer: Bool - let canUnacceptAnswer: Bool - let canEdit: Bool - let canDelete: Bool - let canRecover: Bool - let hidden: Bool - - init(post: TopicPostState) { - id = post.id - username = post.username - name = post.name - avatarTemplate = post.avatarTemplate - presentationLength = post.presentation?.plainText().utf8.count ?? 0 - presentationChecksum = post.presentation?.checksum() ?? 0 - rawLength = post.raw?.utf8.count ?? 0 - rawChecksum = post.raw.map(Self.checksum) ?? 0 - postNumber = post.postNumber - postType = post.postType - createdAt = post.createdAt - updatedAt = post.updatedAt - replyCount = post.replyCount - replyToPostNumber = post.replyToPostNumber - replyToUsername = post.replyToUser?.username - bookmarked = post.bookmarked - bookmarkId = post.bookmarkId - bookmarkName = post.bookmarkName - bookmarkReminderAt = post.bookmarkReminderAt - polls = post.polls.map(FireTopicPollContentToken.init(poll:)) - acceptedAnswer = post.acceptedAnswer - canAcceptAnswer = post.canAcceptAnswer - canUnacceptAnswer = post.canUnacceptAnswer - canEdit = post.canEdit - canDelete = post.canDelete - canRecover = post.canRecover - hidden = post.hidden - } - - private static func checksum(_ value: String) -> UInt64 { - var hash: UInt64 = 14_695_981_039_346_656_037 - for byte in value.utf8 { - hash ^= UInt64(byte) - hash = hash &* 1_099_511_628_211 - } - return hash - } -} - -struct FireTopicPollContentToken: Equatable { - let id: UInt64 - let name: String - let kind: String - let status: String - let results: String - let options: [FireTopicPollOptionContentToken] - let voters: UInt32 - let userVotes: [String] - - init(poll: PollState) { - id = poll.id - name = poll.name - kind = poll.kind - status = poll.status - results = poll.results - options = poll.options.map(FireTopicPollOptionContentToken.init(option:)) - voters = poll.voters - userVotes = poll.userVotes - } -} - -struct FireTopicPollOptionContentToken: Equatable { - let id: String - let plainText: String - let htmlLength: Int - let votes: UInt32 - - init(option: PollOptionState) { - id = option.id - plainText = option.plainText - htmlLength = option.html.utf8.count - votes = option.votes - } -} +import Combine @MainActor final class FireTopicDetailStore: ObservableObject { - nonisolated static let topicPostPageSize = 30 - nonisolated static let topicDetailInitialBatchSize: UInt16 = 40 - nonisolated static let topicDetailLoadMoreBatchSize: UInt16 = 40 - nonisolated static let topicPostPrefetchThreshold = 10 - nonisolated static let topicPostForwardExpansionSize = 60 - nonisolated static let replyContextPostBatchSize = 20 - nonisolated static let topicPostVisibleRangeDebounce = Duration.milliseconds(120) - nonisolated static let topicPostHydrationIterationLimit = 8 - - @Published var topicDetails: [UInt64: TopicDetailState] = [:] - @Published var topicRenderStates: [UInt64: FireTopicDetailRenderState] = [:] - @Published var topicPresenceUsersByTopic: [UInt64: [TopicPresenceUserState]] = [:] - @Published var loadingMoreTopicPostIDs: Set = [] - @Published var loadMoreTopicPostErrorsByTopicID: [UInt64: String] = [:] - @Published var loadingTopicIDs: Set = [] - @Published var submittingReplyTopicIDs: Set = [] - @Published var mutatingPostIDs: Set = [] - @Published var postActionTypes: [PostActionTypeState] = [] - @Published var isLoadingPostActionTypes = false - @Published var postRepliesByPostID: [UInt64: [TopicPostState]] = [:] - @Published var postReplyHistoryByPostID: [UInt64: [TopicPostState]] = [:] - @Published var postReplyContextErrorsByPostID: [UInt64: String] = [:] - @Published var loadingPostReplyContextIDs: Set = [] - @Published var topicAiSummaries: [UInt64: TopicAiSummaryState] = [:] - @Published var loadingTopicAiSummaryIDs: Set = [] - @Published var unavailableTopicAiSummaryIDs: Set = [] - @Published var topicAiSummaryErrorsByTopicID: [UInt64: String] = [:] - @Published var topicCollectionRevisions: [UInt64: UInt64] = [:] - @Published var topicChromeRevisions: [UInt64: UInt64] = [:] - @Published var topicSidecarRevisions: [UInt64: UInt64] = [:] - @Published var topicInteractionRevisions: [UInt64: UInt64] = [:] - @Published var errorMessagesByTopicID: [UInt64: String] = [:] + @Published private(set) var snapshots: [UInt64: TopicDetailUiSnapshotState] = [:] - let appViewModel: FireAppViewModel - var topicSourceSnapshots: [UInt64: TopicDetailSourceSnapshotState] = [:] - var topicDetailNoticesByTopic: [UInt64: FireTopicDetailStatusMessage] = [:] - var topicRecoverySlugsByTopic: [UInt64: String] = [:] - var topicTreePresentations: [UInt64: TopicTreePresentationState] = [:] - var topicSourceCursorsByTopic: [UInt64: TopicSourceCursorState] = [:] - var pendingTopicDetailRefreshTasks: [UInt64: Task] = [:] - var topicPresenceHeartbeatTasks: [UInt64: Task] = [:] - var topicPostPreloadTasks: [UInt64: Task] = [:] - var topicVisibleRangeTasks: [UInt64: Task] = [:] - var topicRenderTasks: [UInt64: Task] = [:] - var topicWindowStates: [UInt64: FireTopicDetailWindowState] = [:] - var topicRenderCaches: [UInt64: FireTopicDetailRenderCache] = [:] - var topicRenderGenerations: [UInt64: UInt64] = [:] - var topicPostLookups: [UInt64: [UInt64: TopicPostState]] = [:] - var topicDetailFeedContentTokens: [UInt64: FireTopicDetailFeedContentToken] = [:] - var topicDetailChromeContentTokens: [UInt64: FireTopicDetailChromeContentToken] = [:] - var topicScrollInteractionStates: [UInt64: Bool] = [:] - var deferredTopicDetailRefreshTopicIDs: Set = [] - var deferredTopicDetailRefreshPayloads: [UInt64: FireTopicDetailPagePayload] = [:] - var hydratingTopicPostIDs: Set = [] - var pendingVisiblePostNumbersByTopic: [UInt64: Set] = [:] - var topicDetailTargetPostNumbers: [UInt64: UInt32] = [:] - var activeTopicDetailOwnerTokens: [UInt64: Set] = [:] - var topicAiSummaryTasks: [UInt64: Task] = [:] - var hasLoadedPostActionTypes = false + private let appViewModel: FireAppViewModel + private var handles: [String: TopicDetailSessionHandle] = [:] + private var sinks: [UInt64: FireTopicDetailSnapshotSink] = [:] + private var appliedGeneration: [UInt64: UInt64] = [:] + private var ownersByTopic: [UInt64: Set] = [:] init(appViewModel: FireAppViewModel) { self.appViewModel = appViewModel } - var renderBaseURLString: String { - let trimmed = appViewModel.session.bootstrap.baseUrl.trimmingCharacters(in: .whitespacesAndNewlines) - return trimmed.isEmpty ? "https://linux.do" : trimmed - } - - func bumpTopicCollectionRevision(topicId: UInt64) { - topicCollectionRevisions[topicId, default: 0] &+= 1 - } - - func bumpTopicChromeRevision(topicId: UInt64) { - topicChromeRevisions[topicId, default: 0] &+= 1 - } - - func bumpTopicSidecarRevision(topicId: UInt64) { - topicSidecarRevisions[topicId, default: 0] &+= 1 - } - - func bumpTopicInteractionRevision(topicId: UInt64) { - topicInteractionRevisions[topicId, default: 0] &+= 1 - } - - func setLoadingTopic(_ isLoading: Bool, topicId: UInt64) { - let changed: Bool - if isLoading { - changed = loadingTopicIDs.insert(topicId).inserted - } else { - changed = loadingTopicIDs.remove(topicId) != nil - } - if changed, topicDetails[topicId] == nil { - bumpTopicCollectionRevision(topicId: topicId) - } - } - - func setLoadingMoreTopicPosts(_ isLoading: Bool, topicId: UInt64) { - let changed: Bool - if isLoading { - changed = loadingMoreTopicPostIDs.insert(topicId).inserted - } else { - changed = loadingMoreTopicPostIDs.remove(topicId) != nil - } - if changed { - bumpTopicCollectionRevision(topicId: topicId) - } - } - - func setLoadMoreTopicPostsError(_ message: String?, topicId: UInt64) { - let trimmed = message?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" - let previous = loadMoreTopicPostErrorsByTopicID[topicId] ?? "" - if trimmed.isEmpty { - loadMoreTopicPostErrorsByTopicID.removeValue(forKey: topicId) - } else { - loadMoreTopicPostErrorsByTopicID[topicId] = trimmed - } - if previous != trimmed { - bumpTopicCollectionRevision(topicId: topicId) - } - } - - func setLoadingTopicAiSummary(_ isLoading: Bool, topicId: UInt64) { - // Loading stays off the render path. Most topics have no summary, so publishing - // loading transitions would only insert/remove empty chrome and jitter the feed. - if isLoading { - _ = loadingTopicAiSummaryIDs.insert(topicId) - } else { - _ = loadingTopicAiSummaryIDs.remove(topicId) - } - } - - func setMutatingPost( - _ isMutating: Bool, - topicId: UInt64, - postId: UInt64 - ) { - let changed: Bool - if isMutating { - changed = mutatingPostIDs.insert(postId).inserted - } else { - changed = mutatingPostIDs.remove(postId) != nil - } - if changed { - bumpTopicInteractionRevision(topicId: topicId) - } - } - - func setSubmittingReply( - _ isSubmitting: Bool, - topicId: UInt64 - ) { - let changed: Bool - if isSubmitting { - changed = submittingReplyTopicIDs.insert(topicId).inserted - } else { - changed = submittingReplyTopicIDs.remove(topicId) != nil - } - if changed { - bumpTopicChromeRevision(topicId: topicId) - } - } - - func setLoadingPostReplyContext( - _ isLoading: Bool, - topicId: UInt64, - postId: UInt64 - ) { - let changed: Bool - if isLoading { - changed = loadingPostReplyContextIDs.insert(postId).inserted - } else { - changed = loadingPostReplyContextIDs.remove(postId) != nil - } - if changed { - bumpTopicInteractionRevision(topicId: topicId) - } + func snapshot(for topicId: UInt64) -> TopicDetailUiSnapshotState? { + snapshots[topicId] } - func setPostReplyContextError( - _ message: String?, + func open( topicId: UInt64, - postId: UInt64 + ownerToken: String, + slug: String?, + targetPostNumber: UInt32?, + bypassCache: Bool, + forceLoad: Bool, + trackVisit: Bool, + allowSuggestedUnreadRoot: Bool ) { - let normalized = message?.trimmingCharacters(in: .whitespacesAndNewlines) - let nextValue = normalized?.isEmpty == false ? normalized : nil - guard postReplyContextErrorsByPostID[postId] != nextValue else { + guard let sessionStore = appViewModel.currentSessionStore() else { return } - postReplyContextErrorsByPostID[postId] = nextValue - bumpTopicInteractionRevision(topicId: topicId) - } - - func setTopicPresenceUsers( - _ users: [TopicPresenceUserState], - topicId: UInt64 - ) { - let previousUsers = topicPresenceUsersByTopic[topicId] ?? [] - if users.isEmpty { - if !previousUsers.isEmpty { - topicPresenceUsersByTopic.removeValue(forKey: topicId) - bumpTopicChromeRevision(topicId: topicId) - } + let sink = sinks[topicId] ?? FireTopicDetailSnapshotSink() + sink.store = self + sinks[topicId] = sink + let request = TopicDetailOpenRequestState( + topicId: topicId, + ownerToken: ownerToken, + slugHint: slug, + targetPostNumber: targetPostNumber, + bypassCache: bypassCache, + forceLoad: forceLoad, + trackVisit: trackVisit, + allowSuggestedUnreadRoot: allowSuggestedUnreadRoot + ) + guard let handle = try? sessionStore.openTopicDetail(request: request, observer: sink) else { return } - guard previousUsers != users else { return } - topicPresenceUsersByTopic[topicId] = users - bumpTopicChromeRevision(topicId: topicId) + handles[handleKey(topicId: topicId, ownerToken: ownerToken)] = handle + ownersByTopic[topicId, default: []].insert(ownerToken) } - func setPendingScrollTarget(_ postNumber: UInt32?, topicId: UInt64) { - let previous = topicDetailTargetPostNumbers[topicId] - if let postNumber { - topicDetailTargetPostNumbers[topicId] = postNumber - } else { - topicDetailTargetPostNumbers.removeValue(forKey: topicId) - } - if previous != postNumber { - bumpTopicCollectionRevision(topicId: topicId) + func close(topicId: UInt64, ownerToken: String) { + let key = handleKey(topicId: topicId, ownerToken: ownerToken) + handles.removeValue(forKey: key)?.close() + ownersByTopic[topicId]?.remove(ownerToken) + if ownersByTopic[topicId]?.isEmpty != false { + ownersByTopic[topicId] = nil } } - func updateTopicErrorMessage(_ message: String?, topicId: UInt64) { - let trimmed = message?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" - let previous = errorMessagesByTopicID[topicId] ?? "" - if trimmed.isEmpty { - errorMessagesByTopicID.removeValue(forKey: topicId) - } else { - errorMessagesByTopicID[topicId] = trimmed - } - if previous != trimmed { - bumpTopicCollectionRevision(topicId: topicId) - } - } - - func updateTopicDetailNotice( - _ notice: FireTopicDetailStatusMessage?, - topicId: UInt64 + func reload( + topicId: UInt64, + targetPostNumber: UInt32?, + forceLoad: Bool, + trackVisit: Bool, + allowSuggestedUnreadRoot: Bool ) { - let changed: Bool - if let notice { - changed = topicDetailNoticesByTopic[topicId] != notice - topicDetailNoticesByTopic[topicId] = notice - } else { - changed = topicDetailNoticesByTopic.removeValue(forKey: topicId) != nil - } - if changed { - bumpTopicCollectionRevision(topicId: topicId) - } - } - - func applySession(_ session: SessionState) { - let readiness = session.readiness - if readiness.canReadAuthenticatedApi { - return - } - let isLoggedOut = !readiness.hasLoginCookie && !readiness.hasCurrentUser - if isLoggedOut { - appViewModel.topicDetailLogger()?.notice( - "resetting topic detail store reason=logged-out topic_ids=\(Self.formattedTopicIDs(Set(topicDetails.keys)))" - ) - reset() - } else { - appViewModel.topicDetailLogger()?.debug( - "pausing topic detail fetches reason=transient-unauth retained_topic_ids=\(Self.formattedTopicIDs(Set(topicDetails.keys)))" - ) - cancelInFlightFetches() - } + handle(for: topicId)?.reload( + targetPostNumber: targetPostNumber, + forceLoad: forceLoad, + trackVisit: trackVisit, + allowSuggestedUnreadRoot: allowSuggestedUnreadRoot + ) } - func cancelInFlightFetches() { - pendingTopicDetailRefreshTasks.values.forEach { $0.cancel() } - pendingTopicDetailRefreshTasks = [:] - topicPostPreloadTasks.values.forEach { $0.cancel() } - topicPostPreloadTasks = [:] - topicVisibleRangeTasks.values.forEach { $0.cancel() } - topicVisibleRangeTasks = [:] - topicRenderTasks.values.forEach { $0.cancel() } - topicRenderTasks = [:] - hydratingTopicPostIDs = [] - pendingVisiblePostNumbersByTopic = [:] - loadingTopicIDs.removeAll() - loadingMoreTopicPostIDs.removeAll() - loadMoreTopicPostErrorsByTopicID.removeAll() - errorMessagesByTopicID.removeAll() - loadingPostReplyContextIDs.removeAll() - topicAiSummaryTasks.values.forEach { $0.cancel() } - topicAiSummaryTasks = [:] - loadingTopicAiSummaryIDs.removeAll() + func loadMore(topicId: UInt64) { + handle(for: topicId)?.loadMore() } - func handleMessageBusStopped() { - pendingTopicDetailRefreshTasks.values.forEach { $0.cancel() } - pendingTopicDetailRefreshTasks = [:] - deferredTopicDetailRefreshTopicIDs = [] - deferredTopicDetailRefreshPayloads = [:] - topicPresenceHeartbeatTasks.values.forEach { $0.cancel() } - topicPresenceHeartbeatTasks = [:] - let affectedTopicIDs = Array(topicPresenceUsersByTopic.keys) - topicPresenceUsersByTopic = [:] - affectedTopicIDs.forEach { bumpTopicChromeRevision(topicId: $0) } + func noteVisiblePosts(topicId: UInt64, postNumbers: Set) { + handle(for: topicId)?.noteVisiblePosts(postNumbers: Array(postNumbers)) } - func reset() { - appViewModel.topicDetailLogger()?.notice( - "resetting topic detail store topic_ids=\(Self.formattedTopicIDs(Set(topicDetails.keys))) loading_ids=\(Self.formattedTopicIDs(loadingTopicIDs))" + func noteFilteredFeedTail(topicId: UInt64, itemCount: Int, visibleMaxItem: Int?) { + handle(for: topicId)?.noteFilteredFeedTail( + itemCount: UInt32(clamping: itemCount), + visibleMaxItem: visibleMaxItem.map { UInt32(clamping: $0) } ) - pendingTopicDetailRefreshTasks.values.forEach { $0.cancel() } - pendingTopicDetailRefreshTasks = [:] - topicPresenceHeartbeatTasks.values.forEach { $0.cancel() } - topicPresenceHeartbeatTasks = [:] - topicPostPreloadTasks.values.forEach { $0.cancel() } - topicPostPreloadTasks = [:] - topicVisibleRangeTasks.values.forEach { $0.cancel() } - topicVisibleRangeTasks = [:] - topicRenderTasks.values.forEach { $0.cancel() } - topicRenderTasks = [:] - topicAiSummaryTasks.values.forEach { $0.cancel() } - topicAiSummaryTasks = [:] - activeTopicDetailOwnerTokens = [:] - topicScrollInteractionStates = [:] - deferredTopicDetailRefreshTopicIDs = [] - deferredTopicDetailRefreshPayloads = [:] - topicDetailTargetPostNumbers = [:] - pendingVisiblePostNumbersByTopic = [:] - topicWindowStates = [:] - topicRenderCaches = [:] - topicRenderGenerations = [:] - topicPostLookups = [:] - topicDetailFeedContentTokens = [:] - topicDetailChromeContentTokens = [:] - topicSourceSnapshots = [:] - topicDetailNoticesByTopic = [:] - topicRecoverySlugsByTopic = [:] - topicTreePresentations = [:] - topicSourceCursorsByTopic = [:] - topicDetails = [:] - topicRenderStates = [:] - topicAiSummaries = [:] - unavailableTopicAiSummaryIDs = [] - topicAiSummaryErrorsByTopicID = [:] - topicCollectionRevisions = [:] - topicChromeRevisions = [:] - topicSidecarRevisions = [:] - topicInteractionRevisions = [:] - topicPresenceUsersByTopic = [:] - loadingMoreTopicPostIDs = [] - loadMoreTopicPostErrorsByTopicID = [:] - loadingTopicIDs = [] - loadingTopicAiSummaryIDs = [] - submittingReplyTopicIDs = [] - mutatingPostIDs = [] - postActionTypes = [] - isLoadingPostActionTypes = false - postRepliesByPostID = [:] - postReplyHistoryByPostID = [:] - postReplyContextErrorsByPostID = [:] - loadingPostReplyContextIDs = [] - hasLoadedPostActionTypes = false - hydratingTopicPostIDs = [] - errorMessagesByTopicID = [:] - } - - - - - - - - - - - - - func clearTopicDetailAnchor(topicId: UInt64) { - clearTransientAnchor(topicId: topicId) } - func pendingScrollTarget(topicId: UInt64) -> UInt32? { - topicDetailTargetPostNumbers[topicId] - } - - func isScrollTargetExhausted(topicId: UInt64, postNumber: UInt32) -> Bool { - guard let detail = topicDetails[topicId] else { return false } - if detail.postStream.posts.contains(where: { $0.postNumber == postNumber }) { - return false + func applySession(_ session: SessionState) { + if session.readiness.canReadAuthenticatedApi { + return } - return topicSourceCursorsByTopic[topicId] == nil - } - - func markScrollTargetSatisfied(topicId: UInt64, postNumber: UInt32) { - guard activeAnchorPostNumber(topicId: topicId) == postNumber - || topicDetailTargetPostNumbers[topicId] == postNumber else { + let loggedOut = !session.readiness.hasLoginCookie && !session.readiness.hasCurrentUser + if loggedOut { + for handle in handles.values { + handle.close() + } + handles.removeAll() + ownersByTopic.removeAll() + sinks.removeAll() + appliedGeneration.removeAll() + snapshots.removeAll() return } - clearTransientAnchor(topicId: topicId) - } - - func topicDetail(for topicId: UInt64) -> TopicDetailState? { - topicDetails[topicId] - } - - func topicRenderState(for topicId: UInt64) -> FireTopicDetailRenderState? { - topicRenderStates[topicId] - } - - func topicPostLookup(for topicId: UInt64) -> [UInt64: TopicPostState] { - topicPostLookups[topicId] ?? [:] - } - - func topicPresenceUsers(for topicId: UInt64) -> [TopicPresenceUserState] { - topicPresenceUsersByTopic[topicId] ?? [] - } - - func topicAiSummary(for topicId: UInt64) -> TopicAiSummaryState? { - topicAiSummaries[topicId] - } - - func isLoadingTopicAiSummary(topicId: UInt64) -> Bool { - loadingTopicAiSummaryIDs.contains(topicId) - } - - func topicAiSummaryError(for topicId: UInt64) -> String? { - topicAiSummaryErrorsByTopicID[topicId] - } - - func detailNotice(topicId: UInt64) -> FireTopicDetailStatusMessage? { - topicDetailNoticesByTopic[topicId] - } - - func topicCollectionRevision(topicId: UInt64) -> UInt64 { - topicCollectionRevisions[topicId] ?? 0 - } - - func topicSidecarRevision(topicId: UInt64) -> UInt64 { - topicSidecarRevisions[topicId] ?? 0 - } - - func topicInteractionRevision(topicId: UInt64) -> UInt64 { - topicInteractionRevisions[topicId] ?? 0 - } - - func isLoadingTopic(topicId: UInt64) -> Bool { - loadingTopicIDs.contains(topicId) + appViewModel.currentSessionStore()?.cancelTopicDetailHttp() } - func isLoadingMoreTopicPosts(topicId: UInt64) -> Bool { - loadingMoreTopicPostIDs.contains(topicId) + func noteScrollInteraction(topicId: UInt64, active: Bool) { + handle(for: topicId)?.noteScrollInteraction(active: active) } - func loadMoreTopicPostsError(topicId: UInt64) -> String? { - loadMoreTopicPostErrorsByTopicID[topicId] + func acknowledgeScrollTarget(topicId: UInt64, postNumber: UInt32) { + handle(for: topicId)?.acknowledgeScrollTarget(postNumber: postNumber) } - func errorMessage(for topicId: UInt64) -> String? { - errorMessagesByTopicID[topicId] + func clearScrollTarget(topicId: UInt64) { + handle(for: topicId)?.clearScrollTarget() } - func postReplies(for postID: UInt64) -> [TopicPostState]? { - postRepliesByPostID[postID] + func beginReplyTyping(topicId: UInt64) { + handle(for: topicId)?.beginReplyTyping() } - func postReplyHistory(for postID: UInt64) -> [TopicPostState]? { - postReplyHistoryByPostID[postID] + func endReplyTyping(topicId: UInt64) { + handle(for: topicId)?.endReplyTyping() } - func postReplyContextError(for postID: UInt64) -> String? { - postReplyContextErrorsByPostID[postID] + func reloadAiSummary(topicId: UInt64, skipAgeCheck: Bool) { + handle(for: topicId)?.reloadAiSummary(skipAgeCheck: skipAgeCheck) } - func isLoadingPostReplyContext(postID: UInt64) -> Bool { - loadingPostReplyContextIDs.contains(postID) + func loadReplyContext(topicId: UInt64, postId: UInt64) { + handle(for: topicId)?.loadReplyContext(postId: postId) } - func hasMoreTopicPosts(topicId: UInt64) -> Bool { - topicSourceCursorsByTopic[topicId] != nil + func prepareEdit(topicId: UInt64, postId: UInt64) async throws -> String { + guard let handle = handle(for: topicId) else { + throw FireTopicInteractionError.unavailable + } + return try await handle.prepareEdit(postId: postId) } - - - nonisolated static func canStartNextTopicSourcePageLoad( - hasMoreTopicPosts: Bool, - isLoadingMoreTopicPosts: Bool, - hasPendingPreloadTask: Bool, - hasLoadedDetail: Bool - ) -> Bool { - hasMoreTopicPosts - && !isLoadingMoreTopicPosts - && !hasPendingPreloadTask - && hasLoadedDetail + func submitReply( + topicId: UInt64, + raw: String, + replyToPostNumber: UInt32?, + scrollToCreated: Bool + ) async throws { + guard let handle = handle(for: topicId) else { + throw FireTopicInteractionError.unavailable + } + try await handle.submitReply( + raw: raw, + replyToPostNumber: replyToPostNumber, + scrollToCreated: scrollToCreated + ) } - - - - - - - - - - - func isSubmittingReply(topicId: UInt64) -> Bool { - submittingReplyTopicIDs.contains(topicId) + func setPostLiked(topicId: UInt64, postId: UInt64, liked: Bool) async throws { + guard let handle = handle(for: topicId) else { + throw FireTopicInteractionError.unavailable + } + try await handle.setLiked(postId: postId, liked: liked) } - func isMutatingPost(postId: UInt64) -> Bool { - mutatingPostIDs.contains(postId) + func togglePostReaction(topicId: UInt64, postId: UInt64, reactionId: String) async throws { + guard let handle = handle(for: topicId) else { + throw FireTopicInteractionError.unavailable + } + try await handle.toggleReaction(postId: postId, reactionId: reactionId) } - - - - - - - - - - nonisolated static func mergeReplyContextTreeRows( - existingRows: [TopicTreeRowState], - bodyPostNumber: UInt32, - rootPost: TopicPostState, - contextPosts: [TopicPostState] - ) -> [TopicTreeRowState] { - guard !contextPosts.isEmpty else { - return existingRows + func votePoll(topicId: UInt64, postId: UInt64, pollName: String, options: [String]) async throws { + guard let handle = handle(for: topicId) else { + throw FireTopicInteractionError.unavailable } + try await handle.votePoll(postId: postId, pollName: pollName, options: options) + } - var rows = existingRows - var rowIndexByPostID: [UInt64: Int] = [:] - var rowByPostNumber: [UInt32: TopicTreeRowState] = [:] - rowIndexByPostID.reserveCapacity(existingRows.count + contextPosts.count) - rowByPostNumber.reserveCapacity(existingRows.count + contextPosts.count) - for (index, row) in rows.enumerated() { - rowIndexByPostID[row.postId] = index - rowByPostNumber[row.postNumber] = row + func unvotePoll(topicId: UInt64, postId: UInt64, pollName: String) async throws { + guard let handle = handle(for: topicId) else { + throw FireTopicInteractionError.unavailable } + try await handle.unvotePoll(postId: postId, pollName: pollName) + } - let rootRow = rowByPostNumber[rootPost.postNumber] - let fallbackRootPostNumber = rootRow?.rootPostNumber - ?? rootPost.replyToPostNumber - ?? bodyPostNumber - let fallbackRootDepth = rootRow?.depth ?? (rootPost.postNumber == bodyPostNumber ? 0 : 1) - var nextPreorderIndex = (rows.map(\.preorderIndex).max() ?? 0) + 1 - var nextSiblingIndexByParent = Dictionary( - grouping: rows, - by: { $0.parentPostNumber ?? bodyPostNumber } - ).mapValues(\.count) - - let orderedContextPosts = FireTopicPresentation.uniqueTopicPostsPreservingOrder(contextPosts) - .filter { post in - post.id != rootPost.id && post.postNumber != bodyPostNumber - } - .sorted { lhs, rhs in - if lhs.postNumber == rhs.postNumber { - return lhs.id < rhs.id - } - return lhs.postNumber < rhs.postNumber - } - - let childCountsByParent = Dictionary( - grouping: orderedContextPosts, - by: { $0.replyToPostNumber ?? rootPost.postNumber } - ).mapValues(\.count) - - for post in orderedContextPosts { - if let existingIndex = rowIndexByPostID[post.id] { - rowByPostNumber[post.postNumber] = rows[existingIndex] - continue - } - - let parentPostNumber = post.replyToPostNumber ?? rootPost.postNumber - let parentRow = rowByPostNumber[parentPostNumber] - let depth = parentRow.map { Int($0.depth) + 1 } ?? Int(fallbackRootDepth) + 1 - let rootPostNumber = parentRow?.rootPostNumber ?? fallbackRootPostNumber - let siblingIndex = nextSiblingIndexByParent[parentPostNumber, default: 0] - nextSiblingIndexByParent[parentPostNumber] = siblingIndex + 1 - let row = TopicTreeRowState( - postId: post.id, - postNumber: post.postNumber, - rootPostNumber: rootPostNumber, - parentPostNumber: parentPostNumber, - depth: UInt16(clamping: depth), - preorderIndex: nextPreorderIndex, - hasChildren: (childCountsByParent[post.postNumber] ?? 0) > 0, - descendantCount: post.replyCount, - siblingIndex: UInt16(clamping: siblingIndex), - isLastSibling: true - ) - nextPreorderIndex += 1 - rowIndexByPostID[post.id] = rows.count - rowByPostNumber[post.postNumber] = row - rows.append(row) + func voteTopic(topicId: UInt64, voted: Bool) async throws { + guard let handle = handle(for: topicId) else { + throw FireTopicInteractionError.unavailable } - - return FireTopicPresentation.uniqueTreeRowsPreservingOrder(rows) + try await handle.voteTopic(voted: voted) } - - - - - - - - - - - - - - - - - static func formattedTopicIDs(_ topicIDs: Set) -> String { - topicIDs.sorted().map(String.init).joined(separator: ",") + func updatePost(topicId: UInt64, postId: UInt64, raw: String, editReason: String?) async throws { + guard let handle = handle(for: topicId) else { + throw FireTopicInteractionError.unavailable + } + try await handle.updatePost(postId: postId, raw: raw, editReason: editReason) } - - - - - - - nonisolated static func renderStateCoversRowInputs( - _ renderState: FireTopicDetailRenderState?, - rowInputs: [FireTopicTimelineRowInput], - originalPostID: UInt64? - ) -> Bool { - guard let renderState, - let originalPostID, - renderState.originalRow?.entry.postId == originalPostID else { - return false + func deletePost(topicId: UInt64, postId: UInt64) async throws { + guard let handle = handle(for: topicId) else { + throw FireTopicInteractionError.unavailable } + try await handle.deletePost(postId: postId) + } - let expectedReplyIDs = rowInputs.dropFirst().map(\.postID) - guard renderState.replyRows.map(\.entry.postId) == expectedReplyIDs else { - return false + func recoverPost(topicId: UInt64, postId: UInt64) async throws { + guard let handle = handle(for: topicId) else { + throw FireTopicInteractionError.unavailable } + try await handle.recoverPost(postId: postId) + } - for rowInput in rowInputs { - guard renderState.contentByPostID[rowInput.postID] != nil else { - return false - } + func flagPost(topicId: UInt64, postId: UInt64, flagTypeId: UInt32, message: String?) async throws { + guard let handle = handle(for: topicId) else { + throw FireTopicInteractionError.unavailable } - return true + try await handle.flagPost(postId: postId, flagTypeId: flagTypeId, message: message) } - nonisolated static func elapsedMilliseconds(since startedAt: Date) -> Int64 { - Int64((Date().timeIntervalSince(startedAt) * 1_000).rounded()) + func ensureFlagTypes(topicId: UInt64) async throws { + guard let handle = handle(for: topicId) else { + throw FireTopicInteractionError.unavailable + } + try await handle.ensureFlagTypes() } - nonisolated static func snapshotByAppending( - _ appendedPosts: [TopicPostState], - loadedRanges: [TopicLoadedRangeState], - sourceCursor: TopicSourceCursorState?, - sourceExhausted: Bool, - onto snapshot: TopicDetailSourceSnapshotState - ) -> TopicDetailSourceSnapshotState { - var loaded = snapshot.loadedPosts - var indexByID: [UInt64: Int] = Dictionary( - uniqueKeysWithValues: loaded.enumerated().map { ($0.element.id, $0.offset) } - ) - for post in appendedPosts { - if let index = indexByID[post.id] { - loaded[index] = post - } else { - indexByID[post.id] = loaded.count - loaded.append(post) - } - } - return TopicDetailSourceSnapshotState( - header: snapshot.header, - body: snapshot.body, - rawStreamIds: snapshot.rawStreamIds, - loadedPosts: loaded, - loadedRanges: loadedRanges, - sourceCursor: sourceCursor, - sourceExhausted: sourceExhausted, - focusedPostNumber: snapshot.focusedPostNumber + func createBookmark( + topicId: UInt64, + bookmarkableId: UInt64, + bookmarkableType: String, + name: String?, + reminderAt: String?, + autoDeletePreference: Int32? + ) async throws { + guard let handle = handle(for: topicId) else { + throw FireTopicInteractionError.unavailable + } + try await handle.createBookmark( + bookmarkableId: bookmarkableId, + bookmarkableType: bookmarkableType, + name: name, + reminderAt: reminderAt, + autoDeletePreference: autoDeletePreference ) } - nonisolated static func cookedByteCount(sourceSnapshot: TopicDetailSourceSnapshotState) -> Int { - var seenPostIDs = Set() - var total = 0 - for post in [sourceSnapshot.body.post] + sourceSnapshot.loadedPosts { - if seenPostIDs.insert(post.id).inserted { - total += post.presentation?.plainText().utf8.count ?? 0 - } - } - return total + func updateBookmark( + topicId: UInt64, + bookmarkId: UInt64, + name: String?, + reminderAt: String?, + autoDeletePreference: Int32? + ) async throws { + guard let handle = handle(for: topicId) else { + throw FireTopicInteractionError.unavailable + } + try await handle.updateBookmark( + bookmarkId: bookmarkId, + name: name, + reminderAt: reminderAt, + autoDeletePreference: autoDeletePreference + ) } - - - - - - - - - - static func hydrateRequestedRange( - detail: TopicDetailState, - window: FireTopicDetailWindowState, - fetchPosts: @escaping @Sendable ([UInt64]) async throws -> [TopicPostState] - ) async throws -> (detail: TopicDetailState, exhaustedPostIDs: Set) { - var hydratedDetail = detail - var exhaustedPostIDs = window.exhaustedPostIDs - - while true { - let missingPostIDs = FireTopicPresentation.missingPostIDs( - orderedPostIDs: hydratedDetail.postStream.stream, - in: window.requestedRange, - loadedPostIDs: Set(hydratedDetail.postStream.posts.map(\.id)), - excluding: exhaustedPostIDs - ) - guard !missingPostIDs.isEmpty else { - return (hydratedDetail, exhaustedPostIDs) - } - - let batchPostIDs = Array(missingPostIDs.prefix(topicPostPageSize)) - let fetchedPosts = try await fetchPosts(batchPostIDs) - let returnedPostIDs = Set(fetchedPosts.map(\.id)) - exhaustedPostIDs.formUnion( - batchPostIDs.filter { !returnedPostIDs.contains($0) } - ) - - guard !fetchedPosts.isEmpty else { - continue - } - - hydratedDetail.postStream.posts = FireTopicPresentation.mergeTopicPosts( - existing: hydratedDetail.postStream.posts, - incoming: fetchedPosts, - orderedPostIDs: hydratedDetail.postStream.stream - ) + func deleteBookmark(topicId: UInt64, bookmarkId: UInt64) async throws { + guard let handle = handle(for: topicId) else { + throw FireTopicInteractionError.unavailable } + try await handle.deleteBookmark(bookmarkId: bookmarkId) } - - - - - - - - - - - - - - - - nonisolated static func nextDirectionalSearchRange( - current: Range, - totalCount: Int, - direction: FireTopicDetailSearchDirection - ) -> Range? { - guard totalCount > 0 else { - return nil - } - - let pageSize = topicPostPageSize - let maxWindowSize = FireTopicDetailWindowState.maxWindowSize - let currentCount = current.count - - switch direction { - case .backward: - if current.lowerBound > 0 { - return previousDirectionalSearchRange( - current: current, - totalCount: totalCount, - pageSize: pageSize, - maxWindowSize: maxWindowSize, - currentCount: currentCount - ) - } - guard current.upperBound < totalCount else { - return nil - } - return nextForwardSearchRange( - current: current, - totalCount: totalCount, - pageSize: pageSize, - maxWindowSize: maxWindowSize, - currentCount: currentCount - ) - case .forward: - if current.upperBound < totalCount { - return nextForwardSearchRange( - current: current, - totalCount: totalCount, - pageSize: pageSize, - maxWindowSize: maxWindowSize, - currentCount: currentCount - ) - } - guard current.lowerBound > 0 else { - return nil - } - return previousDirectionalSearchRange( - current: current, - totalCount: totalCount, - pageSize: pageSize, - maxWindowSize: maxWindowSize, - currentCount: currentCount - ) + func setNotificationLevel(topicId: UInt64, level: Int32) async throws { + guard let handle = handle(for: topicId) else { + throw FireTopicInteractionError.unavailable } + try await handle.setNotificationLevel(level: level) } - nonisolated static func previousDirectionalSearchRange( - current: Range, - totalCount: Int, - pageSize: Int, - maxWindowSize: Int, - currentCount: Int - ) -> Range { - if currentCount >= maxWindowSize { - let lowerBound = max(0, current.lowerBound - pageSize) - let upperBound = min(totalCount, lowerBound + currentCount) - return lowerBound.., - totalCount: Int, - pageSize: Int, - maxWindowSize: Int, - currentCount: Int - ) -> Range { - if currentCount >= maxWindowSize { - let upperBound = min(totalCount, current.upperBound + pageSize) - let lowerBound = max(0, upperBound - currentCount) - return lowerBound..( - _ seconds: Double, - operation: String, - _ body: @escaping () async throws -> T - ) async throws -> T { - let coordinator = FireTopicDetailTimeoutCoordinator() - do { - return try await withTaskCancellationHandler { - try await withCheckedThrowingContinuation { continuation in - coordinator.start( - continuation: continuation, - seconds: seconds, - operation: operation, - body: body - ) - } - } onCancel: { - coordinator.cancel() - } - } catch let error as FireTopicDetailTimeoutError { - if !Task.isCancelled { - appViewModel.topicDetailLogger()?.error( - "topic detail fetch timed out operation=\(operation) seconds=\(seconds)" - ) - } - throw error - } catch { - throw error + func createBoost(topicId: UInt64, postId: UInt64, raw: String) async throws { + guard let handle = handle(for: topicId) else { + throw FireTopicInteractionError.unavailable } + try await handle.createBoost(postId: postId, raw: raw) } -} - -private final class FireTopicDetailTimeoutCoordinator: @unchecked Sendable { - private let lock = NSLock() - var continuation: CheckedContinuation? - var workTask: Task? - var timeoutTask: Task? - func start( - continuation: CheckedContinuation, - seconds: Double, - operation: String, - body: @escaping () async throws -> T - ) { - lock.lock() - self.continuation = continuation - lock.unlock() - - let workTask = Task { [weak self] in - do { - let value = try await body() - self?.finish(.success(value), cancelWork: false, cancelTimeout: true) - } catch { - self?.finish(.failure(error), cancelWork: false, cancelTimeout: true) - } - } - setWorkTask(workTask) - - let timeoutTask = Task { [weak self] in - do { - try await Task.sleep(for: .seconds(seconds)) - } catch { - return - } - self?.finish( - .failure(FireTopicDetailTimeoutError(operation: operation, seconds: seconds)), - cancelWork: true, - cancelTimeout: false - ) + func reportTimings(topicId: UInt64, topicTimeMs: UInt32, timings: [UInt32: UInt32]) async -> Bool { + guard let handle = handle(for: topicId) else { + return false } - setTimeoutTask(timeoutTask) + let entries = timings.map { TopicTimingEntryState(postNumber: $0.key, milliseconds: $0.value) } + return (try? await handle.reportTimings(topicTimeMs: topicTimeMs, timings: entries)) ?? false } - func cancel() { - finish(.failure(CancellationError()), cancelWork: true, cancelTimeout: true) + func reset() { + appViewModel.currentSessionStore()?.closeAllTopicDetailSessions() + handles.removeAll() + ownersByTopic.removeAll() + sinks.removeAll() + appliedGeneration.removeAll() + snapshots.removeAll() } - func setWorkTask(_ task: Task) { - lock.lock() - if continuation == nil { - lock.unlock() - task.cancel() + func apply(_ snapshot: TopicDetailUiSnapshotState) { + let applied = appliedGeneration[snapshot.topicId] ?? 0 + guard snapshot.generation >= applied else { return } - workTask = task - lock.unlock() - } - - func setTimeoutTask(_ task: Task) { - lock.lock() - if continuation == nil { - lock.unlock() - task.cancel() - return + appliedGeneration[snapshot.topicId] = snapshot.generation + snapshots[snapshot.topicId] = snapshot + if let patch = snapshot.homeRowPatch { + appViewModel.applyHomeRowCountPatch(patch) } - timeoutTask = task - lock.unlock() } - @discardableResult - func finish( - _ result: Result, - cancelWork: Bool, - cancelTimeout: Bool - ) -> Bool { - lock.lock() - guard let continuation else { - lock.unlock() - return false + private func handle(for topicId: UInt64) -> TopicDetailSessionHandle? { + guard let owner = ownersByTopic[topicId]?.first else { + return nil } - self.continuation = nil - let workTask = self.workTask - let timeoutTask = self.timeoutTask - self.workTask = nil - self.timeoutTask = nil - lock.unlock() + return handles[handleKey(topicId: topicId, ownerToken: owner)] + } - if cancelWork { - workTask?.cancel() - } - if cancelTimeout { - timeoutTask?.cancel() - } - continuation.resume(with: result) - return true + private func handleKey(topicId: UInt64, ownerToken: String) -> String { + "\(topicId)|\(ownerToken)" } } -struct FireTopicDetailTimeoutError: LocalizedError { - let operation: String - let seconds: Double - var errorDescription: String? { - "\(operation)超时(\(Int(seconds))s),请稍后重试" +final class FireTopicDetailSnapshotSink: TopicDetailObserver, @unchecked Sendable { + weak var store: FireTopicDetailStore? + + func onSnapshot(snapshot: TopicDetailUiSnapshotState) { + let store = store + Task { @MainActor in + store?.apply(snapshot) + } } } diff --git a/native/ios-app/App/TopicDetail/Article/FireTopicDetailArticleSnapshot.swift b/native/ios-app/App/TopicDetail/Article/FireTopicDetailArticleSnapshot.swift new file mode 100644 index 00000000..a88b7367 --- /dev/null +++ b/native/ios-app/App/TopicDetail/Article/FireTopicDetailArticleSnapshot.swift @@ -0,0 +1,112 @@ +import Foundation + +extension FireTopicDetailRuntimeConfiguration { + /// Title and tags, summary, body, reaction token, stats, topic vote. + /// Reaction icons stay on the original-post cell and update through + /// `inPlaceUpdateToken`. The body band is `contentToken`. + func makeArticleItems() -> [FireTopicDetailRuntimeItem] { + var items: [FireTopicDetailRuntimeItem] = [] + + items.append(.init( + id: "header:\(topic.id)", + kind: .header, + postID: nil, + postNumber: nil, + replyIndex: nil, + contentToken: AnyHashable([ + displayedTopicTitle, + displayedCategory.map { "\($0.id)|\($0.slug)|\($0.displayName)|\($0.colorHex ?? "")" } ?? "", + displayedTagNames.joined(separator: ","), + displayedParticipants.map { + "\($0.userId)|\($0.username ?? "")|\($0.name ?? "")" + }.joined(separator: ";"), + row.statusLabels.joined(separator: ","), + String(isPrivateMessageThread), + ]) + )) + + if let topicAiSummary { + items.append(.init( + id: "ai-summary:\(topic.id)", + kind: .aiSummary, + postID: nil, + postNumber: nil, + replyIndex: nil, + contentToken: AnyHashable([ + Self.topicAiSummaryContentToken(topicAiSummary), + String(isTopicAiSummaryExpanded), + ]) + )) + } + + if let originalPost, + let originalPostRenderContent { + items.append(.init( + id: "original:\(topic.id)", + kind: .originalPost, + postID: originalPost.id, + postNumber: originalPost.postNumber, + replyIndex: nil, + contentToken: AnyHashable( + postLayoutContentToken( + originalPost, + renderContent: originalPostRenderContent, + replyShortcutCount: nil, + textExpansionState: .disabled + ) + ), + inPlaceUpdateToken: AnyHashable( + postContentToken( + originalPost, + renderContent: originalPostRenderContent, + replyContext: nil, + replyTargetPostNumber: nil, + isLoadingReplyContext: false, + textExpansionState: .disabled + ) + ), + messageBands: makeMessageBands( + originalPost, + renderContent: originalPostRenderContent, + replyContext: nil, + replyShortcutCount: nil, + isReplyThreadExpanded: false, + showsThreadLine: false, + showsDivider: false, + textExpansionState: .disabled + ) + )) + } + + items.append(.init( + id: "stats:\(topic.id)", + kind: .stats, + postID: nil, + postNumber: nil, + replyIndex: nil, + contentToken: AnyHashable([ + String(displayedReplyCount), + String(displayedViewsCount), + displayedInteractionCount.map(String.init) ?? "", + ]) + )) + + if showsTopicVote { + items.append(.init( + id: "topic-vote:\(topic.id)", + kind: .topicVote, + postID: nil, + postNumber: nil, + replyIndex: nil, + contentToken: AnyHashable([ + String(detail?.canVote ?? false), + String(detail?.userVoted ?? false), + String(detail?.voteCount ?? 0), + String(canWriteInteractions), + ]) + )) + } + + return items + } +} diff --git a/native/ios-app/App/TopicDetail/Comments/FireTopicDetailCommentListSnapshot.swift b/native/ios-app/App/TopicDetail/Comments/FireTopicDetailCommentListSnapshot.swift new file mode 100644 index 00000000..32b5f21a --- /dev/null +++ b/native/ios-app/App/TopicDetail/Comments/FireTopicDetailCommentListSnapshot.swift @@ -0,0 +1,159 @@ +import Foundation + +struct FireTopicDetailCommentListSlice { + let items: [FireTopicDetailRuntimeItem] + let replyIndexByPostID: [UInt64: Int] +} + +extension FireTopicDetailRuntimeConfiguration { + /// Floor header, status, then one item per visible message, then the floor footer. + func makeCommentListSlice() -> FireTopicDetailCommentListSlice { + var items: [FireTopicDetailRuntimeItem] = [] + let replyDisplayPlan = makeReplyDisplayPlan() + let currentReplyFooterState = replyFooterState + + items.append(.init( + id: "replies-header:\(topic.id)", + kind: .repliesHeader, + postID: nil, + postNumber: nil, + replyIndex: nil, + contentToken: AnyHashable([ + String(loadedReplyCount), + String(totalReplyCount), + String(displayedFloorCount), + String(detail != nil), + ]) + )) + + if let detailNotice { + items.append(.init( + id: "notice:\(topic.id)", + kind: .notice, + postID: nil, + postNumber: nil, + replyIndex: nil, + contentToken: AnyHashable([ + detailNotice.title ?? "", + detailNotice.message, + String(detailNotice.retryable), + String(detailNotice.emphasizesError), + ]), + statusMessage: detailNotice + )) + } + + if detail == nil || isWaitingForPostRender { + items.append(.init( + id: "body-state:\(topic.id)", + kind: .bodyState, + postID: nil, + postNumber: nil, + replyIndex: nil, + contentToken: AnyHashable( + [ + String(isLoadingTopic), + String(isWaitingForPostRender), + detailError ?? "", + ].joined(separator: "\u{1F}") + ) + )) + return FireTopicDetailCommentListSlice( + items: items, + replyIndexByPostID: replyDisplayPlan.sourceIndexByPostID + ) + } + + for displayedRow in replyDisplayPlan.rows { + let row = displayedRow.row + let post = resolvedPostLookup[row.entry.postId] + let renderContent = renderState?.contentByPostID[row.entry.postId] + ?? post.flatMap { FireTopicPresentation.renderContent(from: $0) } + let replyContext = post.map { + FireTopicPresentation.replyContextLabel( + for: $0, + preferredPostNumber: row.entry.parentPostNumber + ) + } ?? nil + let replyTargetPostNumber = post.map { + FireTopicPresentation.replyTargetPostNumber( + for: $0, + preferredPostNumber: row.entry.parentPostNumber + ) + } ?? nil + let textExpansionState = post.map { + FirePostTextExpansionState( + isCollapsible: true, + isExpanded: isPostTextExpanded($0.id) + ) + } ?? .disabled + let isLoadingReplyContext = post.map { isLoadingPostReplyContext($0.id) } ?? false + items.append(.init( + id: "reply:\(row.entry.postId):\(row.entry.postNumber)", + kind: .reply, + postID: row.entry.postId, + postNumber: row.entry.postNumber, + replyIndex: displayedRow.sourceIndex, + replyShowsThreadLine: displayedRow.showsThreadLine, + replyShowsDivider: displayedRow.showsDivider, + replyShortcutCount: displayedRow.replyShortcutCount, + isReplyThreadExpanded: displayedRow.isReplyThreadExpanded, + contentToken: AnyHashable([ + String(displayedRow.sourceIndex), + post.map { + postLayoutContentToken( + $0, + renderContent: renderContent, + replyShortcutCount: displayedRow.replyShortcutCount, + isReplyThreadExpanded: displayedRow.isReplyThreadExpanded, + textExpansionState: textExpansionState + ) + } ?? "missing", + String(displayedRow.showsThreadLine), + String(displayedRow.showsDivider), + String(displayedRow.isReplyThreadExpanded), + ].joined(separator: "\u{1F}")), + inPlaceUpdateToken: AnyHashable( + post.map { + postContentToken( + $0, + renderContent: renderContent, + replyContext: replyContext, + replyTargetPostNumber: replyTargetPostNumber, + isLoadingReplyContext: isLoadingReplyContext, + textExpansionState: textExpansionState + ) + } ?? "missing" + ), + messageBands: post.map { + makeMessageBands( + $0, + renderContent: renderContent, + replyContext: replyContext, + replyShortcutCount: displayedRow.replyShortcutCount, + isReplyThreadExpanded: displayedRow.isReplyThreadExpanded, + showsThreadLine: displayedRow.showsThreadLine, + showsDivider: displayedRow.showsDivider, + textExpansionState: textExpansionState + ) + } + )) + } + + if currentReplyFooterState != .none { + items.append(.init( + id: "reply-footer:\(topic.id):\(currentReplyFooterState.identityToken)", + kind: .replyFooter, + postID: nil, + postNumber: nil, + replyIndex: nil, + contentToken: AnyHashable(currentReplyFooterState.contentToken) + )) + } + + return FireTopicDetailCommentListSlice( + items: items, + replyIndexByPostID: replyDisplayPlan.sourceIndexByPostID + ) + } +} diff --git a/native/ios-app/App/TopicDetail/Controller/FireTopicDetailInteractionCoordinator.swift b/native/ios-app/App/TopicDetail/Controller/FireTopicDetailInteractionCoordinator.swift index 072cebef..49873f18 100644 --- a/native/ios-app/App/TopicDetail/Controller/FireTopicDetailInteractionCoordinator.swift +++ b/native/ios-app/App/TopicDetail/Controller/FireTopicDetailInteractionCoordinator.swift @@ -60,7 +60,7 @@ extension FireTopicDetailViewController { guard canWriteInteractions else { return } guard !visiblePostNumbers.isEmpty else { return } - let posts = topicDetailStore.topicDetail(for: topic.id)?.postStream.posts ?? [] + let posts = topicDetailStore.snapshot(for: topic.id)?.rows ?? [] guard let coachPost = posts.first(where: { post in visiblePostNumbers.contains(post.postNumber) && !post.hidden @@ -70,7 +70,7 @@ extension FireTopicDetailViewController { didAttemptReactionPickerCoachmark = true FireTopicDetailReactionPickerCoachmark.markSeen() - expandReactionPicker(for: coachPost.id, markCoachmarkSeen: false) + expandReactionPicker(for: coachPost.postId, markCoachmarkSeen: false) } func togglePostTextExpansion(for post: TopicPostState) { @@ -91,12 +91,7 @@ extension FireTopicDetailViewController { expandedReplyRootPostIDs.insert(post.id) applyLocalInteractionSnapshot() - Task { - await topicDetailStore.loadPostReplyContextIfNeeded( - topicID: topic.id, - post: post - ) - } + topicDetailStore.loadReplyContext(topicId: topic.id, postId: post.id) } func toggleLike(for post: TopicPostState) { diff --git a/native/ios-app/App/TopicDetail/Controller/FireTopicDetailModalRouter.swift b/native/ios-app/App/TopicDetail/Controller/FireTopicDetailModalRouter.swift index 674e9ee6..7292635f 100644 --- a/native/ios-app/App/TopicDetail/Controller/FireTopicDetailModalRouter.swift +++ b/native/ios-app/App/TopicDetail/Controller/FireTopicDetailModalRouter.swift @@ -248,7 +248,8 @@ final class FireTopicDetailModalRouter { initialBody: String, initialBodySelectionLocation: Int? = nil, onReplySubmitted: @escaping @MainActor () -> Void, - onSubmissionNotice: @escaping @MainActor (String) -> Void + onSubmissionNotice: @escaping @MainActor (String) -> Void, + scrollToCreatedReply: Bool = false ) { let composer = FireComposerViewController( viewModel: viewModel, @@ -256,7 +257,8 @@ final class FireTopicDetailModalRouter { initialBody: initialBody, initialBodySelectionLocation: initialBodySelectionLocation, onReplySubmitted: onReplySubmitted, - onSubmissionNotice: onSubmissionNotice + onSubmissionNotice: onSubmissionNotice, + scrollToCreatedReply: scrollToCreatedReply ) let navigationController = UINavigationController(rootViewController: composer) navigationController.modalPresentationStyle = .fullScreen @@ -479,27 +481,25 @@ private struct FireTopicDetailPostRepliesHost: View { let onJumpToPost: (UInt32) -> Void var body: some View { + let snapshot = store.snapshot(for: topicID) + let appendedIDs = Set(snapshot?.focusedReplyContext?.appendedPostIds ?? []) + let replies = (snapshot?.rows ?? []) + .filter { appendedIDs.contains($0.postId) } + .map(FireTopicDetailUiProjection.post(from:)) FirePostRepliesSheet( post: context.post, - replies: store.postReplies(for: context.post.id) ?? [], - replyHistory: store.postReplyHistory(for: context.post.id) ?? [], - isLoading: store.isLoadingPostReplyContext(postID: context.post.id), - errorMessage: store.postReplyContextError(for: context.post.id), + replies: replies, + replyHistory: snapshot?.focusedReplyContext?.historyRows.map(FireTopicDetailUiProjection.post(from:)) ?? [], + isLoading: snapshot?.rows.contains { $0.postId == context.post.id && $0.isLoadingReplyContext } ?? false, + errorMessage: nil, baseURLString: baseURLString, onJumpToPost: onJumpToPost, onRetry: { - await store.loadPostReplyContextIfNeeded( - topicID: topicID, - post: context.post, - force: true - ) + store.loadReplyContext(topicId: topicID, postId: context.post.id) } ) .task(id: context.post.id) { - await store.loadPostReplyContextIfNeeded( - topicID: topicID, - post: context.post - ) + store.loadReplyContext(topicId: topicID, postId: context.post.id) } } } diff --git a/native/ios-app/App/TopicDetail/Controller/FireTopicDetailSearchCoordinator.swift b/native/ios-app/App/TopicDetail/Controller/FireTopicDetailSearchCoordinator.swift index acc01f13..07471a96 100644 --- a/native/ios-app/App/TopicDetail/Controller/FireTopicDetailSearchCoordinator.swift +++ b/native/ios-app/App/TopicDetail/Controller/FireTopicDetailSearchCoordinator.swift @@ -42,7 +42,7 @@ extension FireTopicDetailViewController { let previousPostID = activeTopicSearchMatch?.postID topicSearchMatches = FireTopicPresentation.topicSearchMatches( query: topicSearchQuery, - posts: detail?.postStream.posts ?? [] + posts: detailSnapshot.map(FireTopicDetailUiProjection.posts(from:)) ?? [] ) if topicSearchMatches.isEmpty { topicSearchIndex = -1 diff --git a/native/ios-app/App/TopicDetail/Controller/FireTopicDetailToolbarCoordinator.swift b/native/ios-app/App/TopicDetail/Controller/FireTopicDetailToolbarCoordinator.swift index b9fe5b64..f40760ac 100644 --- a/native/ios-app/App/TopicDetail/Controller/FireTopicDetailToolbarCoordinator.swift +++ b/native/ios-app/App/TopicDetail/Controller/FireTopicDetailToolbarCoordinator.swift @@ -40,6 +40,9 @@ final class FireTopicDetailToolbarCoordinator { /// thrash-expands/collapses the action cluster (perf + battery). private var prefersCompactActions = false private var autoCollapseWorkItem: DispatchWorkItem? + private var appliedTitleText: String? + private var appliedTitleVisible: Bool? + private var appliedTrailing: FireTopicDetailToolbarActionsView.Configuration? init( viewController: UIViewController, @@ -52,6 +55,8 @@ final class FireTopicDetailToolbarCoordinator { func configureNavigationItem(_ item: UINavigationItem) { item.largeTitleDisplayMode = .never + // Leading slot is the system back button. Center is the title. + // Trailing is the icon cluster. item.titleView = titleLabel item.rightBarButtonItem = actionsBarItem apply(to: item, animated: false) @@ -140,31 +145,42 @@ final class FireTopicDetailToolbarCoordinator { cancelAutoCollapse() } - actionsView.apply( - configuration: .init( - shareURLAvailable: state.shareURL != nil, - showsNotification: !state.isPrivateMessageThread, - isBookmarked: state.isBookmarked, - canWriteInteractions: state.canWriteInteractions, - canEditTopic: state.canEditTopic && !state.isPrivateMessageThread, - currentNotificationLevel: state.currentNotificationLevel, - isExpanded: areActionsExpanded, - collapsesToOverflow: isTitlePinned || prefersCompactActions - ), - animated: animated + applyTrailingSlot(animated: animated) + applyTitleSlot(animated: animated) + } + + private func trailingConfiguration() -> FireTopicDetailToolbarActionsView.Configuration { + .init( + shareURLAvailable: state.shareURL != nil, + showsNotification: !state.isPrivateMessageThread, + isBookmarked: state.isBookmarked, + canWriteInteractions: state.canWriteInteractions, + canEditTopic: state.canEditTopic && !state.isPrivateMessageThread, + currentNotificationLevel: state.currentNotificationLevel, + isExpanded: areActionsExpanded, + collapsesToOverflow: isTitlePinned || prefersCompactActions ) - updateTitleDisplay(animated: animated) + } + + private func applyTitleSlot(animated: Bool) { + let shouldShow = (isTitlePinned || prefersCompactActions) && !state.title.isEmpty + let text = shouldShow ? state.title : "" + guard appliedTitleText != text || appliedTitleVisible != shouldShow else { return } + appliedTitleText = text + appliedTitleVisible = shouldShow + titleLabel.setTitle(text, visible: shouldShow, animated: animated) + } + + private func applyTrailingSlot(animated: Bool) { + let configuration = trailingConfiguration() + guard appliedTrailing != configuration else { return } + appliedTrailing = configuration + actionsView.apply(configuration: configuration, animated: animated) refreshBarButtonLayout() } private func updateTitleDisplay(animated: Bool) { - // After the first pin, keep the nav title visible so chrome stays calm on scroll-back. - let shouldShow = (isTitlePinned || prefersCompactActions) && !state.title.isEmpty - titleLabel.setTitle( - shouldShow ? state.title : "", - visible: shouldShow, - animated: animated - ) + applyTitleSlot(animated: animated) } private func setActionsExpanded(_ expanded: Bool, animated: Bool) { @@ -179,20 +195,7 @@ final class FireTopicDetailToolbarCoordinator { cancelAutoCollapse() } - actionsView.apply( - configuration: .init( - shareURLAvailable: state.shareURL != nil, - showsNotification: !state.isPrivateMessageThread, - isBookmarked: state.isBookmarked, - canWriteInteractions: state.canWriteInteractions, - canEditTopic: state.canEditTopic && !state.isPrivateMessageThread, - currentNotificationLevel: state.currentNotificationLevel, - isExpanded: areActionsExpanded, - collapsesToOverflow: isTitlePinned || prefersCompactActions - ), - animated: animated - ) - refreshBarButtonLayout() + applyTrailingSlot(animated: animated) if expanded, prefersCompactActions || isTitlePinned { scheduleAutoCollapse() diff --git a/native/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController.swift b/native/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController.swift index 7bc6bbdd..ccaaf07a 100644 --- a/native/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController.swift +++ b/native/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController.swift @@ -66,7 +66,9 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer lazy var runtimeInteractions = FireTopicDetailRuntimeInteractions( isMutatingPost: { [weak self] postID in - self?.topicDetailStore.isMutatingPost(postId: postID) ?? false + self?.topicDetailStore.snapshot(for: self?.row.topic.id ?? 0)?.rows.contains { + $0.postId == postID && $0.isMutating + } ?? false }, isPostTextExpanded: { [weak self] postID in self?.expandedPostTextIDs.contains(postID) ?? false @@ -75,7 +77,9 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer self?.expandedReplyRootPostIDs.contains(postID) ?? false }, isLoadingPostReplyContext: { [weak self] postID in - self?.topicDetailStore.isLoadingPostReplyContext(postID: postID) ?? false + self?.topicDetailStore.snapshot(for: self?.row.topic.id ?? 0)?.rows.contains { + $0.postId == postID && $0.isLoadingReplyContext + } ?? false }, onVisiblePostNumbersChanged: { [weak self] visiblePostNumbers in self?.handleVisiblePostNumbersChanged(visiblePostNumbers) @@ -88,18 +92,19 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer }, onScrollTargetHandled: { [weak self] postNumber in guard let self else { return } - self.topicDetailStore.markScrollTargetSatisfied( + self.topicDetailStore.acknowledgeScrollTarget( topicId: self.topic.id, postNumber: postNumber ) }, onLoadMoreTopicPosts: { [weak self] in guard let self else { return false } - return self.topicDetailStore.loadMoreTopicPostsIfNeeded(topicId: self.topic.id) + self.topicDetailStore.loadMore(topicId: self.topic.id) + return true }, onReloadTopicAiSummary: { [weak self] in guard let self else { return } - self.topicDetailStore.reloadTopicAiSummary(topicId: self.topic.id) + self.topicDetailStore.reloadAiSummary(topicId: self.topic.id, skipAgeCheck: true) }, onToggleTopicAiSummaryExpanded: { [weak self] in guard let self else { return } @@ -195,6 +200,11 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer var snapshotBuildTask: Task? var snapshotBuildGeneration: UInt64 = 0 var cancellables = Set() + private var lastAppliedCollectionRevision: UInt64 = 0 + private var lastAppliedChromeRevision: UInt64 = 0 + private var lastAppliedSidecarRevision: UInt64 = 0 + private var lastAppliedInteractionRevision: UInt64 = 0 + private var lastFeedSnapshot: FireTopicDetailRuntimeSnapshot? var expandedPostTextIDs: Set = [] var expandedReplyRootPostIDs: Set = [] @@ -359,7 +369,7 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer viewModel.restoreTopLevelAPMRoute() Task { await timingTracker.stop() - await topicDetailStore.endTopicReplyPresence(topicId: row.topic.id) + topicDetailStore.endReplyTyping(topicId: row.topic.id) } } @@ -367,12 +377,12 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer row.topic } - var detail: TopicDetailState? { - topicDetailStore.topicDetail(for: topic.id) + var detailSnapshot: TopicDetailUiSnapshotState? { + topicDetailStore.snapshot(for: topic.id) } var displayedTopicTitle: String { - let trimmedDetailTitle = detail?.title.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + let trimmedDetailTitle = detailSnapshot?.chrome.title.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" if !trimmedDetailTitle.isEmpty { return trimmedDetailTitle } @@ -381,7 +391,7 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer } var displayedTopicSlug: String { - let trimmedDetailSlug = detail?.slug.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + let trimmedDetailSlug = detailSnapshot?.chrome.slug.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" if !trimmedDetailSlug.isEmpty { return trimmedDetailSlug } @@ -389,7 +399,7 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer } var displayedCategoryId: UInt64? { - detail?.categoryId ?? topic.categoryId + detailSnapshot?.chrome.categoryId ?? topic.categoryId } var baseURLString: String { @@ -409,7 +419,7 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer } var isPrivateMessageThread: Bool { - FireTopicPresentation.isPrivateMessageArchetype(detail?.archetype) + FireTopicPresentation.isPrivateMessageArchetype(detailSnapshot?.chrome.archetype) } var topicCloudflareRecoveryURL: URL { @@ -421,15 +431,15 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer var topicBookmarkContext: FireBookmarkEditorContext { FireBookmarkEditorContext( - bookmarkID: detail?.bookmarkId, + bookmarkID: detailSnapshot?.chrome.bookmarkId, bookmarkableID: topic.id, bookmarkableType: "Topic", topicID: topic.id, postNumber: nil, title: displayedTopicTitle, - initialName: detail?.bookmarkName, - initialReminderAt: detail?.bookmarkReminderAt, - allowsDelete: detail?.bookmarkId != nil + initialName: detailSnapshot?.chrome.bookmarkName, + initialReminderAt: detailSnapshot?.chrome.bookmarkReminderAt, + allowsDelete: detailSnapshot?.chrome.bookmarkId != nil ) } @@ -463,9 +473,9 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer } feedController.onScrollInteractionChanged = { [weak self] isActive in guard let self else { return } - self.topicDetailStore.setTopicDetailScrollInteractionActive( - isActive, - topicId: self.row.topic.id + self.topicDetailStore.noteScrollInteraction( + topicId: self.row.topic.id, + active: isActive ) self.toolbarCoordinator.updateScrollChrome( isTitlePinned: self.feedController.isTitleCurrentlyPinned, @@ -482,6 +492,14 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer feedController.setup() paginationCoordinator.feedController = feedController + paginationCoordinator.onNoteFilteredFeedTail = { [weak self] itemCount, visibleMaxItem in + guard let self else { return } + self.topicDetailStore.noteFilteredFeedTail( + topicId: self.topic.id, + itemCount: itemCount, + visibleMaxItem: visibleMaxItem + ) + } visibilityCoordinator.feedController = feedController visibilityCoordinator.onVisiblePostNumbersChanged = { [weak self] visiblePostNumbers in @@ -489,7 +507,7 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer } visibilityCoordinator.onScrollTargetHandled = { [weak self] postNumber in guard let self else { return } - self.topicDetailStore.markScrollTargetSatisfied( + self.topicDetailStore.acknowledgeScrollTarget( topicId: self.topic.id, postNumber: postNumber ) @@ -568,9 +586,16 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer viewModel.topicDetailLogger()?.info( "topic detail lifecycle begin topic_id=\(row.topic.id) owner_token=\(detailOwnerToken)" ) - topicDetailStore.beginTopicDetailLifecycle( + let hasReadySnapshot = topicDetailStore.snapshot(for: row.topic.id)?.phase == .ready + topicDetailStore.open( topicId: row.topic.id, - ownerToken: detailOwnerToken + ownerToken: detailOwnerToken, + slug: displayedTopicSlug.isEmpty ? nil : displayedTopicSlug, + targetPostNumber: scrollToPostNumber, + bypassCache: false, + forceLoad: false, + trackVisit: true, + allowSuggestedUnreadRoot: scrollToPostNumber == nil && !hasReadySnapshot ) timingTracker.start { [weak viewModel] topicId, topicTimeMs, timings in @@ -585,7 +610,7 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer subscribeToKeyboardNotifications() subscribeToStoreRevisions() kickOffInitialLoad() - kickOffMessageBusSubscription() + // The Rust topic session subscribes to detail, reactions, polls, and presence. viewModel.topicDetailLogger()?.debug( "topic detail lifecycle begin scheduled tasks topic_id=\(row.topic.id) owner_token=\(detailOwnerToken)" ) @@ -602,17 +627,9 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer snapshotBuildTask?.cancel() snapshotBuildTask = nil cancellables.removeAll() - topicDetailStore.setTopicDetailScrollInteractionActive( - false, - topicId: row.topic.id, - drainDeferredRefresh: false - ) + topicDetailStore.noteScrollInteraction(topicId: row.topic.id, active: false) - topicDetailStore.endTopicDetailLifecycle( - topicId: row.topic.id, - ownerToken: detailOwnerToken, - visibleTopicIDs: viewModel.currentVisibleTopicIDs() - ) + topicDetailStore.close(topicId: row.topic.id, ownerToken: detailOwnerToken) } func kickOffInitialLoad() { @@ -626,7 +643,7 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer self.viewModel.topicDetailLogger()?.info( "topic detail initial load task start topic_id=\(self.row.topic.id) target_post=\(self.scrollToPostNumber.map(String.init) ?? "nil")" ) - await self.loadTopicDetail(targetPostNumber: self.scrollToPostNumber) + _ = self.topicDetailStore.snapshot(for: self.row.topic.id) self.viewModel.topicDetailLogger()?.info( "topic detail initial load task complete topic_id=\(self.row.topic.id) elapsed_ms=\(Self.elapsedMilliseconds(since: startedAt)) cancelled=\(Task.isCancelled)" ) @@ -780,7 +797,7 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer self.viewModel.topicDetailLogger()?.debug( "topic detail messagebus subscription task start topic_id=\(self.row.topic.id) owner_token=\(self.detailOwnerToken)" ) - await self.topicDetailStore.maintainTopicDetailSubscription( + await self.viewModel.maintainTopicDetailSubscription( topicId: self.row.topic.id, ownerToken: self.detailOwnerToken ) @@ -799,52 +816,56 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer viewModel.topicDetailLogger()?.info( "topic detail controller load request start topic_id=\(row.topic.id) force=\(force) target_post=\(targetPostNumber.map(String.init) ?? "nil") slug_present=\(!topicSlug.isEmpty)" ) - await topicDetailStore.loadTopicDetail( + let hasReadySnapshot = topicDetailStore.snapshot(for: row.topic.id)?.phase == .ready + topicDetailStore.open( topicId: row.topic.id, - topicSlug: topicSlug.isEmpty ? nil : topicSlug, + ownerToken: detailOwnerToken, + slug: topicSlug.isEmpty ? nil : topicSlug, targetPostNumber: targetPostNumber, - force: force + bypassCache: force, + forceLoad: force, + trackVisit: true, + allowSuggestedUnreadRoot: targetPostNumber == nil && !hasReadySnapshot ) + let loaded = topicDetailStore.snapshot(for: row.topic.id) viewModel.topicDetailLogger()?.info( - "topic detail controller load request complete topic_id=\(row.topic.id) elapsed_ms=\(Self.elapsedMilliseconds(since: startedAt)) has_detail=\(topicDetailStore.topicDetail(for: row.topic.id) != nil) is_loading=\(topicDetailStore.isLoadingTopic(topicId: row.topic.id)) error_present=\(topicDetailStore.errorMessage(for: row.topic.id) != nil)" + "topic detail controller load request complete topic_id=\(row.topic.id) elapsed_ms=\(Self.elapsedMilliseconds(since: startedAt)) phase=\(String(describing: loaded?.phase)) rows=\(loaded?.rows.count ?? 0)" ) } func subscribeToStoreRevisions() { let topicId = row.topic.id - topicDetailStore.$topicCollectionRevisions - .map { revisions in revisions[topicId] ?? 0 } - .removeDuplicates() - .receive(on: RunLoop.main) - .sink { [weak self] _ in - self?.buildAndApplySnapshot() - } - .store(in: &cancellables) - - topicDetailStore.$topicChromeRevisions - .map { revisions in revisions[topicId] ?? 0 } - .removeDuplicates() - .receive(on: RunLoop.main) - .sink { [weak self] _ in - self?.buildAndApplyChromeState() + topicDetailStore.$snapshots + .map { snapshots -> (UInt64, UInt64, UInt64, UInt64) in + let snapshot = snapshots[topicId] + return ( + snapshot?.collectionRevision ?? 0, + snapshot?.chromeRevision ?? 0, + snapshot?.sidecarRevision ?? 0, + snapshot?.interactionRevision ?? 0 + ) } - .store(in: &cancellables) - - topicDetailStore.$topicSidecarRevisions - .map { revisions in revisions[topicId] ?? 0 } .removeDuplicates() .receive(on: RunLoop.main) - .sink { [weak self] _ in - self?.buildAndApplySnapshot() - } - .store(in: &cancellables) - - topicDetailStore.$topicInteractionRevisions - .map { revisions in revisions[topicId] ?? 0 } - .removeDuplicates() - .receive(on: RunLoop.main) - .sink { [weak self] _ in - self?.buildAndApplySnapshot() + .sink { [weak self] revisions in + guard let self else { return } + let collectionChanged = revisions.0 != self.lastAppliedCollectionRevision + let chromeChanged = revisions.1 != self.lastAppliedChromeRevision + let sidecarChanged = revisions.2 != self.lastAppliedSidecarRevision + let interactionChanged = revisions.3 != self.lastAppliedInteractionRevision + self.lastAppliedCollectionRevision = revisions.0 + self.lastAppliedChromeRevision = revisions.1 + self.lastAppliedSidecarRevision = revisions.2 + self.lastAppliedInteractionRevision = revisions.3 + + if chromeChanged { + self.buildAndApplyChromeState() + } + guard collectionChanged || chromeChanged || sidecarChanged || interactionChanged else { + return + } + let reuseComments = !collectionChanged && !interactionChanged + self.buildAndApplySnapshot(reuseComments: reuseComments) } .store(in: &cancellables) } @@ -862,36 +883,44 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer } func buildCurrentRouteState(topicId: UInt64) -> FireTopicDetailRouteState { - let detail = topicDetailStore.topicDetail(for: topicId) + let chrome = topicDetailStore.snapshot(for: topicId)?.chrome return FireTopicDetailRouteState( currentUsername: viewModel.session.bootstrap.currentUsername, baseURLString: baseURLString, canWriteInteractions: canWriteInteractions, row: row, - displayedCategory: viewModel.categoryPresentation(for: detail?.categoryId ?? row.topic.categoryId) + displayedCategory: viewModel.categoryPresentation(for: chrome?.categoryId ?? row.topic.categoryId) ) } func buildCurrentFeedState(topicId: UInt64) -> FireTopicDetailFeedState { - let store = topicDetailStore + let snapshot = topicDetailStore.snapshot(for: topicId) + let posts = snapshot.map(FireTopicDetailUiProjection.posts(from:)) ?? [] return FireTopicDetailFeedState( - detail: store.topicDetail(for: topicId), - renderState: store.topicRenderState(for: topicId), - postLookup: store.topicPostLookup(for: topicId), - isLoadingTopic: store.isLoadingTopic(topicId: topicId), - isLoadingMoreTopicPosts: store.isLoadingMoreTopicPosts(topicId: topicId), - loadMoreTopicPostsError: store.loadMoreTopicPostsError(topicId: topicId), - hasMoreTopicPosts: store.hasMoreTopicPosts(topicId: topicId), - detailError: store.errorMessage(for: topicId), - detailNotice: store.detailNotice(topicId: topicId), - topicCollectionRevision: store.topicCollectionRevision(topicId: topicId), - pendingScrollTarget: store.pendingScrollTarget(topicId: topicId) + detail: nil, + renderState: nil, + postLookup: Dictionary(uniqueKeysWithValues: posts.map { ($0.id, $0) }), + isLoadingTopic: snapshot?.phase == .loading, + isLoadingMoreTopicPosts: snapshot?.isLoadingMore ?? false, + loadMoreTopicPostsError: snapshot?.loadMoreError, + hasMoreTopicPosts: snapshot?.hasMore ?? false, + detailError: Self.loadErrorMessage(snapshot?.loadError), + detailNotice: snapshot?.notice.map { + FireTopicDetailStatusMessage( + title: $0.title, + message: $0.message, + retryable: $0.retryable, + emphasizesError: $0.emphasizesError + ) + }, + topicCollectionRevision: snapshot?.collectionRevision ?? 0, + pendingScrollTarget: snapshot?.scrollTargetPostNumber ) } func buildCurrentChromeState(topicId: UInt64) -> FireTopicDetailChromeState { FireTopicDetailChromeState( - detail: topicDetailStore.topicDetail(for: topicId), + detail: nil, row: row, baseURLString: baseURLString, canWriteInteractions: canWriteInteractions @@ -899,35 +928,61 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer } func buildCurrentComposerState(topicId: UInt64) -> FireTopicDetailComposerState { - FireTopicDetailComposerState( - typingUsers: topicDetailStore.topicPresenceUsers(for: topicId), + let snapshot = topicDetailStore.snapshot(for: topicId) + return FireTopicDetailComposerState( + typingUsers: snapshot?.composer.typingUsers ?? [], composerContext: composerContext, replyDraft: replyDraft, quickReplyError: quickReplyError, - isSubmittingReply: topicDetailStore.isSubmittingReply(topicId: topicId), + isSubmittingReply: snapshot?.composer.isSubmitting ?? false, minimumReplyLength: minimumReplyLength, canWriteInteractions: canWriteInteractions ) } func buildCurrentSidecarState(topicId: UInt64) -> FireTopicDetailSidecarState { - FireTopicDetailSidecarState( - topicAiSummary: topicDetailStore.topicAiSummary(for: topicId), - isLoadingTopicAiSummary: topicDetailStore.isLoadingTopicAiSummary(topicId: topicId), - topicAiSummaryError: topicDetailStore.topicAiSummaryError(for: topicId) + let sidecar = topicDetailStore.snapshot(for: topicId)?.sidecar + let summary = sidecar?.summarizedText.map { text in + TopicAiSummaryState( + summarizedText: text, + algorithm: sidecar?.algorithm, + outdated: sidecar?.outdated ?? false, + canRegenerate: sidecar?.canRegenerate ?? false, + newPostsSinceSummary: sidecar?.newPostsSinceSummary ?? 0, + updatedAt: sidecar?.updatedAt + ) + } + return FireTopicDetailSidecarState( + topicAiSummary: summary, + isLoadingTopicAiSummary: sidecar?.isLoading ?? false, + topicAiSummaryError: sidecar?.error ) } func buildCurrentInteractionState() -> FireTopicDetailInteractionState { - FireTopicDetailInteractionState( - mutatingPostIDs: topicDetailStore.mutatingPostIDs, - loadingPostReplyContextIDs: topicDetailStore.loadingPostReplyContextIDs, + let rows = topicDetailStore.snapshot(for: row.topic.id)?.rows ?? [] + return FireTopicDetailInteractionState( + mutatingPostIDs: Set(rows.filter(\.isMutating).map(\.postId)), + loadingPostReplyContextIDs: Set(rows.filter(\.isLoadingReplyContext).map(\.postId)), expandedPostTextIDs: expandedPostTextIDs, expandedReplyRootPostIDs: expandedReplyRootPostIDs, expandedReactionPickerPostIDs: expandedReactionPickerPostIDs ) } + private static func loadErrorMessage(_ error: TopicDetailLoadErrorState?) -> String? { + switch error { + case .network: + return "网络错误" + case .loginRequired: + return "需要登录" + case .unrecoverable(let message): + return message + case nil: + return nil + } + } + func buildCurrentPageState() -> FireTopicDetailPageState { let topicId = row.topic.id return FireTopicDetailPageState( @@ -947,6 +1002,7 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer currentUsername: state.route.currentUsername, row: state.route.row, baseURLString: state.route.baseURLString, + snapshot: topicDetailStore.snapshot(for: state.topic.id), detail: state.feed.detail, renderState: state.feed.renderState, pendingScrollTarget: state.feed.pendingScrollTarget, @@ -987,7 +1043,7 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer ) } - func buildAndApplySnapshot() { + func buildAndApplySnapshot(reuseComments: Bool = false) { snapshotBuildGeneration &+= 1 let generation = snapshotBuildGeneration let pageState = buildCurrentPageState() @@ -1004,9 +1060,10 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer snapshotBuildTask?.cancel() let logger = viewModel.topicDetailLogger() - snapshotBuildTask = Task.detached(priority: .userInitiated) { [weak self, snapshotAssembler, input, configuration, generation, logger] in + let cachedComments = reuseComments ? lastFeedSnapshot : nil + snapshotBuildTask = Task.detached(priority: .userInitiated) { [weak self, snapshotAssembler, input, configuration, generation, logger, cachedComments] in let buildStartedAt = Date() - let snapshot = snapshotAssembler.buildSnapshot(from: input) + let snapshot = snapshotAssembler.buildSnapshot(from: input, reusingComments: cachedComments) let buildDurationMs = Self.elapsedMilliseconds(since: buildStartedAt) if buildDurationMs >= fireTopicDetailSnapshotBuildDiagnosticThresholdMs { logger?.debug( @@ -1076,6 +1133,10 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer buildDurationMs: Int64 ) { let applyStartedAt = Date() + lastFeedSnapshot = FireTopicDetailRuntimeSnapshot( + items: snapshot.items, + replyIndexByPostID: snapshot.replyIndexByPostID + ) feedUpdatePipeline.apply(snapshot: snapshot, configuration: configuration) // Collection updates can recreate Texture shells; keep canvas in sync with // the current appearance so dark→light survives data reload paths. @@ -1141,7 +1202,7 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer func performRefresh() async { timingTracker.recordInteraction() - topicDetailStore.clearTopicDetailAnchor(topicId: topic.id) + topicDetailStore.clearScrollTarget(topicId: topic.id) await loadTopicDetail(force: true) // Force-load rebuilds Texture nodes; re-assert shell so dark→light survives PTR. applyAppearanceShell() @@ -1233,9 +1294,9 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer } timingTracker.updateVisiblePostNumbers(visiblePostNumbers) - topicDetailStore.handleVisiblePostNumbersChanged( + topicDetailStore.noteVisiblePosts( topicId: topic.id, - visiblePostNumbers: visiblePostNumbers + postNumbers: visiblePostNumbers ) maybePresentReactionPickerCoachmark(visiblePostNumbers: visiblePostNumbers) } @@ -1271,10 +1332,10 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer func handleQuickReplyFocusChanged(_ focused: Bool) { if focused { - topicDetailStore.beginTopicReplyPresence(topicId: topic.id) + topicDetailStore.beginReplyTyping(topicId: topic.id) } else { Task { - await topicDetailStore.endTopicReplyPresence(topicId: topic.id) + topicDetailStore.endReplyTyping(topicId: topic.id) } } } @@ -1384,9 +1445,6 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer self.composerContext = nil self.quickReplyError = nil self.buildAndApplyChromeState() - Task { - await self.loadTopicDetail(force: true) - } }, onSubmissionNotice: { [weak self] message in self?.modalRouter.presentNotice(message: message) @@ -1438,13 +1496,11 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer self.composerContext = nil self.quickReplyError = nil self.buildAndApplyChromeState() - Task { - await self.loadTopicDetail(targetPostNumber: post.postNumber, force: true) - } }, onSubmissionNotice: { [weak self] message in self?.modalRouter.presentNotice(message: message) - } + }, + scrollToCreatedReply: true ) } @@ -1488,7 +1544,8 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer try await topicDetailStore.submitReply( topicId: topicId, raw: trimmed, - replyToPostNumber: replyToPostNumber + replyToPostNumber: replyToPostNumber, + scrollToCreated: false ) finishQuickReplySuccess() } catch { @@ -1600,9 +1657,7 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer modalRouter.presentBookmarkEditor( context: topicBookmarkContext, recoveryOriginURL: topicCloudflareRecoveryURL, - onReload: { [weak self] in - await self?.loadTopicDetail(force: true) - } + onReload: { } ) } @@ -1610,9 +1665,7 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer modalRouter.presentBookmarkEditor( context: postBookmarkContext(for: post), recoveryOriginURL: topicCloudflareRecoveryURL, - onReload: { [weak self] in - await self?.loadTopicDetail(force: true) - } + onReload: { } ) } @@ -1621,7 +1674,8 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer topicID: topic.id, context: FirePostEditorContext(postID: post.id, postNumber: post.postNumber), onSaved: { [weak self] in - await self?.loadTopicDetail(force: true) + guard let self else { return } + _ = try? await self.topicDetailStore.prepareEdit(topicId: self.topic.id, postId: post.id) } ) } @@ -1629,12 +1683,10 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer func presentTopicEditor() { modalRouter.presentTopicEditor( topicID: topic.id, - initialTitle: detail?.title ?? topic.title, - initialCategoryID: detail?.categoryId ?? topic.categoryId, - initialTags: detail?.tags.map(\.name) ?? row.tagNames, - onSaved: { [weak self] in - await self?.loadTopicDetail(force: true) - } + initialTitle: detailSnapshot?.chrome.title ?? topic.title, + initialCategoryID: detailSnapshot?.chrome.categoryId ?? topic.categoryId, + initialTags: detailSnapshot?.chrome.tags ?? row.tagNames, + onSaved: { } ) } @@ -1660,7 +1712,10 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer notificationLevel: option.rawValue, recoveryOriginURL: topicCloudflareRecoveryURL ) - await loadTopicDetail(force: true) + try await topicDetailStore.setNotificationLevel( + topicId: topic.id, + level: Int32(option.rawValue) + ) FireUIKitToast.show(option.cycleToastMessage, style: .success, in: view) } catch { // Reconcile toolbar glyph if the optimistic cycle preview diverged. diff --git a/native/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedController.swift b/native/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedController.swift index cfa3ade6..b6547e10 100644 --- a/native/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedController.swift +++ b/native/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedController.swift @@ -189,6 +189,7 @@ final class FireTopicDetailFeedController: NSObject, func applyVisibleNodeUpdates( at indices: [Int], + previousItems: [FireTopicDetailRuntimeItem], nextItems: [FireTopicDetailRuntimeItem], configuration: FireTopicDetailRuntimeConfiguration ) { @@ -198,17 +199,21 @@ final class FireTopicDetailFeedController: NSObject, let node = collectionNode.nodeForItem(at: IndexPath(item: index, section: 0)) as? FirePostCellNode else { continue } + let previous = index < previousItems.count ? previousItems[index] : nil + let bands = previous.map { nextItems[index].changedMessageBands(from: $0) } + ?? Set(FireTopicDetailMessageBand.allCases) applyPostCellNode( node, with: postContext, configuration: configuration, - mode: .inPlace + mode: .bands(bands, relayout: false) ) } } func applyVisiblePostRelayouts( at indexPaths: [IndexPath], + previousItems: [FireTopicDetailRuntimeItem], items: [FireTopicDetailRuntimeItem], configuration: FireTopicDetailRuntimeConfiguration ) { @@ -219,11 +224,14 @@ final class FireTopicDetailFeedController: NSObject, let node = collectionNode.nodeForItem(at: indexPath) as? FirePostCellNode else { continue } + let previous = indexPath.item < previousItems.count ? previousItems[indexPath.item] : nil + let bands = previous.map { items[indexPath.item].changedMessageBands(from: $0) } + ?? Set(FireTopicDetailMessageBand.allCases) applyPostCellNode( node, with: postContext, configuration: configuration, - mode: .relayout + mode: .bands(bands, relayout: true) ) } } @@ -717,8 +725,7 @@ final class FireTopicDetailFeedController: NSObject, private enum FirePostCellApplyMode { case configure - case inPlace - case relayout + case bands(Set, relayout: Bool) } private func configurePostCellNode( @@ -778,12 +785,17 @@ final class FireTopicDetailFeedController: NSObject, showsThreadLine: context.showsThreadLine, showsDivider: context.showsDivider ) - case .inPlace: - node.applyInPlaceInteraction(payload: payload, callbacks: callbacks) - case .relayout: - node.applyVisibleRowRelayout(payload: payload, callbacks: callbacks) - node.invalidateCalculatedLayout() - node.setNeedsLayout() + case .bands(let bands, let relayout): + node.applyBands( + bands, + payload: payload, + callbacks: callbacks, + showsThreadLine: context.showsThreadLine, + relayout: relayout + ) + if relayout { + node.invalidateCalculatedLayout() + } } } diff --git a/native/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedModels.swift b/native/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedModels.swift index e51c613d..06a6ecf0 100644 --- a/native/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedModels.swift +++ b/native/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedModels.swift @@ -37,6 +37,7 @@ struct FireTopicDetailRuntimeItem: Hashable, @unchecked Sendable { let isReplyThreadExpanded: Bool let contentToken: AnyHashable let inPlaceUpdateToken: AnyHashable? + let messageBands: FireTopicDetailMessageBands? let statusMessage: FireTopicDetailStatusMessage? init( @@ -51,6 +52,7 @@ struct FireTopicDetailRuntimeItem: Hashable, @unchecked Sendable { isReplyThreadExpanded: Bool = false, contentToken: AnyHashable, inPlaceUpdateToken: AnyHashable? = nil, + messageBands: FireTopicDetailMessageBands? = nil, statusMessage: FireTopicDetailStatusMessage? = nil ) { self.id = id @@ -64,6 +66,7 @@ struct FireTopicDetailRuntimeItem: Hashable, @unchecked Sendable { self.isReplyThreadExpanded = isReplyThreadExpanded self.contentToken = contentToken self.inPlaceUpdateToken = inPlaceUpdateToken + self.messageBands = messageBands self.statusMessage = statusMessage } @@ -95,9 +98,16 @@ struct FireTopicDetailRuntimeItem: Hashable, @unchecked Sendable { hasSameRenderedContent(as: other) && inPlaceUpdateToken != other.inPlaceUpdateToken } + + func changedMessageBands(from previous: FireTopicDetailRuntimeItem) -> Set { + guard let messageBands, let previousBands = previous.messageBands else { + return Set(FireTopicDetailMessageBand.allCases) + } + return messageBands.changed(from: previousBands) + } } -struct FireTopicDetailRuntimeSnapshot { +struct FireTopicDetailRuntimeSnapshot: Sendable { let items: [FireTopicDetailRuntimeItem] let replyIndexByPostID: [UInt64: Int] } @@ -258,6 +268,7 @@ struct FireTopicDetailRuntimeConfiguration: @unchecked Sendable { let currentUsername: String? let row: FireTopicRowPresentation let baseURLString: String + let snapshot: TopicDetailUiSnapshotState? let detail: TopicDetailState? let renderState: FireTopicDetailRenderState? let pendingScrollTarget: UInt32? @@ -324,7 +335,8 @@ struct FireTopicDetailRuntimeConfiguration: @unchecked Sendable { } var displayedTopicTitle: String { - let trimmedDetailTitle = detail?.title.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" + let trimmedDetailTitle = (snapshot?.chrome.title ?? detail?.title)? + .trimmingCharacters(in: .whitespacesAndNewlines) ?? "" if !trimmedDetailTitle.isEmpty { return trimmedDetailTitle } @@ -333,30 +345,26 @@ struct FireTopicDetailRuntimeConfiguration: @unchecked Sendable { } var displayedReplyCount: UInt32 { - if let detail { - return detail.replyCount - } - return topic.replyCount + snapshot?.chrome.replyCount ?? detail?.replyCount ?? topic.replyCount } var displayedViewsCount: UInt32 { - detail?.views ?? topic.views + snapshot?.chrome.views ?? detail?.views ?? topic.views } var displayedCategoryId: UInt64? { - detail?.categoryId ?? topic.categoryId + snapshot?.chrome.categoryId ?? detail?.categoryId ?? topic.categoryId } var displayedTagNames: [String] { - let detailTags = detail?.tags - .map(\.name) + let detailTags = (snapshot?.chrome.tags ?? detail?.tags.map(\.name) ?? []) .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } - .filter { !$0.isEmpty } ?? [] + .filter { !$0.isEmpty } return detailTags.isEmpty ? row.tagNames : detailTags } var isPrivateMessageThread: Bool { - FireTopicPresentation.isPrivateMessageArchetype(detail?.archetype) + FireTopicPresentation.isPrivateMessageArchetype(snapshot?.chrome.archetype ?? detail?.archetype) } var displayedParticipants: [TopicParticipantState] { @@ -364,9 +372,21 @@ struct FireTopicDetailRuntimeConfiguration: @unchecked Sendable { return [] } - let source = !(detail?.details.participants.isEmpty ?? true) - ? detail?.details.participants ?? [] - : topic.participants + let source: [TopicParticipantState] + if let participants = snapshot?.chrome.participants, !participants.isEmpty { + source = participants.map { + TopicParticipantState( + userId: $0.userId, + username: $0.username, + name: $0.name, + avatarTemplate: nil + ) + } + } else if !(detail?.details.participants.isEmpty ?? true) { + source = detail?.details.participants ?? [] + } else { + source = topic.participants + } let currentUsername = currentUsername? .trimmingCharacters(in: .whitespacesAndNewlines) @@ -391,7 +411,10 @@ struct FireTopicDetailRuntimeConfiguration: @unchecked Sendable { } var displayedInteractionCount: UInt32? { - detail.map(FireTopicPresentation.interactionCount(for:)) + if let snapshot { + return snapshot.chrome.likeCount + } + return detail.map(FireTopicPresentation.interactionCount(for:)) } var loadedReplyCount: Int { @@ -403,34 +426,55 @@ struct FireTopicDetailRuntimeConfiguration: @unchecked Sendable { } var totalReplyCount: Int { - detail.map { Int($0.replyCount) } ?? Int(topic.replyCount) + Int(snapshot?.chrome.replyCount ?? detail?.replyCount ?? topic.replyCount) } var showsTopicVote: Bool { + if let chrome = snapshot?.chrome, !isPrivateMessageThread { + return chrome.canVote || chrome.userVoted || chrome.voteCount > 0 + } guard let detail, !isPrivateMessageThread else { return false } return detail.canVote || detail.userVoted || detail.voteCount > 0 } + var resolvedPostLookup: [UInt64: TopicPostState] { + if let snapshot { + return Dictionary(uniqueKeysWithValues: snapshot.rows.map { + ($0.postId, FireTopicDetailUiProjection.post(from: $0)) + }) + } + return postLookup + } + var originalRow: FirePreparedTopicTimelineRow? { - renderState?.originalRow + if let row = snapshot?.rows.first(where: \.isOriginalPost) ?? snapshot?.rows.first { + return FirePreparedTopicTimelineRow(entry: FireTopicDetailUiProjection.timelineEntry(from: row)) + } + return renderState?.originalRow } var originalPost: TopicPostState? { if let originalRow { - return postLookup[originalRow.entry.postId] + return resolvedPostLookup[originalRow.entry.postId] } return detail?.postStream.posts.min(by: { $0.postNumber < $1.postNumber }) } var replyRows: [FirePreparedTopicTimelineRow] { - renderState?.replyRows ?? [] + if let snapshot { + return snapshot.rows.filter { !$0.isOriginalPost }.map { + FirePreparedTopicTimelineRow(entry: FireTopicDetailUiProjection.timelineEntry(from: $0)) + } + } + return renderState?.replyRows ?? [] } var availableReplyRows: [FirePreparedTopicTimelineRow] { - // The feed only renders replies whose backing post entity and render content are both present. - // This keeps transient store/render-state skew from producing placeholder rows. + if snapshot != nil { + return replyRows.filter { resolvedPostLookup[$0.entry.postId] != nil } + } replyRows.filter { postLookup[$0.entry.postId] != nil && renderState?.contentByPostID[$0.entry.postId] != nil @@ -438,6 +482,9 @@ struct FireTopicDetailRuntimeConfiguration: @unchecked Sendable { } var originalPostRenderContent: FireTopicPostRenderContent? { + if let post = originalPost, snapshot != nil { + return FireTopicPresentation.renderContent(from: post) + } guard let originalRow else { return nil } return renderState?.contentByPostID[originalRow.entry.postId] } @@ -447,11 +494,12 @@ struct FireTopicDetailRuntimeConfiguration: @unchecked Sendable { } var isWaitingForPostRender: Bool { - detail != nil && !canRenderOriginalPost + let hasSource = snapshot?.phase == .ready || detail != nil + return hasSource && !canRenderOriginalPost } var replyFooterState: FireTopicDetailRuntimeReplyFooterState { - guard detail != nil else { + guard snapshot != nil || detail != nil else { return .none } if let loadMoreTopicPostsError, diff --git a/native/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedUpdatePipeline.swift b/native/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedUpdatePipeline.swift index 82c8c9e1..dbca3182 100644 --- a/native/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedUpdatePipeline.swift +++ b/native/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedUpdatePipeline.swift @@ -100,17 +100,6 @@ func fireTopicDetailLoadMoreProbe( ) } -func fireTopicDetailShouldLoadMore( - itemCount: Int, - visibleMaxItem: Int?, - trailingThreshold: Int = 5 -) -> Bool { - guard itemCount > 0, let visibleMaxItem else { - return false - } - return itemCount - visibleMaxItem <= trailingThreshold -} - func fireTopicDetailShouldEvaluatePagination( forceLoadMoreEvaluation: Bool, isScrollInteractionActive: Bool @@ -306,6 +295,7 @@ final class FireTopicDetailFeedUpdatePipeline { ) feedController.applyVisibleNodeUpdates( at: indices, + previousItems: previousItems, nextItems: snapshot.items, configuration: configuration ) @@ -367,6 +357,7 @@ final class FireTopicDetailFeedUpdatePipeline { if !inPlacePostRelayouts.isEmpty { feedController.applyVisiblePostRelayouts( at: inPlacePostRelayouts, + previousItems: previousItems, items: snapshot.items, configuration: configuration ) diff --git a/native/ios-app/App/TopicDetail/Feed/FireTopicDetailPaginationCoordinator.swift b/native/ios-app/App/TopicDetail/Feed/FireTopicDetailPaginationCoordinator.swift index 4e0b63a9..2745b7eb 100644 --- a/native/ios-app/App/TopicDetail/Feed/FireTopicDetailPaginationCoordinator.swift +++ b/native/ios-app/App/TopicDetail/Feed/FireTopicDetailPaginationCoordinator.swift @@ -5,6 +5,7 @@ final class FireTopicDetailPaginationCoordinator { weak var feedController: FireTopicDetailFeedController? var configuration: FireTopicDetailRuntimeConfiguration? + var onNoteFilteredFeedTail: ((Int, Int?) -> Void)? private var lastLoadMoreProbe: FireTopicDetailLoadMoreProbe? private var lastRejectedLoadMoreProbe: FireTopicDetailLoadMoreProbe? @@ -41,16 +42,7 @@ final class FireTopicDetailPaginationCoordinator { return false } - if fireTopicDetailShouldLoadMore( - itemCount: probe.itemCount, - visibleMaxItem: probe.visibleMaxItem - ) { - return attemptLoadMore( - probe: probe, - allowRetry: true, - bypassRejectedProbeGuard: forceEvaluation - ) - } + onNoteFilteredFeedTail?(probe.itemCount, probe.visibleMaxItem) lastLoadMoreProbe = probe lastRejectedLoadMoreProbe = nil diff --git a/native/ios-app/App/TopicDetail/Feed/FireTopicDetailRuntimeSnapshotBuilder.swift b/native/ios-app/App/TopicDetail/Feed/FireTopicDetailRuntimeSnapshotBuilder.swift index 1ff98f8b..f8e3884d 100644 --- a/native/ios-app/App/TopicDetail/Feed/FireTopicDetailRuntimeSnapshotBuilder.swift +++ b/native/ios-app/App/TopicDetail/Feed/FireTopicDetailRuntimeSnapshotBuilder.swift @@ -1,225 +1,21 @@ import Foundation extension FireTopicDetailRuntimeConfiguration { - func makeSnapshot() -> FireTopicDetailRuntimeSnapshot { - var items: [FireTopicDetailRuntimeItem] = [] - let replyDisplayPlan = makeReplyDisplayPlan() - let replyIndexByPostID = replyDisplayPlan.sourceIndexByPostID - let currentReplyFooterState = replyFooterState - - items.append(.init( - id: "header:\(topic.id)", - kind: .header, - postID: nil, - postNumber: nil, - replyIndex: nil, - contentToken: AnyHashable([ - displayedTopicTitle, - displayedCategory.map { "\($0.id)|\($0.slug)|\($0.displayName)|\($0.colorHex ?? "")" } ?? "", - displayedTagNames.joined(separator: ","), - displayedParticipants.map { - "\($0.userId)|\($0.username ?? "")|\($0.name ?? "")" - }.joined(separator: ";"), - row.statusLabels.joined(separator: ","), - String(isPrivateMessageThread), - ]) - )) - - if let topicAiSummary { - items.append(.init( - id: "ai-summary:\(topic.id)", - kind: .aiSummary, - postID: nil, - postNumber: nil, - replyIndex: nil, - contentToken: AnyHashable([ - Self.topicAiSummaryContentToken(topicAiSummary), - String(isTopicAiSummaryExpanded), - ]) - )) - } - - if let originalPost, - let originalPostRenderContent { - items.append(.init( - id: "original:\(topic.id)", - kind: .originalPost, - postID: originalPost.id, - postNumber: originalPost.postNumber, - replyIndex: nil, - contentToken: AnyHashable( - postLayoutContentToken( - originalPost, - renderContent: originalPostRenderContent, - replyShortcutCount: nil, - textExpansionState: .disabled - ) - ), - inPlaceUpdateToken: AnyHashable( - postContentToken( - originalPost, - renderContent: originalPostRenderContent, - replyContext: nil, - replyTargetPostNumber: nil, - isLoadingReplyContext: false, - textExpansionState: .disabled - ) - ) - )) - } - - items.append(.init( - id: "stats:\(topic.id)", - kind: .stats, - postID: nil, - postNumber: nil, - replyIndex: nil, - contentToken: AnyHashable([ - String(displayedReplyCount), - String(displayedViewsCount), - displayedInteractionCount.map(String.init) ?? "", - ]) - )) - - if showsTopicVote { - items.append(.init( - id: "topic-vote:\(topic.id)", - kind: .topicVote, - postID: nil, - postNumber: nil, - replyIndex: nil, - contentToken: AnyHashable([ - String(detail?.canVote ?? false), - String(detail?.userVoted ?? false), - String(detail?.voteCount ?? 0), - String(canWriteInteractions), - ]) - )) - } - - items.append(.init( - id: "replies-header:\(topic.id)", - kind: .repliesHeader, - postID: nil, - postNumber: nil, - replyIndex: nil, - contentToken: AnyHashable([ - String(loadedReplyCount), - String(totalReplyCount), - String(displayedFloorCount), - String(detail != nil), - ]) - )) - - if let detailNotice { - items.append(.init( - id: "notice:\(topic.id)", - kind: .notice, - postID: nil, - postNumber: nil, - replyIndex: nil, - contentToken: AnyHashable([ - detailNotice.title ?? "", - detailNotice.message, - String(detailNotice.retryable), - String(detailNotice.emphasizesError), - ]), - statusMessage: detailNotice - )) - } - - if detail == nil || isWaitingForPostRender { - items.append(.init( - id: "body-state:\(topic.id)", - kind: .bodyState, - postID: nil, - postNumber: nil, - replyIndex: nil, - contentToken: AnyHashable( - [ - String(isLoadingTopic), - String(isWaitingForPostRender), - detailError ?? "", - ].joined(separator: "\u{1F}") - ) - )) - } else { - for displayedRow in replyDisplayPlan.rows { - let row = displayedRow.row - let post = postLookup[row.entry.postId] - let renderContent = renderState?.contentByPostID[row.entry.postId] - let replyContext = post.map { - FireTopicPresentation.replyContextLabel( - for: $0, - preferredPostNumber: row.entry.parentPostNumber - ) - } ?? nil - let replyTargetPostNumber = post.map { - FireTopicPresentation.replyTargetPostNumber( - for: $0, - preferredPostNumber: row.entry.parentPostNumber - ) - } ?? nil - let textExpansionState = post.map { - FirePostTextExpansionState( - isCollapsible: true, - isExpanded: isPostTextExpanded($0.id) - ) - } ?? .disabled - let isLoadingReplyContext = post.map { isLoadingPostReplyContext($0.id) } ?? false - items.append(.init( - id: "reply:\(row.entry.postId):\(row.entry.postNumber)", - kind: .reply, - postID: row.entry.postId, - postNumber: row.entry.postNumber, - replyIndex: displayedRow.sourceIndex, - replyShowsThreadLine: displayedRow.showsThreadLine, - replyShowsDivider: displayedRow.showsDivider, - replyShortcutCount: displayedRow.replyShortcutCount, - isReplyThreadExpanded: displayedRow.isReplyThreadExpanded, - contentToken: AnyHashable([ - String(displayedRow.sourceIndex), - post.map { - postLayoutContentToken( - $0, - renderContent: renderContent, - replyShortcutCount: displayedRow.replyShortcutCount, - isReplyThreadExpanded: displayedRow.isReplyThreadExpanded, - textExpansionState: textExpansionState - ) - } ?? "missing", - String(displayedRow.showsThreadLine), - String(displayedRow.showsDivider), - String(displayedRow.isReplyThreadExpanded), - ].joined(separator: "\u{1F}")), - inPlaceUpdateToken: AnyHashable( - post.map { - postContentToken( - $0, - renderContent: renderContent, - replyContext: replyContext, - replyTargetPostNumber: replyTargetPostNumber, - isLoadingReplyContext: isLoadingReplyContext, - textExpansionState: textExpansionState - ) - } ?? "missing" - ) - )) - } - - if currentReplyFooterState != .none { - items.append(.init( - id: "reply-footer:\(topic.id):\(currentReplyFooterState.identityToken)", - kind: .replyFooter, - postID: nil, - postNumber: nil, - replyIndex: nil, - contentToken: AnyHashable(currentReplyFooterState.contentToken) - )) - } + func makeSnapshot( + reusingComments cached: FireTopicDetailRuntimeSnapshot? = nil + ) -> FireTopicDetailRuntimeSnapshot { + let article = makeArticleItems() + if let cached { + return FireTopicDetailRuntimeSnapshot( + items: article + cached.commentItems, + replyIndexByPostID: cached.replyIndexByPostID + ) } - - return FireTopicDetailRuntimeSnapshot(items: items, replyIndexByPostID: replyIndexByPostID) + let comments = makeCommentListSlice() + return FireTopicDetailRuntimeSnapshot( + items: article + comments.items, + replyIndexByPostID: comments.replyIndexByPostID + ) } func makeReplyDisplayPlan() -> FireTopicDetailReplyDisplayPlan { @@ -249,7 +45,7 @@ extension FireTopicDetailRuntimeConfiguration { let selectedSecondaryIndices = threadExpanded ? secondaryIndices : selectedAnchoredSecondaryIndices(from: secondaryIndices) - let declaredReplyCount = postLookup[rootRow.entry.postId].map { Int($0.replyCount) } ?? 0 + let declaredReplyCount = resolvedPostLookup[rootRow.entry.postId].map { Int($0.replyCount) } ?? 0 let totalSecondaryCount = max(secondaryIndices.count, declaredReplyCount) let hiddenCount = max(totalSecondaryCount - selectedSecondaryIndices.count, 0) // Keep the bubble control after expand so the user can collapse again. @@ -408,6 +204,77 @@ extension FireTopicDetailRuntimeConfiguration { Int(row.entry.depth) } + func makeMessageBands( + _ post: TopicPostState, + renderContent: FireTopicPostRenderContent?, + replyContext: String?, + replyShortcutCount: UInt32?, + isReplyThreadExpanded: Bool, + showsThreadLine: Bool, + showsDivider: Bool, + textExpansionState: FirePostTextExpansionState + ) -> FireTopicDetailMessageBands { + let segments = renderContent?.segments ?? [] + let imageToken = segments.compactMap { segment -> String? in + switch segment { + case .image, .onebox: + return segment.signatureToken + case .text: + return nil + } + }.joined(separator: "\u{1F}") + let textToken = segments.compactMap { segment -> String? in + guard case .text = segment else { return nil } + return segment.signatureToken + }.joined(separator: "\u{1F}") + return FireTopicDetailMessageBands( + author: AnyHashable([ + post.username, + post.name ?? "", + post.avatarTemplate ?? "", + FirePostAuthorMetadataDisplay.contentToken(for: post), + post.createdAt ?? "", + String(post.postNumber), + String(post.acceptedAnswer), + ].joined(separator: "\u{1F}")), + quote: AnyHashable(replyContext ?? ""), + images: AnyHashable(imageToken), + text: AnyHashable([ + textToken, + Self.pollsContentToken(post.polls), + FirePostBoostDisplay.contentToken(for: post.boosts), + String(post.hidden), + ].joined(separator: "\u{1F}")), + showMore: AnyHashable([ + String(textExpansionState.isExpanded), + String(textExpansionState.isCollapsible), + String(replyShortcutCount ?? 0), + String(replyShortcutCount != nil), + String(isReplyThreadExpanded), + ].joined(separator: "\u{1F}")), + actions: AnyHashable([ + String(canWriteInteractions), + String(isMutatingPost(post.id)), + String(post.canEdit), + String(post.canDelete), + String(post.canRecover), + String(post.canBoost), + String(post.bookmarked), + String(isSearchHighlighted(postID: post.id)), + ].joined(separator: "\u{1F}")), + reactions: AnyHashable([ + Self.reactionsContentToken(post.reactions), + post.currentUserReaction?.id ?? "", + String(post.likeCount), + String(isReactionPickerExpanded(post.id)), + ].joined(separator: "\u{1F}")), + thread: AnyHashable([ + String(showsThreadLine), + String(showsDivider), + ].joined(separator: "\u{1F}")) + ) + } + func postLayoutContentToken( _ post: TopicPostState, renderContent: FireTopicPostRenderContent?, @@ -415,6 +282,16 @@ extension FireTopicDetailRuntimeConfiguration { isReplyThreadExpanded: Bool = false, textExpansionState: FirePostTextExpansionState ) -> String { + if let row = snapshot?.rows.first(where: { $0.postId == post.id }) { + return [ + String(row.layoutChecksum), + String(replyShortcutCount != nil), + String(isReplyThreadExpanded), + String(isReactionPickerExpanded(post.id)), + String(textExpansionState.isExpanded), + String(textExpansionState.isCollapsible), + ].joined(separator: "\u{1F}") + } [ String(post.id), FirePostAuthorMetadataDisplay.contentToken(for: post), @@ -438,6 +315,16 @@ extension FireTopicDetailRuntimeConfiguration { isLoadingReplyContext: Bool, textExpansionState: FirePostTextExpansionState ) -> String { + if let row = snapshot?.rows.first(where: { $0.postId == post.id }) { + let localChrome = [ + String(textExpansionState.isExpanded), + String(textExpansionState.isCollapsible), + String(isReactionPickerExpanded(post.id)), + String(isSearchHighlighted(postID: post.id)), + String(canWriteInteractions), + ].joined(separator: "\u{1F}") + return [String(row.interactionChecksum), localChrome].joined(separator: "\u{1F}") + } var parts: [String] = [] parts.reserveCapacity(30) parts.append(String(post.id)) diff --git a/native/ios-app/App/TopicDetail/Nodes/FireTopicQuickReplyBarNode.swift b/native/ios-app/App/TopicDetail/Nodes/FireTopicQuickReplyBarNode.swift index 9d42afdf..b731d022 100644 --- a/native/ios-app/App/TopicDetail/Nodes/FireTopicQuickReplyBarNode.swift +++ b/native/ios-app/App/TopicDetail/Nodes/FireTopicQuickReplyBarNode.swift @@ -109,36 +109,53 @@ final class FireTopicQuickReplyBarView: UIView { applyingState = true defer { applyingState = false } + let previous = currentState currentState = state - isHidden = !state.isVisible + var heightChanged = previous.isVisible != state.isVisible - typingLabel.text = state.typingSummary - typingLabel.isHidden = (state.typingSummary?.isEmpty ?? true) - - targetLabel.text = state.targetSummary - targetRow.isHidden = (state.targetSummary?.isEmpty ?? true) - - inputBar.apply( - text: state.draft, - placeholder: state.placeholder, - isSending: state.isSubmitting, - isEnabled: !state.isSubmitting - ) - clearTargetButton.isEnabled = !state.isSubmitting - - if let message = state.validationMessage, message.isEmpty == false { - messageLabel.text = message - messageLabel.textColor = message.contains("至少需要") - ? FireTheme.uiSubtleInk - : FireTheme.uiError - messageLabel.isHidden = false - } else { - messageLabel.text = nil - messageLabel.isHidden = true + if previous.isVisible != state.isVisible { + isHidden = !state.isVisible + } + if previous.typingSummary != state.typingSummary { + typingLabel.text = state.typingSummary + typingLabel.isHidden = (state.typingSummary?.isEmpty ?? true) + heightChanged = true + } + if previous.targetSummary != state.targetSummary { + targetLabel.text = state.targetSummary + targetRow.isHidden = (state.targetSummary?.isEmpty ?? true) + heightChanged = true + } + if previous.draft != state.draft + || previous.placeholder != state.placeholder + || previous.isSubmitting != state.isSubmitting { + inputBar.apply( + text: state.draft, + placeholder: state.placeholder, + isSending: state.isSubmitting, + isEnabled: !state.isSubmitting + ) + clearTargetButton.isEnabled = !state.isSubmitting + heightChanged = true + } + if previous.validationMessage != state.validationMessage { + if let message = state.validationMessage, message.isEmpty == false { + messageLabel.text = message + messageLabel.textColor = message.contains("至少需要") + ? FireTheme.uiSubtleInk + : FireTheme.uiError + messageLabel.isHidden = false + } else { + messageLabel.text = nil + messageLabel.isHidden = true + } + heightChanged = true } - invalidateIntrinsicContentSize() - setNeedsLayout() + if heightChanged { + invalidateIntrinsicContentSize() + setNeedsLayout() + } } func focusInput() { diff --git a/native/ios-app/App/TopicDetail/Shell/FireTopicDetailPageSkeleton.swift b/native/ios-app/App/TopicDetail/Shell/FireTopicDetailPageSkeleton.swift new file mode 100644 index 00000000..bd081a01 --- /dev/null +++ b/native/ios-app/App/TopicDetail/Shell/FireTopicDetailPageSkeleton.swift @@ -0,0 +1,152 @@ +import Foundation + +/// Topic detail is four regions. Each region refreshes on its own. +/// +/// The article and the comment list share one scrolling feed so the post +/// scrolls away and the navigation title can pin. They are still separate +/// item slices: a title or stats change reuses the comment slice. +enum FireTopicDetailPageRegion: Equatable { + /// Navigation bar. The system back button is the leading slot. + case titleBar + /// Original post: title and tags, body, reaction icons, stats. + case article + /// Reply rows plus the floor header and footer. + case comments + /// Bottom quick-reply bar. It is not a feed row. + case composer +} + +/// Slots inside the navigation title bar. Each one applies on its own. +enum FireTopicDetailTitleBarSlot: Equatable { + /// System back button. The page does not rebuild it. + case leading + case title + case trailing +} + +/// Slots inside the quick-reply bar. +enum FireTopicDetailComposerSlot: Equatable { + case typing + case replyTarget + case input + case validation +} + +/// Bands inside one post cell, original post or a comment row. +enum FireTopicDetailMessageBand: Equatable, Hashable, CaseIterable, Sendable { + case author + /// "回复 @用户" quote entry. The quoted paragraph stays in the text segment. + case quote + case images + case text + /// Collapsed body expand, and the reply-count control that opens the floor. + case showMore + case actions + case reactions + /// Vertical floor line and row divider. Not the expand control. + case thread +} + +struct FireTopicDetailMessageBands: Equatable, Sendable { + var author: AnyHashable + var quote: AnyHashable + var images: AnyHashable + var text: AnyHashable + var showMore: AnyHashable + var actions: AnyHashable + var reactions: AnyHashable + var thread: AnyHashable + + func changed(from previous: FireTopicDetailMessageBands) -> Set { + var bands: Set = [] + if author != previous.author { bands.insert(.author) } + if quote != previous.quote { bands.insert(.quote) } + if images != previous.images { bands.insert(.images) } + if text != previous.text { bands.insert(.text) } + if showMore != previous.showMore { bands.insert(.showMore) } + if actions != previous.actions { bands.insert(.actions) } + if reactions != previous.reactions { bands.insert(.reactions) } + if thread != previous.thread { bands.insert(.thread) } + return bands + } +} + +/// Bands inside the original post. Title, stats, and the vote row are their own cells. +/// Body and reactions stay on the original-post cell and update through `messageBands`. +enum FireTopicDetailArticleBand: Equatable { + case titleAndTags + case summary + case body + case reactions + case stats + case topicVote +} + +/// Comment list pieces. A message row is one floor; the header and footer +/// are the floor chrome around that list. +enum FireTopicDetailCommentBand: Equatable { + case floorHeader + case notice + case placeholder + case message + case floorFooter +} + +extension FireTopicDetailRuntimeItemKind { + var pageRegion: FireTopicDetailPageRegion { + switch self { + case .header, .aiSummary, .originalPost, .stats, .topicVote: + return .article + case .repliesHeader, .bodyState, .reply, .replyFooter, .notice: + return .comments + } + } + + var articleBand: FireTopicDetailArticleBand? { + switch self { + case .header: + return .titleAndTags + case .aiSummary: + return .summary + case .originalPost: + return .body + case .stats: + return .stats + case .topicVote: + return .topicVote + case .repliesHeader, .bodyState, .reply, .replyFooter, .notice: + return nil + } + } + + var commentBand: FireTopicDetailCommentBand? { + switch self { + case .repliesHeader: + return .floorHeader + case .notice: + return .notice + case .bodyState: + return .placeholder + case .reply: + return .message + case .replyFooter: + return .floorFooter + case .header, .aiSummary, .originalPost, .stats, .topicVote: + return nil + } + } +} + +extension FireTopicDetailRuntimeItem { + var pageRegion: FireTopicDetailPageRegion { kind.pageRegion } +} + +extension FireTopicDetailRuntimeSnapshot { + var articleItems: [FireTopicDetailRuntimeItem] { + items.filter { $0.pageRegion == .article } + } + + var commentItems: [FireTopicDetailRuntimeItem] { + items.filter { $0.pageRegion == .comments } + } +} diff --git a/native/ios-app/App/TopicDetail/State/FireTopicDetailPageState.swift b/native/ios-app/App/TopicDetail/State/FireTopicDetailPageState.swift index f44432e9..a679b5e1 100644 --- a/native/ios-app/App/TopicDetail/State/FireTopicDetailPageState.swift +++ b/native/ios-app/App/TopicDetail/State/FireTopicDetailPageState.swift @@ -26,7 +26,7 @@ struct FireTopicDetailChromeState { /// Quick-reply state. Typing and validation changes should only apply chrome. struct FireTopicDetailComposerState { - let typingUsers: [TopicPresenceUserState] + let typingUsers: [TopicDetailTypingUserState] let composerContext: FireReplyComposerContext? let replyDraft: String let quickReplyError: String? diff --git a/native/ios-app/App/TopicDetail/State/FireTopicDetailSnapshotAssembler.swift b/native/ios-app/App/TopicDetail/State/FireTopicDetailSnapshotAssembler.swift index 88872e1a..24046beb 100644 --- a/native/ios-app/App/TopicDetail/State/FireTopicDetailSnapshotAssembler.swift +++ b/native/ios-app/App/TopicDetail/State/FireTopicDetailSnapshotAssembler.swift @@ -9,9 +9,10 @@ struct FireTopicDetailSnapshotAssembler: Sendable { // MARK: - Build func buildSnapshot( - from input: FireTopicDetailSnapshotInput + from input: FireTopicDetailSnapshotInput, + reusingComments cached: FireTopicDetailRuntimeSnapshot? = nil ) -> FireTopicDetailPageSnapshot { - let runtimeSnapshot = input.configuration.makeSnapshot() + let runtimeSnapshot = input.configuration.makeSnapshot(reusingComments: cached) return FireTopicDetailPageSnapshot( items: runtimeSnapshot.items, diff --git a/native/ios-app/App/TopicDetail/Support/FireTopicPresentation.swift b/native/ios-app/App/TopicDetail/Support/FireTopicPresentation.swift index de521306..c9042ed3 100644 --- a/native/ios-app/App/TopicDetail/Support/FireTopicPresentation.swift +++ b/native/ios-app/App/TopicDetail/Support/FireTopicPresentation.swift @@ -131,6 +131,20 @@ enum FireTopicPostRenderSegment: @unchecked Sendable { if case .onebox = self { return true } return false } + + enum Kind: Hashable { + case text + case image + case onebox + } + + var kind: Kind { + switch self { + case .text: return .text + case .image: return .image + case .onebox: return .onebox + } + } } struct FirePreparedTopicTimelineRow: Identifiable, Sendable { @@ -1188,3 +1202,98 @@ extension Color { ) } } + +enum FireTopicDetailUiProjection { + static func posts(from snapshot: TopicDetailUiSnapshotState) -> [TopicPostState] { + snapshot.rows.map(post(from:)) + } + + static func timelineEntry(from row: TopicDetailUiRowState) -> FireTopicTimelineEntry { + FireTopicTimelineEntry( + postId: row.postId, + postNumber: row.postNumber, + parentPostNumber: row.parentPostNumber, + depth: UInt32(row.depth), + isOriginalPost: row.isOriginalPost + ) + } + + static func post(from row: TopicDetailUiRowState) -> TopicPostState { + let author = row.author + TopicPostState( + id: row.postId, + username: author.username, + name: author.name, + avatarTemplate: author.avatarTemplate, + authorMetadata: TopicPostAuthorMetadataState( + userId: author.userId, + userTitle: author.userTitle, + primaryGroupName: author.primaryGroupName, + flairUrl: author.flairUrl, + flairName: author.flairName, + flairBgColor: author.flairBgColor, + flairColor: author.flairColor, + flairGroupId: author.flairGroupId, + moderator: author.moderator, + admin: author.admin, + groupModerator: author.groupModerator, + userStatusEmoji: author.userStatusEmoji, + userStatusDescription: author.userStatusDescription + ), + presentation: row.presentation, + raw: nil, + postNumber: row.postNumber, + postType: row.postType, + createdAt: row.createdAt, + updatedAt: row.updatedAt, + likeCount: row.likeCount, + replyCount: row.replyCount, + replyToPostNumber: row.parentPostNumber, + replyToUser: row.replyToUser.map { + TopicReplyToUserState( + username: $0.username, + name: $0.name, + avatarTemplate: $0.avatarTemplate + ) + }, + bookmarked: row.bookmarked, + bookmarkId: row.bookmarkId, + bookmarkName: row.bookmarkName, + bookmarkReminderAt: row.bookmarkReminderAt, + reactions: row.reactions.map { + TopicReactionState(id: $0.id, kind: $0.kind, count: $0.count, canUndo: $0.canUndo) + }, + currentUserReaction: row.currentReactionId.flatMap { id in + row.reactions.first { $0.id == id }.map { + TopicReactionState(id: $0.id, kind: $0.kind, count: $0.count, canUndo: $0.canUndo) + } + }, + boosts: row.boosts.map { boost in + TopicPostBoostState( + id: boost.id, + presentation: boost.presentation, + displayText: boost.displayText, + user: TopicPostBoostUserState( + id: boost.user.id, + username: boost.user.username, + name: boost.user.name, + avatarTemplate: boost.user.avatarTemplate + ), + canDelete: boost.canDelete, + canFlag: boost.canFlag, + userFlagStatus: boost.userFlagStatus, + availableFlags: boost.availableFlags + ) + }, + canBoost: row.canBoost, + polls: row.polls, + acceptedAnswer: row.acceptedAnswer, + canAcceptAnswer: row.canAcceptAnswer, + canUnacceptAnswer: row.canUnacceptAnswer, + canEdit: row.canEdit, + canDelete: row.canDelete, + canRecover: row.canRecover, + hidden: row.hidden + ) + } +} diff --git a/native/ios-app/App/ViewModels/FireAppViewModel.swift b/native/ios-app/App/ViewModels/FireAppViewModel.swift index faa60cb6..875742f3 100644 --- a/native/ios-app/App/ViewModels/FireAppViewModel.swift +++ b/native/ios-app/App/ViewModels/FireAppViewModel.swift @@ -60,6 +60,7 @@ final class FireAppViewModel: ObservableObject { /// epoch, and once an epoch's resync has failed we stop retrying it on read /// errors so the caller falls back to reporting the original error. private var readPathLoginRecoveryTask: Task? + private var lastReadPathLoginGeneration: UInt64 = 0 private var readPathLoginRecoveryEpoch: UInt64? private var readPathLoginRecoveryAttemptedEpochs: Set = [] /// Single-flight mid-session headless reauth (Google first). @@ -788,62 +789,73 @@ final class FireAppViewModel: ObservableObject { homeFeedStore?.loadMoreTopics() } - func patchHomeTopicCounts(from detail: TopicDetailState) { - homeFeedStore?.patchTopicCounts(from: detail) + func applyHomeRowCountPatch(_ patch: TopicHomeRowCountPatchState) { + homeFeedStore?.applyHomeRowCountPatch(patch) } - func loadTopicDetail( + func openTopicDetail( topicId: UInt64, + ownerToken: String, topicSlug: String? = nil, targetPostNumber: UInt32? = nil, - force: Bool = false - ) async { - await topicDetailStore?.loadTopicDetail( + bypassCache: Bool, + forceLoad: Bool, + trackVisit: Bool, + allowSuggestedUnreadRoot: Bool + ) { + topicDetailStore?.open( topicId: topicId, - topicSlug: topicSlug, + ownerToken: ownerToken, + slug: topicSlug, targetPostNumber: targetPostNumber, - force: force + bypassCache: bypassCache, + forceLoad: forceLoad, + trackVisit: trackVisit, + allowSuggestedUnreadRoot: allowSuggestedUnreadRoot ) } func clearTopicDetailAnchor(topicId: UInt64) { - topicDetailStore?.clearTopicDetailAnchor(topicId: topicId) + topicDetailStore?.clearScrollTarget(topicId: topicId) } - func topicDetail(for topicId: UInt64) -> TopicDetailState? { - topicDetailStore?.topicDetail(for: topicId) + func topicDetail(for topicId: UInt64) -> TopicDetailUiSnapshotState? { + topicDetailStore?.snapshot(for: topicId) } - func topicPresenceUsers(for topicId: UInt64) -> [TopicPresenceUserState] { - topicDetailStore?.topicPresenceUsers(for: topicId) ?? [] + func topicPresenceUsers(for topicId: UInt64) -> [TopicDetailTypingUserState] { + topicDetailStore?.snapshot(for: topicId)?.composer.typingUsers ?? [] } func isLoadingTopic(topicId: UInt64) -> Bool { - topicDetailStore?.isLoadingTopic(topicId: topicId) ?? false + topicDetailStore?.snapshot(for: topicId)?.phase == .loading } func isLoadingMoreTopicPosts(topicId: UInt64) -> Bool { - topicDetailStore?.isLoadingMoreTopicPosts(topicId: topicId) ?? false + topicDetailStore?.snapshot(for: topicId)?.isLoadingMore ?? false } func hasMoreTopicPosts(topicId: UInt64) -> Bool { - topicDetailStore?.hasMoreTopicPosts(topicId: topicId) ?? false + topicDetailStore?.snapshot(for: topicId)?.hasMore ?? false } - // MARK: - Topic detail lifecycle - func beginTopicDetailLifecycle(topicId: UInt64, ownerToken: String) { - topicDetailStore?.beginTopicDetailLifecycle(topicId: topicId, ownerToken: ownerToken) - } - - func endTopicDetailLifecycle(topicId: UInt64, ownerToken: String) { - topicDetailStore?.endTopicDetailLifecycle( + topicDetailStore?.open( topicId: topicId, ownerToken: ownerToken, - visibleTopicIDs: currentVisibleTopicIDs() + slug: nil, + targetPostNumber: nil, + bypassCache: false, + forceLoad: false, + trackVisit: true, + allowSuggestedUnreadRoot: topicDetailStore?.snapshot(for: topicId)?.phase != .ready ) } + func endTopicDetailLifecycle(topicId: UInt64, ownerToken: String) { + topicDetailStore?.close(topicId: topicId, ownerToken: ownerToken) + } + func retainedTopicDetailIDs(visibleTopicIDs: Set) -> Set { topicDetailStore?.retainedTopicDetailIDs(visibleTopicIDs: visibleTopicIDs) ?? visibleTopicIDs @@ -852,16 +864,13 @@ final class FireAppViewModel: ObservableObject { // MARK: - Topic detail MessageBus subscription func maintainTopicDetailSubscription(topicId: UInt64, ownerToken: String) async { - await topicDetailStore?.maintainTopicDetailSubscription( - topicId: topicId, - ownerToken: ownerToken - ) + _ = (topicId, ownerToken) } // MARK: - Write interactions func isSubmittingReply(topicId: UInt64) -> Bool { - topicDetailStore?.isSubmittingReply(topicId: topicId) ?? false + topicDetailStore?.snapshot(for: topicId)?.composer.isSubmitting ?? false } func isMutatingPost(postId: UInt64) -> Bool { @@ -930,7 +939,8 @@ final class FireAppViewModel: ObservableObject { func submitReply( topicId: UInt64, raw: String, - replyToPostNumber: UInt32? + replyToPostNumber: UInt32?, + scrollToCreated: Bool = false ) async throws { guard let topicDetailStore else { throw FireTopicInteractionError.unavailable @@ -938,7 +948,8 @@ final class FireAppViewModel: ObservableObject { try await topicDetailStore.submitReply( topicId: topicId, raw: raw, - replyToPostNumber: replyToPostNumber + replyToPostNumber: replyToPostNumber, + scrollToCreated: scrollToCreated ) } @@ -1051,8 +1062,13 @@ final class FireAppViewModel: ObservableObject { ) } await syncSessionSnapshotIfAvailable(from: sessionStore) + try await topicDetailStore?.updateTopic( + topicId: topicID, + title: trimmedTitle, + categoryId: categoryID, + tags: tags + ) await refreshHomeFeedIfPossible(force: true) - await topicDetailStore?.refreshTopicDetailAfterMutation(topicId: topicID) } catch { _ = await handleInteractionError(error) throw error @@ -1069,16 +1085,17 @@ final class FireAppViewModel: ObservableObject { postID: UInt64, raw: String, editReason: String? = nil - ) async throws -> TopicPostState { + ) async throws { guard let topicDetailStore else { throw FireTopicInteractionError.unavailable } - return try await topicDetailStore.updatePost( - topicID: topicID, - postID: postID, + try await topicDetailStore.updatePost( + topicId: topicID, + postId: postID, raw: raw, editReason: editReason ) + await refreshHomeFeedIfPossible(force: false) } func fetchDrafts( @@ -1218,7 +1235,6 @@ final class FireAppViewModel: ObservableObject { messageBusStartRetryCount = 0 notificationStore?.cancelScheduledRefresh() homeFeedStore?.handleMessageBusStopped() - topicDetailStore?.handleMessageBusStopped() clearMessageBusError() guard isMessageBusActive else { return } messageBusCoordinator = nil @@ -1233,7 +1249,7 @@ final class FireAppViewModel: ObservableObject { homeFeedStore?.handleTopicListMessageBusEvent(event) case .topicDetail, .topicReaction, .presence: - topicDetailStore?.handleMessageBusEvent(event) + break case .notification: notificationStore?.scheduleStateRefresh() @@ -1259,11 +1275,11 @@ final class FireAppViewModel: ObservableObject { } func beginTopicReplyPresence(topicId: UInt64) { - topicDetailStore?.beginTopicReplyPresence(topicId: topicId) + topicDetailStore?.beginReplyTyping(topicId: topicId) } func endTopicReplyPresence(topicId: UInt64) async { - await topicDetailStore?.endTopicReplyPresence(topicId: topicId) + topicDetailStore?.endReplyTyping(topicId: topicId) } // MARK: - Private helpers @@ -1344,6 +1360,19 @@ final class FireAppViewModel: ObservableObject { } homeFeedStore?.applySession(session) topicDetailStore?.applySession(session) + if let request = session.readPathLoginRequest, + request.generation != lastReadPathLoginGeneration { + lastReadPathLoginGeneration = request.generation + let operation = request.operation + let recovered = await attemptHostCookieResyncRecovery(operation: operation) + let succeeded = recovered || await attemptMidSessionHeadlessReauth(operation: operation) + if let sessionStore = currentSessionStore() { + try? sessionStore.completeReadPathLogin( + generation: request.generation, + succeeded: succeeded + ) + } + } let isAuthenticated = session.readiness.canReadAuthenticatedApi if wasAuthenticated && !isAuthenticated { @@ -2101,9 +2130,7 @@ final class FireAppViewModel: ObservableObject { } func pruneTopicDetailState(retainingVisibleTopicIDs visibleTopicIDs: Set) { - topicDetailStore?.pruneInactiveTopicDetailState( - retainingVisibleTopicIDs: visibleTopicIDs - ) + _ = visibleTopicIDs } func currentVisibleTopicIDs() -> Set { diff --git a/native/ios-app/App/Views/Composer/FireComposerView.swift b/native/ios-app/App/Views/Composer/FireComposerView.swift index 87cba2b5..1d4647de 100644 --- a/native/ios-app/App/Views/Composer/FireComposerView.swift +++ b/native/ios-app/App/Views/Composer/FireComposerView.swift @@ -715,6 +715,7 @@ final class FireComposerViewController: UIViewController { private let initialTags: [String] private let onTopicCreated: ((UInt64) -> Void)? private let onReplySubmitted: (() -> Void)? + private let scrollToCreatedReply: Bool private let onPrivateMessageCreated: ((UInt64, String) -> Void)? private let onSubmissionNotice: ((String) -> Void)? @@ -798,7 +799,8 @@ final class FireComposerViewController: UIViewController { onTopicCreated: ((UInt64) -> Void)? = nil, onReplySubmitted: (() -> Void)? = nil, onPrivateMessageCreated: ((UInt64, String) -> Void)? = nil, - onSubmissionNotice: ((String) -> Void)? = nil + onSubmissionNotice: ((String) -> Void)? = nil, + scrollToCreatedReply: Bool = false ) { self.viewModel = viewModel self.route = route @@ -808,6 +810,7 @@ final class FireComposerViewController: UIViewController { self.initialTags = initialTags self.onTopicCreated = onTopicCreated self.onReplySubmitted = onReplySubmitted + self.scrollToCreatedReply = scrollToCreatedReply self.onPrivateMessageCreated = onPrivateMessageCreated self.onSubmissionNotice = onSubmissionNotice super.init(nibName: nil, bundle: nil) @@ -2015,7 +2018,8 @@ final class FireComposerViewController: UIViewController { try await viewModel.submitReply( topicId: topicID, raw: trimmedBody, - replyToPostNumber: replyToPostNumber + replyToPostNumber: replyToPostNumber, + scrollToCreated: scrollToCreatedReply ) try? await viewModel.deleteDraft(draftKey: route.draftKey, sequence: draftSequence) draftSequence = 0 diff --git a/native/ios-app/App/Views/Profile/FireFollowListViewController.swift b/native/ios-app/App/Views/Profile/FireFollowListViewController.swift index 57729f3c..71c8b592 100644 --- a/native/ios-app/App/Views/Profile/FireFollowListViewController.swift +++ b/native/ios-app/App/Views/Profile/FireFollowListViewController.swift @@ -428,7 +428,7 @@ struct FireFollowListControllerHost: UIViewControllerRepresentable { self.viewModel = viewModel self.username = username self.kind = kind - self.topicDetailStore = FireTopicDetailStore(appViewModel: viewModel) + self.topicDetailStore = viewModel.topicDetailStore ?? FireTopicDetailStore(appViewModel: viewModel) } func makeUIViewController(context: Context) -> FireFollowListViewController { diff --git a/native/ios-app/App/Views/Profile/FireProfileActivityTimelineView.swift b/native/ios-app/App/Views/Profile/FireProfileActivityTimelineView.swift index 6439fd29..4b1b5dba 100644 --- a/native/ios-app/App/Views/Profile/FireProfileActivityTimelineView.swift +++ b/native/ios-app/App/Views/Profile/FireProfileActivityTimelineView.swift @@ -17,7 +17,7 @@ struct FireProfileActivityTimelineView: View { ) { self.viewModel = viewModel self.profileViewModel = profileViewModel - self.topicDetailStore = topicDetailStore ?? FireTopicDetailStore(appViewModel: viewModel) + self.topicDetailStore = topicDetailStore ?? viewModel.topicDetailStore ?? FireTopicDetailStore(appViewModel: viewModel) } var body: some View { diff --git a/native/ios-app/App/Views/Profile/FireProfileView.swift b/native/ios-app/App/Views/Profile/FireProfileView.swift index a78f976a..a692a054 100644 --- a/native/ios-app/App/Views/Profile/FireProfileView.swift +++ b/native/ios-app/App/Views/Profile/FireProfileView.swift @@ -636,7 +636,7 @@ struct FireProfileView: View { FireAppRouteControllerFactory.presentSecondaryRoute( route, viewModel: viewModel, - topicDetailStore: FireTopicDetailStore(appViewModel: viewModel) + topicDetailStore: viewModel.topicDetailStore ?? FireTopicDetailStore(appViewModel: viewModel) ) return } diff --git a/native/ios-app/App/Views/Profile/FirePublicProfileView.swift b/native/ios-app/App/Views/Profile/FirePublicProfileView.swift index 0ab7f690..bbd687ac 100644 --- a/native/ios-app/App/Views/Profile/FirePublicProfileView.swift +++ b/native/ios-app/App/Views/Profile/FirePublicProfileView.swift @@ -467,7 +467,7 @@ struct FirePublicProfileView: View { FireAppRouteControllerFactory.presentSecondaryRoute( route, viewModel: viewModel, - topicDetailStore: FireTopicDetailStore(appViewModel: viewModel) + topicDetailStore: viewModel.topicDetailStore ?? FireTopicDetailStore(appViewModel: viewModel) ) return } diff --git a/native/ios-app/Sources/FireAppSession/FireSessionStore.swift b/native/ios-app/Sources/FireAppSession/FireSessionStore.swift index af86af2f..73c0dfb7 100644 --- a/native/ios-app/Sources/FireAppSession/FireSessionStore.swift +++ b/native/ios-app/Sources/FireAppSession/FireSessionStore.swift @@ -113,6 +113,25 @@ public actor FireSessionStore { self.lastPersistedAuthCookieRevision = persistenceState.authCookieRevision } + public func completeReadPathLogin(generation: UInt64, succeeded: Bool) throws { + try core.session().completeReadPathLogin(generation: generation, succeeded: succeeded) + } + + public func cancelTopicDetailHttp() { + try? core.topics().cancelTopicDetailHttp() + } + + public func closeAllTopicDetailSessions() { + try? core.topics().closeAllTopicDetailSessions() + } + + public func openTopicDetail( + request: TopicDetailOpenRequestState, + observer: TopicDetailObserver + ) throws -> TopicDetailSessionHandle { + try core.topics().openTopicDetail(request: request, observer: observer) + } + public func snapshot() throws -> SessionState { try core.session().snapshot() } @@ -1001,30 +1020,6 @@ public actor FireSessionStore { ) } - public func fetchTopicDetailSourceSnapshot( - query: TopicDetailSourceQueryState - ) async throws -> TopicDetailSourceSnapshotState { - try await runPersistingSessionChanges { - try await core.topics().fetchTopicDetailSourceSnapshot(query: query) - } - } - - public func fetchTopicDetailPage( - query: TopicDetailSourceQueryState - ) async throws -> TopicDetailPageState { - try await runPersistingSessionChanges { - try await core.topics().fetchTopicDetailPage(query: query) - } - } - - public func loadMoreTopicPosts( - query: LoadMoreTopicPostsQueryState - ) async throws -> TopicLoadMoreOutcomeState { - try await runPersistingSessionChanges { - try await core.topics().loadMoreTopicPosts(query: query) - } - } - public func fetchTopicPosts(topicID: UInt64, postIDs: [UInt64]) async throws -> [TopicPostState] { try await runPersistingSessionChanges { try await core.topics().fetchTopicPosts(topicId: topicID, postIds: postIDs) diff --git a/native/ios-app/Tests/Unit/FireListPaginationAndUpdateTests.swift b/native/ios-app/Tests/Unit/FireListPaginationAndUpdateTests.swift index c97f0806..491947fb 100644 --- a/native/ios-app/Tests/Unit/FireListPaginationAndUpdateTests.swift +++ b/native/ios-app/Tests/Unit/FireListPaginationAndUpdateTests.swift @@ -114,11 +114,8 @@ final class FireListPaginationAndUpdateTests: XCTestCase { } func testTopicDetailShouldLoadMoreNearTrailingThreshold() { - XCTAssertTrue(fireTopicDetailShouldLoadMore(itemCount: 20, visibleMaxItem: 15)) - XCTAssertTrue(fireTopicDetailShouldLoadMore(itemCount: 20, visibleMaxItem: 16)) - XCTAssertFalse(fireTopicDetailShouldLoadMore(itemCount: 20, visibleMaxItem: 14)) - XCTAssertFalse(fireTopicDetailShouldLoadMore(itemCount: 20, visibleMaxItem: 13)) - XCTAssertFalse(fireTopicDetailShouldLoadMore(itemCount: 20, visibleMaxItem: nil)) + XCTAssertTrue(fireTopicDetailShouldEvaluatePagination(forceLoadMoreEvaluation: true, isScrollInteractionActive: false)) + XCTAssertFalse(fireTopicDetailShouldEvaluatePagination(forceLoadMoreEvaluation: false, isScrollInteractionActive: false)) } func testTopicDetailPaginationSkipsProgrammaticScrollEvaluation() { diff --git a/native/ios-app/Tests/Unit/FireSessionStoreTests.swift b/native/ios-app/Tests/Unit/FireSessionStoreTests.swift index 2c82011f..674ade5d 100644 --- a/native/ios-app/Tests/Unit/FireSessionStoreTests.swift +++ b/native/ios-app/Tests/Unit/FireSessionStoreTests.swift @@ -167,7 +167,8 @@ final class FireSessionStoreTests: XCTestCase { hasLoginSession: true, browserUserAgent: nil, profileDisplayName: "alice", - loginPhaseLabel: csrfToken == nil ? "账号信息同步中" : "已就绪" + loginPhaseLabel: csrfToken == nil ? "账号信息同步中" : "已就绪", + readPathLoginRequest: nil ) } } diff --git a/native/ios-app/Tests/Unit/FireTopicDetailRuntimeTests.swift b/native/ios-app/Tests/Unit/FireTopicDetailRuntimeTests.swift index d235aab2..b449554b 100644 --- a/native/ios-app/Tests/Unit/FireTopicDetailRuntimeTests.swift +++ b/native/ios-app/Tests/Unit/FireTopicDetailRuntimeTests.swift @@ -985,6 +985,7 @@ final class FireTopicDetailRuntimeTests: XCTestCase { currentUsername: nil, row: makeTopicRow(), baseURLString: "https://linux.do", + snapshot: nil, detail: detail, renderState: renderState, pendingScrollTarget: pendingScrollTarget, diff --git a/native/ios-app/Tests/Unit/FireTopicDetailStoreTests.swift b/native/ios-app/Tests/Unit/FireTopicDetailStoreTests.swift index 5f759b93..dc79aa83 100644 --- a/native/ios-app/Tests/Unit/FireTopicDetailStoreTests.swift +++ b/native/ios-app/Tests/Unit/FireTopicDetailStoreTests.swift @@ -12,1098 +12,4 @@ final class FireTopicDetailStoreTests: XCTestCase { XCTAssertEqual(window.activeAnchorPostNumber, 88) } - - func testClearingTransientAnchorPreservesWindowShape() { - let window = FireTopicDetailWindowState( - anchorPostNumber: 88, - requestedRange: 40..<70, - loadedIndices: IndexSet(integersIn: 42...50), - loadedPostNumbers: Set([41, 42, 43]), - exhaustedPostIDs: Set([9001]), - pendingScrollTarget: 88 - ) - - let cleared = window.clearingTransientAnchor() - - XCTAssertNil(cleared.anchorPostNumber) - XCTAssertNil(cleared.pendingScrollTarget) - XCTAssertNil(cleared.activeAnchorPostNumber) - XCTAssertEqual(cleared.requestedRange, 40..<70) - XCTAssertEqual(cleared.loadedIndices, IndexSet(integersIn: 42...50)) - XCTAssertEqual(cleared.loadedPostNumbers, Set([41, 42, 43])) - XCTAssertEqual(cleared.exhaustedPostIDs, Set([9001])) - } - - func testInitialRequestedRangeCentersOnAnchorAndIncludesLoadedSpan() { - let range = FireTopicDetailStore.initialRequestedRange( - totalCount: 120, - anchorIndex: 60, - loadedIndices: IndexSet(integersIn: 58...62) - ) - - XCTAssertTrue(range.contains(60)) - XCTAssertLessThanOrEqual(range.lowerBound, 58) - XCTAssertGreaterThanOrEqual(range.upperBound, 63) - XCTAssertGreaterThanOrEqual(range.upperBound - range.lowerBound, 30) - } - - func testInitialRequestedRangeFallsBackToLeadingPageWithoutAnchor() { - let range = FireTopicDetailStore.initialRequestedRange( - totalCount: 120, - anchorIndex: nil, - loadedIndices: IndexSet() - ) - - XCTAssertEqual(range, 0..<30) - } - - func testExpandedRequestedRangeGrowsForwardAroundAnchor() { - let range = FireTopicDetailStore.expandedRequestedRange( - current: 45..<75, - totalCount: 200, - expandBackward: false, - expandForward: true, - anchorIndex: 60 - ) - - XCTAssertEqual(range, 45..<135) - } - - func testBoundedRequestedRangeKeepsAnchorInsideWindowCap() { - let range = FireTopicDetailStore.boundedRequestedRange( - lowerBound: 0, - upperBound: 260, - totalCount: 400, - anchorIndex: 180 - ) - - XCTAssertEqual(range.upperBound - range.lowerBound, FireTopicDetailWindowState.maxWindowSize) - XCTAssertTrue(range.contains(180)) - } - - func testActiveScrollTargetIsNotExhaustedUntilWholeStreamHasBeenCovered() { - let window = FireTopicDetailWindowState( - anchorPostNumber: 88, - requestedRange: 40..<70, - loadedIndices: IndexSet(integersIn: 40..<70), - loadedPostNumbers: Set((40..<70).map(UInt32.init)), - pendingScrollTarget: 88 - ) - let orderedPostIDs = Array(1...120).map(UInt64.init) - let loadedPostIDs = Set(orderedPostIDs[40..<70]) - - XCTAssertFalse(FireTopicDetailStore.scrollTargetIsExhausted( - postNumber: 88, - window: window, - orderedPostIDs: orderedPostIDs, - loadedPostIDs: loadedPostIDs - )) - } - - func testScrollTargetIsExhaustedAfterWholeStreamCoveredWithoutTarget() { - let window = FireTopicDetailWindowState( - anchorPostNumber: 88, - requestedRange: 0..<5, - loadedIndices: IndexSet(integersIn: 0..<5), - loadedPostNumbers: Set([1, 2, 3, 4, 5]), - pendingScrollTarget: 88 - ) - let orderedPostIDs = Array(1...5).map(UInt64.init) - let loadedPostIDs = Set(orderedPostIDs) - - XCTAssertTrue(FireTopicDetailStore.scrollTargetIsExhausted( - postNumber: 88, - window: window, - orderedPostIDs: orderedPostIDs, - loadedPostIDs: loadedPostIDs - )) - } - - func testUnresolvedScrollTargetSearchJumpsNearEstimatedPostNumber() { - let nextRange = FireTopicDetailStore.nextRequestedRangeForUnresolvedTarget( - postNumber: 500, - current: 0..<30, - totalCount: 1_000, - loadedPostNumbersInCurrentRange: Array(1...30).map(UInt32.init) - ) - - XCTAssertNotNil(nextRange) - XCTAssertTrue(nextRange?.contains(499) == true) - } - - func testUnresolvedScrollTargetSearchMovesBackwardWhenWindowIsPastTarget() { - let nextRange = FireTopicDetailStore.nextRequestedRangeForUnresolvedTarget( - postNumber: 500, - current: 480..<510, - totalCount: 1_000, - loadedPostNumbersInCurrentRange: Array(700...729).map(UInt32.init) - ) - - XCTAssertEqual(nextRange, 450..<510) - } - - func testUnresolvedScrollTargetSearchSlidesForwardAtWindowCap() { - let nextRange = FireTopicDetailStore.nextRequestedRangeForUnresolvedTarget( - postNumber: 500, - current: 400..<600, - totalCount: 1_000, - loadedPostNumbersInCurrentRange: Array(300...499).map(UInt32.init) - ) - - XCTAssertEqual(nextRange, 430..<630) - } - - func testRenderStateCoverageRequiresOriginalRowAndAllRenderedPosts() { - let original = TopicPostState( - id: 100, - username: "alice", - name: nil, - avatarTemplate: nil, - authorMetadata: fireEmptyPostAuthorMetadataState(), - presentation: presentCookedHtml(rawHtml: "

Original

", baseUrl: "https://linux.do"), - raw: "Original", - postNumber: 1, - postType: 1, - createdAt: "2026-03-28T10:00:00Z", - updatedAt: "2026-03-28T10:00:00Z", - likeCount: 0, - replyCount: 0, - replyToPostNumber: nil, - replyToUser: nil, - bookmarked: false, - bookmarkId: nil, - bookmarkName: nil, - bookmarkReminderAt: nil, - reactions: [], - currentUserReaction: nil, - boosts: [], - canBoost: false, - polls: [], - acceptedAnswer: false, - canAcceptAnswer: false, - canUnacceptAnswer: false, - canEdit: false, - canDelete: false, - canRecover: false, - hidden: false - ) - let reply = TopicPostState( - id: 200, - username: "bob", - name: nil, - avatarTemplate: nil, - authorMetadata: fireEmptyPostAuthorMetadataState(), - presentation: presentCookedHtml(rawHtml: "

Reply

", baseUrl: "https://linux.do"), - raw: "Reply", - postNumber: 2, - postType: 1, - createdAt: "2026-03-28T10:01:00Z", - updatedAt: "2026-03-28T10:01:00Z", - likeCount: 0, - replyCount: 0, - replyToPostNumber: 1, - replyToUser: nil, - bookmarked: false, - bookmarkId: nil, - bookmarkName: nil, - bookmarkReminderAt: nil, - reactions: [], - currentUserReaction: nil, - boosts: [], - canBoost: false, - polls: [], - acceptedAnswer: false, - canAcceptAnswer: false, - canUnacceptAnswer: false, - canEdit: false, - canDelete: false, - canRecover: false, - hidden: false - ) - let rowInputs = [ - FireTopicTimelineRowInput(postID: original.id, postNumber: 1, replyToPostNumber: nil), - FireTopicTimelineRowInput(postID: reply.id, postNumber: 2, replyToPostNumber: 1), - ] - let renderContent = fireRenderContentFixture("

text

") - let validState = FireTopicDetailRenderState( - originalRow: FirePreparedTopicTimelineRow( - entry: FireTopicTimelineEntry( - postId: original.id, - postNumber: 1, - parentPostNumber: nil, - depth: 0, - isOriginalPost: true - ) - ), - replyRows: [ - FirePreparedTopicTimelineRow( - entry: FireTopicTimelineEntry( - postId: reply.id, - postNumber: 2, - parentPostNumber: 1, - depth: 1, - isOriginalPost: false - ) - ) - ], - contentByPostID: [ - original.id: renderContent, - reply.id: renderContent, - ] - ) - let missingOriginalContent = FireTopicDetailRenderState( - originalRow: validState.originalRow, - replyRows: validState.replyRows, - contentByPostID: [reply.id: renderContent] - ) - - XCTAssertTrue( - FireTopicDetailStore.renderStateCoversRowInputs( - validState, - rowInputs: rowInputs, - originalPostID: original.id - ) - ) - XCTAssertFalse( - FireTopicDetailStore.renderStateCoversRowInputs( - missingOriginalContent, - rowInputs: rowInputs, - originalPostID: original.id - ) - ) - } - - func testNextSourcePageLoadGateAllowsLoadedIdleTopic() { - XCTAssertTrue(FireTopicDetailStore.canStartNextTopicSourcePageLoad( - hasMoreTopicPosts: true, - isLoadingMoreTopicPosts: false, - hasPendingPreloadTask: false, - hasLoadedDetail: true - )) - XCTAssertFalse(FireTopicDetailStore.canStartNextTopicSourcePageLoad( - hasMoreTopicPosts: true, - isLoadingMoreTopicPosts: true, - hasPendingPreloadTask: false, - hasLoadedDetail: true - )) - XCTAssertFalse(FireTopicDetailStore.canStartNextTopicSourcePageLoad( - hasMoreTopicPosts: true, - isLoadingMoreTopicPosts: false, - hasPendingPreloadTask: true, - hasLoadedDetail: true - )) - XCTAssertFalse(FireTopicDetailStore.canStartNextTopicSourcePageLoad( - hasMoreTopicPosts: false, - isLoadingMoreTopicPosts: false, - hasPendingPreloadTask: false, - hasLoadedDetail: true - )) - } - - func testCloudflareRecoveryTopicURLUsesCanonicalTopicHTMLRouteWhenSlugIsKnown() { - let url = FireAppViewModel.cloudflareRecoveryTopicURL( - baseURL: "https://linux.do", - topicId: 42, - topicSlug: "fire-native" - ) - - XCTAssertEqual(url.absoluteString, "https://linux.do/t/fire-native/42") - } - - func testCloudflareRecoveryTopicURLFallsBackToTopicIDHTMLRouteWithoutSlug() { - let url = FireAppViewModel.cloudflareRecoveryTopicURL( - baseURL: "https://linux.do/", - topicId: 42, - topicSlug: " " - ) - - XCTAssertEqual(url.absoluteString, "https://linux.do/t/42") - } - - func testCloudflareRecoveryTopicListURLUsesLatestHTMLRoute() { - let url = FireAppViewModel.cloudflareRecoveryTopicListURL( - baseURL: "https://linux.do/", - query: TopicListQueryState( - kind: .latest, - page: nil, - topicIds: [], - order: nil, - ascending: nil, - categorySlug: nil, - categoryId: nil, - parentCategorySlug: nil, - tag: nil, - additionalTags: [], - matchAllTags: false - ) - ) - - XCTAssertEqual(url.absoluteString, "https://linux.do/latest") - } - - func testCloudflareRecoveryTopicListURLUsesCategoryHTMLRouteWithPage() { - let url = FireAppViewModel.cloudflareRecoveryTopicListURL( - baseURL: "https://linux.do", - query: TopicListQueryState( - kind: .new, - page: 2, - topicIds: [], - order: nil, - ascending: nil, - categorySlug: "rust", - categoryId: 99, - parentCategorySlug: "dev", - tag: nil, - additionalTags: [], - matchAllTags: false - ) - ) - - XCTAssertEqual(url.absoluteString, "https://linux.do/c/dev/rust/99/l/new?page=2") - } - - func testCloudflareRecoveryTopicListURLUsesTagHTMLRoute() { - let url = FireAppViewModel.cloudflareRecoveryTopicListURL( - baseURL: "https://linux.do", - query: TopicListQueryState( - kind: .top, - page: nil, - topicIds: [], - order: nil, - ascending: nil, - categorySlug: nil, - categoryId: nil, - parentCategorySlug: nil, - tag: "swift", - additionalTags: [], - matchAllTags: false - ) - ) - - XCTAssertEqual(url.absoluteString, "https://linux.do/tag/swift/l/top") - } - - func testCloudflareRecoveryTopicListURLUsesLatestForIncrementalTopicIDs() { - let url = FireAppViewModel.cloudflareRecoveryTopicListURL( - baseURL: "https://linux.do", - query: TopicListQueryState( - kind: .new, - page: nil, - topicIds: [1, 2, 3], - order: nil, - ascending: nil, - categorySlug: nil, - categoryId: nil, - parentCategorySlug: nil, - tag: nil, - additionalTags: [], - matchAllTags: false - ) - ) - - XCTAssertEqual(url.absoluteString, "https://linux.do/latest") - } - - func testCloudflareRecoveryTopicListURLPreservesCategoryTagQuery() { - let url = FireAppViewModel.cloudflareRecoveryTopicListURL( - baseURL: "https://linux.do", - query: TopicListQueryState( - kind: .latest, - page: nil, - topicIds: [], - order: nil, - ascending: nil, - categorySlug: "dev", - categoryId: 42, - parentCategorySlug: nil, - tag: "swift", - additionalTags: ["rust"], - matchAllTags: true - ) - ) - - XCTAssertEqual( - url.absoluteString, - "https://linux.do/c/dev/42/l/latest?tags%5B%5D=swift&tags%5B%5D=rust&match_all_tags=true" - ) - } - - func testCloudflareRecoverySnapshotRequiresNewClearance() { - let initial = FireCloudflareRecoveryCookieSnapshot( - hasAuthCookies: true, - authFingerprint: "auth", - cfClearanceFingerprint: "old" - ) - let unchanged = FireCloudflareRecoveryCookieSnapshot( - hasAuthCookies: true, - authFingerprint: "auth", - cfClearanceFingerprint: "old" - ) - let missing = FireCloudflareRecoveryCookieSnapshot( - hasAuthCookies: true, - authFingerprint: "auth", - cfClearanceFingerprint: nil - ) - let rotated = FireCloudflareRecoveryCookieSnapshot( - hasAuthCookies: true, - authFingerprint: "auth", - cfClearanceFingerprint: "new" - ) - - XCTAssertTrue(initial.hasCloudflareClearance) - XCTAssertFalse(unchanged.hasNewCloudflareClearance(comparedTo: initial)) - XCTAssertFalse(missing.hasNewCloudflareClearance(comparedTo: initial)) - XCTAssertTrue(rotated.hasNewCloudflareClearance(comparedTo: initial)) - } - - func testCloudflareRecoverySnapshotAcceptsFirstClearanceWhenBaselineHasNone() { - let initial = FireCloudflareRecoveryCookieSnapshot( - hasAuthCookies: true, - authFingerprint: "auth", - cfClearanceFingerprint: nil - ) - let current = FireCloudflareRecoveryCookieSnapshot( - hasAuthCookies: true, - authFingerprint: "auth", - cfClearanceFingerprint: "new" - ) - - XCTAssertFalse(initial.hasCloudflareClearance) - XCTAssertTrue(current.hasNewCloudflareClearance(comparedTo: initial)) - } - - func testHydrateRequestedRangeFillsAnchorWindowBeforeFirstRender() async throws { - let initialDetail = makeTopicDetail( - posts: [ - makePost(postNumber: 3, replyToPostNumber: 2, username: "reply-a"), - makePost(postNumber: 4, replyToPostNumber: 3, username: "reply-b"), - ], - stream: [1, 2, 3, 4, 5, 6] - ) - let window = FireTopicDetailWindowState( - anchorPostNumber: 4, - requestedRange: 1..<5, - loadedIndices: IndexSet(integersIn: 2..<4), - loadedPostNumbers: [3, 4], - pendingScrollTarget: 4 - ) - let requestedBatches = RequestedBatchRecorder() - - let hydrated = try await FireTopicDetailStore.hydrateRequestedRange( - detail: initialDetail, - window: window - ) { postIDs in - await requestedBatches.append(postIDs) - return [ - self.makePost(postNumber: 2, replyToPostNumber: 1, username: "reply-root"), - self.makePost(postNumber: 5, replyToPostNumber: 4, username: "reply-c"), - ] - } - let capturedBatches = await requestedBatches.snapshot() - - XCTAssertEqual(capturedBatches, [[2, 5]]) - XCTAssertEqual( - hydrated.detail.postStream.posts.map(\.postNumber), - [2, 3, 4, 5] - ) - XCTAssertTrue(hydrated.exhaustedPostIDs.isEmpty) - } - - @MainActor - func testCompleteLoginUsesAtomicFinalizationWithoutEagerCsrfRefresh() async throws { - let captured = FireCapturedLoginState( - currentURL: "https://linux.do/", - username: "alice", - csrfToken: nil, - homeHTML: "", - browserUserAgent: "FireTests/1.0", - cookies: [ - PlatformCookieState( - name: "_t", - value: "token", - domain: "linux.do", - path: "/", - expiresAtUnixMs: nil, - sameSite: nil - ) - ] - ) - let store = MockLoginSessionStore( - finalizationResult: makeSessionState(csrfToken: nil), - bootstrapResult: makeSessionState(csrfToken: nil), - ) - let coordinator = FireWebViewLoginCoordinator(loginSessionStore: store) - - let finalState = try await coordinator.completeLogin(captured) - let calls = await store.callsSnapshot() - let finalizedCapture = await store.finalizedCaptureSnapshot() - - XCTAssertEqual( - calls, - [.finalizeLoginFromWebView, .finalizeLoginReady] - ) - XCTAssertEqual(finalizedCapture, captured) - XCTAssertNil(finalState.cookies.csrfToken) - XCTAssertFalse(finalState.readiness.hasCsrfToken) - XCTAssertFalse(finalState.readiness.canWriteAuthenticatedApi) - XCTAssertTrue(finalState.readiness.canReadAuthenticatedApi) - } - - @MainActor - func testAuthoritativePlatformCookieApplySkipsPartialBrowserBatch() async throws { - let currentState = makeSessionState(csrfToken: "csrf-token") - let store = MockLoginSessionStore( - finalizationResult: makeSessionState(csrfToken: nil), - bootstrapResult: currentState, - currentSnapshot: currentState - ) - let coordinator = FireWebViewLoginCoordinator(loginSessionStore: store) - - let state = try await coordinator.applyPlatformCookiesIfAuthoritative([ - PlatformCookieState( - name: "cf_clearance", - value: "clearance", - domain: "linux.do", - path: "/", - expiresAtUnixMs: nil, - sameSite: nil - ) - ]) - let calls = await store.callsSnapshot() - let appliedCookies = await store.appliedPlatformCookiesSnapshot() - - XCTAssertEqual(calls, [MockLoginSessionStore.Call.currentSessionSnapshot]) - XCTAssertEqual(state, currentState) - XCTAssertTrue(appliedCookies.isEmpty) - } - - @MainActor - func testCloudflareCompletionUsesChallengeMergePathForPartialBrowserBatch() async throws { - let finalState = makeSessionState(csrfToken: "csrf-token") - let store = MockLoginSessionStore( - finalizationResult: finalState, - bootstrapResult: finalState - ) - let coordinator = FireWebViewLoginCoordinator(loginSessionStore: store) - let cookies = [ - PlatformCookieState( - name: "cf_clearance", - value: "fresh-clearance", - domain: "linux.do", - path: "/", - expiresAtUnixMs: nil, - sameSite: nil - ) - ] - - let state = try await coordinator.completeCloudflareChallenge( - cookies: cookies, - freshCfClearance: "fresh-clearance", - browserUserAgent: "FireTests/1.0" - ) - let calls = await store.callsSnapshot() - let appliedCookies = await store.appliedPlatformCookiesSnapshot() - let challengeCookies = await store.completedCloudflareChallengeCookiesSnapshot() - - XCTAssertEqual(calls, [.completeCloudflareChallenge]) - XCTAssertEqual(state, finalState) - XCTAssertTrue(appliedCookies.isEmpty) - XCTAssertEqual(challengeCookies, cookies) - } - - @MainActor - func testCompleteLoginKeepsCookiesWhenLoginReadyBootstrapChallenges() async throws { - let captured = FireCapturedLoginState( - currentURL: "https://linux.do/", - username: "alice", - csrfToken: nil, - homeHTML: "", - browserUserAgent: "FireTests/1.0", - cookies: [] - ) - let partialState = SessionState( - cookies: CookieState( - tToken: "token", - forumSession: "forum", - cfClearance: "clearance", - csrfToken: nil, - platformCookies: [], - canonicalCookies: [] - ), - bootstrap: BootstrapState( - baseUrl: "https://linux.do", - discourseBaseUri: "/", - sharedSessionKey: nil, - currentUsername: "alice", - currentUserId: 1, - notificationChannelPosition: nil, - longPollingBaseUrl: nil, - turnstileSitekey: nil, - topicTrackingStateMeta: nil, - preloadedJson: nil, - hasPreloadedData: false, - hasSiteMetadata: false, - topTags: [], - canTagTopics: false, - categories: [], - hasSiteSettings: false, - enabledReactionIds: [], - minPostLength: 1, - minTopicTitleLength: 15, - minFirstPostLength: 20, - minPersonalMessageTitleLength: 2, - minPersonalMessagePostLength: 10, - defaultComposerCategory: nil - ), - readiness: SessionReadinessState( - hasLoginCookie: true, - hasForumSession: true, - hasCloudflareClearance: true, - hasCsrfToken: false, - hasCurrentUser: true, - hasPreloadedData: false, - hasSharedSessionKey: false, - canReadAuthenticatedApi: true, - canWriteAuthenticatedApi: false, - canOpenMessageBus: false - ), - loginPhase: .bootstrapCaptured, - hasLoginSession: true, - browserUserAgent: "FireTests/1.0", - profileDisplayName: "alice", - loginPhaseLabel: "账号信息同步中" - ) - let store = MockLoginSessionStore( - finalizationResult: partialState, - bootstrapResult: partialState, - bootstrapError: FireUniFfiError.CloudflareChallenge(reason: "required") - ) - let coordinator = FireWebViewLoginCoordinator(loginSessionStore: store) - - // fluxdo LoginReady finally: trusted cookies still enter home even if - // bootstrap/CF refresh is incomplete. - let finalState = try await coordinator.completeLogin(captured) - let calls = await store.callsSnapshot() - - XCTAssertEqual( - calls, - [ - .finalizeLoginFromWebView, - .finalizeLoginReady, - ] - ) - XCTAssertEqual(finalState.cookies.tToken, "token") - XCTAssertTrue(finalState.readiness.canReadAuthenticatedApi) - } - - func testReplyContextRowsAppendMissingNestedRepliesWithDepth() { - let root = makePost(postNumber: 2, replyToPostNumber: 1, username: "root") - let sibling = makePost(postNumber: 5, replyToPostNumber: 1, username: "sibling") - let existingRows = [ - TopicTreeRowState( - postId: root.id, - postNumber: root.postNumber, - rootPostNumber: 1, - parentPostNumber: 1, - depth: 1, - preorderIndex: 1, - hasChildren: false, - descendantCount: 0, - siblingIndex: 0, - isLastSibling: false - ), - TopicTreeRowState( - postId: sibling.id, - postNumber: sibling.postNumber, - rootPostNumber: 1, - parentPostNumber: 1, - depth: 1, - preorderIndex: 2, - hasChildren: false, - descendantCount: 0, - siblingIndex: 1, - isLastSibling: true - ), - ] - let child = makePost(postNumber: 3, replyToPostNumber: 2, username: "child") - let grandchild = makePost(postNumber: 4, replyToPostNumber: 3, username: "grandchild") - - let merged = FireTopicDetailStore.mergeReplyContextTreeRows( - existingRows: existingRows, - bodyPostNumber: 1, - rootPost: root, - contextPosts: [grandchild, child] - ) - - XCTAssertEqual(merged.map(\.postNumber), [2, 5, 3, 4]) - XCTAssertEqual(merged.map { $0.depth }, [1, 1, 2, 3] as [UInt16]) - XCTAssertEqual(merged.suffix(2).map { $0.parentPostNumber }, [2, 3] as [UInt32?]) - XCTAssertEqual(merged.suffix(2).map { $0.rootPostNumber }, [1, 1] as [UInt32]) - } - - private func makeTreeRow( - postNumber: UInt32, - parentPostNumber: UInt32?, - depth: UInt16, - username: String - ) -> TopicTreeRowState { - let post = makePost( - postNumber: postNumber, - replyToPostNumber: parentPostNumber, - username: username - ) - return TopicTreeRowState( - postId: post.id, - postNumber: post.postNumber, - rootPostNumber: 1, - parentPostNumber: parentPostNumber, - depth: depth, - preorderIndex: postNumber - 1, - hasChildren: false, - descendantCount: 0, - siblingIndex: 0, - isLastSibling: true - ) - } - - private func makePost( - postNumber: UInt32, - replyToPostNumber: UInt32?, - username: String - ) -> TopicPostState { - let cooked = "

\(username)

" - return TopicPostState( - id: UInt64(postNumber), - username: username, - name: nil, - avatarTemplate: nil, - authorMetadata: fireEmptyPostAuthorMetadataState(), - presentation: presentCookedHtml(rawHtml: cooked, baseUrl: "https://linux.do"), - raw: nil, - postNumber: postNumber, - postType: 1, - createdAt: "2026-03-28T10:00:00Z", - updatedAt: "2026-03-28T10:00:00Z", - likeCount: 0, - replyCount: 0, - replyToPostNumber: replyToPostNumber, - replyToUser: nil, - bookmarked: false, - bookmarkId: nil, - bookmarkName: nil, - bookmarkReminderAt: nil, - reactions: [], - currentUserReaction: nil, - boosts: [], - canBoost: false, - polls: [], - acceptedAnswer: false, - canAcceptAnswer: false, - canUnacceptAnswer: false, - canEdit: false, - canDelete: false, - canRecover: false, - hidden: false - ) - } - - private func makeTopicDetail( - posts: [TopicPostState], - stream: [UInt64] - ) -> TopicDetailState { - TopicDetailState( - id: 42, - messageBusLastId: nil, - title: "Fire Native", - slug: "fire-native", - postsCount: UInt32(max(stream.count, posts.count)), - replyCount: UInt32(max(max(stream.count, posts.count) - 1, 0)), - categoryId: 7, - tags: [], - views: 128, - likeCount: 9, - createdAt: "2026-03-28T10:00:00Z", - highestPostNumber: UInt32(max(stream.count, posts.count)), - lastReadPostNumber: nil, - bookmarks: [], - bookmarked: false, - bookmarkId: nil, - bookmarkName: nil, - bookmarkReminderAt: nil, - acceptedAnswer: false, - hasAcceptedAnswer: false, - canVote: false, - voteCount: 0, - userVoted: false, - summarizable: false, - hasCachedSummary: false, - hasSummary: false, - archetype: "regular", - postStream: TopicPostStreamState(posts: posts, stream: stream), - details: TopicDetailMetaState( - notificationLevel: nil, - canEdit: false, - createdBy: nil, - participants: [] - ) - ) - } - - private func makeSessionState(csrfToken: String?) -> SessionState { - SessionState( - cookies: CookieState( - tToken: "token", - forumSession: "forum", - cfClearance: "clearance", - csrfToken: csrfToken, - platformCookies: [], - canonicalCookies: [] - ), - bootstrap: BootstrapState( - baseUrl: "https://linux.do", - discourseBaseUri: "/", - sharedSessionKey: "shared-session", - currentUsername: "alice", - currentUserId: 1, - notificationChannelPosition: nil, - longPollingBaseUrl: "https://linux.do", - turnstileSitekey: nil, - topicTrackingStateMeta: nil, - preloadedJson: "{\"site\":{}}", - hasPreloadedData: true, - hasSiteMetadata: true, - topTags: [], - canTagTopics: false, - categories: [], - hasSiteSettings: true, - enabledReactionIds: ["heart"], - minPostLength: 1, - minTopicTitleLength: 15, - minFirstPostLength: 20, - minPersonalMessageTitleLength: 2, - minPersonalMessagePostLength: 10, - defaultComposerCategory: nil - ), - readiness: SessionReadinessState( - hasLoginCookie: true, - hasForumSession: true, - hasCloudflareClearance: true, - hasCsrfToken: csrfToken != nil, - hasCurrentUser: true, - hasPreloadedData: true, - hasSharedSessionKey: true, - canReadAuthenticatedApi: true, - canWriteAuthenticatedApi: csrfToken != nil, - canOpenMessageBus: true - ), - loginPhase: .ready, - hasLoginSession: true, - browserUserAgent: nil, - profileDisplayName: "alice", - loginPhaseLabel: csrfToken == nil ? "账号信息同步中" : "已就绪" - ) - } - - func testFeedContentTokenIgnoresPostReactionCounts() { - var liked = makePost(postNumber: 2, replyToPostNumber: 1, username: "bob") - liked.likeCount = 4 - liked.reactions = [ - TopicReactionState(id: "heart", kind: nil, count: 4, canUndo: true) - ] - liked.currentUserReaction = TopicReactionState(id: "heart", kind: nil, count: 1, canUndo: true) - - let idle = makePost(postNumber: 2, replyToPostNumber: 1, username: "bob") - XCTAssertEqual( - FireTopicPostContentToken(post: idle), - FireTopicPostContentToken(post: liked) - ) - } -} - -private actor RequestedBatchRecorder { - private var batches: [[UInt64]] = [] - - func append(_ batch: [UInt64]) { - batches.append(batch) - } - - func snapshot() -> [[UInt64]] { - batches - } -} - -private actor MockLoginSessionStore: FireLoginSessionStoring { - enum Call: Equatable { - case currentSessionSnapshot - case finalizeLoginFromWebView - case finalizeLoginReady - case applyPlatformCookies - case completeCloudflareChallenge - case syncLoginContext - case refreshBootstrapIfNeeded - case refreshCsrfTokenIfNeeded - case logoutLocal - case webViewPrimingPayload - case cookieSweepPlan - case cookieNuclearResetPlan - case commitCookieSweepResult - } - - private let finalizationResult: SessionState - private let bootstrapResult: SessionState - private let csrfResult: SessionState - private let currentSnapshot: SessionState - private let bootstrapError: Error? - private let csrfError: Error? - private var calls: [Call] = [] - private var appliedPlatformCookies: [PlatformCookieState] = [] - private var completedCloudflareChallengeCookies: [PlatformCookieState] = [] - private var finalizedCapture: FireCapturedLoginState? - - init( - finalizationResult: SessionState, - bootstrapResult: SessionState, - csrfResult: SessionState? = nil, - currentSnapshot: SessionState? = nil, - bootstrapError: Error? = nil, - csrfError: Error? = nil - ) { - self.finalizationResult = finalizationResult - self.bootstrapResult = bootstrapResult - self.csrfResult = csrfResult ?? bootstrapResult - self.currentSnapshot = currentSnapshot ?? finalizationResult - self.bootstrapError = bootstrapError - self.csrfError = csrfError - } - - func currentSessionSnapshot() async throws -> SessionState { - calls.append(.currentSessionSnapshot) - return currentSnapshot - } - - func restorePersistedSessionIfAvailable() async throws -> SessionState? { - nil - } - - func finalizeLoginFromWebView( - _ captured: FireCapturedLoginState, - allowLowConfidenceSessionCookies: Bool - ) async throws -> LoginFinalizationResultState { - calls.append(.finalizeLoginFromWebView) - finalizedCapture = captured - return LoginFinalizationResultState( - success: true, - session: finalizationResult, - tTokenVerified: true, - fingerprintWaitNeeded: true - ) - } - - func finalizeLoginReady() async throws -> SessionState { - calls.append(.finalizeLoginReady) - if let bootstrapError { - // Keep login-ready finally semantics: still return cookies even if bootstrap fails. - return finalizationResult - } - return bootstrapResult - } - - func syncLoginContext(_ captured: FireCapturedLoginState) async throws -> SessionState { - calls.append(.syncLoginContext) - return finalizationResult - } - - func refreshBootstrapIfNeeded() async throws -> SessionState { - calls.append(.refreshBootstrapIfNeeded) - if let bootstrapError { - throw bootstrapError - } - return bootstrapResult - } - - func refreshCsrfTokenIfNeeded() async throws -> SessionState { - calls.append(.refreshCsrfTokenIfNeeded) - if let csrfError { - throw csrfError - } - return csrfResult - } - - func logout() async throws -> SessionState { - bootstrapResult - } - - func logoutLocal(preserveCfClearance: Bool) async throws -> SessionState { - calls.append(.logoutLocal) - return bootstrapResult - } - - func applyPlatformCookies(_ cookies: [PlatformCookieState]) async throws -> SessionState { - calls.append(.applyPlatformCookies) - appliedPlatformCookies = cookies - return finalizationResult - } - - func completeCloudflareChallenge( - cookies: [PlatformCookieState], - freshCfClearance: String?, - browserUserAgent: String? - ) async throws -> SessionState { - calls.append(.completeCloudflareChallenge) - completedCloudflareChallengeCookies = cookies - return finalizationResult - } - - func webViewPrimingPayload(targetURL: String?) async throws -> [WebViewCookieActionState] { - calls.append(.webViewPrimingPayload) - return [] - } - - func cookieSweepPlan( - targetURL: String?, - name: String, - webViewCookies: [WebViewCookieInfoState] - ) async throws -> CookieSweepPlanState { - calls.append(.cookieSweepPlan) - return CookieSweepPlanState( - name: name, - intent: .ensureUnique, - actions: [], - selectedWinner: nil - ) - } - - func cookieNuclearResetPlan( - targetURL: String?, - webViewCookies: [WebViewCookieInfoState] - ) async throws -> NuclearResetPlanState { - calls.append(.cookieNuclearResetPlan) - return NuclearResetPlanState(actions: []) - } - - func commitCookieSweepResult( - targetURL: String?, - name: String, - intent: CookieSweepIntentState, - webViewCookies: [WebViewCookieInfoState] - ) async throws -> SessionState { - calls.append(.commitCookieSweepResult) - return finalizationResult - } - - func callsSnapshot() -> [Call] { - calls - } - - func appliedPlatformCookiesSnapshot() -> [PlatformCookieState] { - appliedPlatformCookies - } - - func completedCloudflareChallengeCookiesSnapshot() -> [PlatformCookieState] { - completedCloudflareChallengeCookies - } - - func finalizedCaptureSnapshot() -> FireCapturedLoginState? { - finalizedCapture - } } diff --git a/native/ios-app/Tests/Unit/FireTopicListMessageBusRefreshTests.swift b/native/ios-app/Tests/Unit/FireTopicListMessageBusRefreshTests.swift index b2cedd78..42ab201f 100644 --- a/native/ios-app/Tests/Unit/FireTopicListMessageBusRefreshTests.swift +++ b/native/ios-app/Tests/Unit/FireTopicListMessageBusRefreshTests.swift @@ -171,9 +171,17 @@ final class FireTopicListMessageBusRefreshTests: XCTestCase { @MainActor func testHomeTopicCountPatchOnlyUpdatesMatchingExistingRow() { let row = makeTopicRow(id: 42, activityTimestampUnixMs: 100) - let detail = makeTopicDetail(id: 42, postsCount: 9, replyCount: 8, views: 321) + let patch = TopicHomeRowCountPatchState( + topicId: 42, + postsCount: 9, + replyCount: 8, + views: 321, + lastReadPostNumber: 8, + highestPostNumber: 9, + unread: .stillUnread + ) - let patched = FireHomeFeedStore.patchedTopicRow(row, from: detail) + let patched = FireHomeFeedStore.applyHomeRowCountPatch(row, patch: patch) XCTAssertEqual(patched?.topic.id, 42) XCTAssertEqual(patched?.topic.postsCount, 9) @@ -181,9 +189,9 @@ final class FireTopicListMessageBusRefreshTests: XCTestCase { XCTAssertEqual(patched?.topic.views, 321) XCTAssertEqual(patched?.topic.highestPostNumber, 9) XCTAssertEqual(patched?.topic.lastReadPostNumber, 8) - XCTAssertNil(FireHomeFeedStore.patchedTopicRow( + XCTAssertNil(FireHomeFeedStore.applyHomeRowCountPatch( makeTopicRow(id: 7, activityTimestampUnixMs: 200), - from: detail + patch: patch )) } @@ -195,9 +203,17 @@ final class FireTopicListMessageBusRefreshTests: XCTestCase { row.topic.lastReadPostNumber = 7 row.topic.highestPostNumber = 9 row.hasUnreadPosts = true - let detail = makeTopicDetail(id: 42, postsCount: 9, replyCount: 9, views: 321) + let patch = TopicHomeRowCountPatchState( + topicId: 42, + postsCount: 9, + replyCount: 9, + views: 321, + lastReadPostNumber: 9, + highestPostNumber: 9, + unread: .caughtUp + ) - let patched = FireHomeFeedStore.patchedTopicRow(row, from: detail) + let patched = FireHomeFeedStore.applyHomeRowCountPatch(row, patch: patch) XCTAssertEqual(patched?.topic.lastReadPostNumber, 9) XCTAssertEqual(patched?.topic.highestPostNumber, 9) diff --git a/native/ios-app/Tests/Unit/FireTopicPresentationTests.swift b/native/ios-app/Tests/Unit/FireTopicPresentationTests.swift index f7b020b7..5bf64533 100644 --- a/native/ios-app/Tests/Unit/FireTopicPresentationTests.swift +++ b/native/ios-app/Tests/Unit/FireTopicPresentationTests.swift @@ -908,7 +908,8 @@ final class FireTopicPresentationTests: XCTestCase { hasLoginSession: true, browserUserAgent: nil, profileDisplayName: "会话已连接", - loginPhaseLabel: "账号信息同步中" + loginPhaseLabel: "账号信息同步中", + readPathLoginRequest: nil ) XCTAssertEqual(session.profileDisplayName, "会话已连接") @@ -946,7 +947,8 @@ final class FireTopicPresentationTests: XCTestCase { hasLoginSession: true, browserUserAgent: nil, profileDisplayName: "alice", - loginPhaseLabel: "已就绪" + loginPhaseLabel: "已就绪", + readPathLoginRequest: nil ) XCTAssertEqual(session.profileDisplayName, "alice") diff --git a/rust/crates/fire-core/src/core/messagebus.rs b/rust/crates/fire-core/src/core/messagebus.rs deleted file mode 100644 index 20af231b..00000000 --- a/rust/crates/fire-core/src/core/messagebus.rs +++ /dev/null @@ -1,1544 +0,0 @@ -use std::{ - collections::{BTreeMap, HashMap}, - sync::{ - atomic::{AtomicU64, Ordering}, - Arc, Mutex, RwLock, - }, - time::{Duration, SystemTime, UNIX_EPOCH}, -}; - -use fire_models::{ - BootstrapArtifacts, MessageBusClientMode, MessageBusEvent, MessageBusEventKind, - MessageBusSubscription, MessageBusSubscriptionScope, NotificationAlert, - NotificationAlertPollResult, SessionSnapshot, TopicListKind, -}; -use http::{Method, Request, Response}; -use http_body_util::BodyExt; -use openwire::{RequestBody, ResponseBody, WireErrorKind}; -use serde_json::Value; -use tokio::{ - runtime::Handle, - sync::{mpsc::UnboundedSender, watch}, - task::JoinHandle, - time::{sleep, Instant}, -}; -use tracing::{debug, info, warn}; -use url::{form_urlencoded::Serializer, Url}; - -use super::{ - network::{ - classify_http_status_error, header_value, request_origin, take_trace_cancellation_guard, - FireCallProfile, FireNetworkLayer, FireRequestEpoch, FireRequestProfile, TracedRequest, - }, - notifications::{merge_notification_event_data, FireNotificationRuntime}, - presence::{ - clear_topic_presence_snapshot, merge_topic_presence_event_data, FireTopicPresenceRuntime, - }, - FireCore, FireSessionRuntimeState, -}; -use crate::{ - diagnostics::FireDiagnosticsStore, - error::FireCoreError, - json_helpers::{boolean, integer_i64, integer_u32, positive_u64, scalar_string}, - sync_utils::read_rwlock, -}; - -const MESSAGE_BUS_OPERATION: &str = "message bus poll"; -const INITIAL_MESSAGE_ID: i64 = -1; -const MAX_BACKOFF_DELAY: Duration = Duration::from_secs(15); -const MESSAGE_BUS_MIN_RESTART_INTERVAL: Duration = Duration::from_millis(150); -const BOOTSTRAP_TRACKING_OWNER_TOKEN: &str = "__bootstrap_tracking__"; -const BOOTSTRAP_NOTIFICATION_OWNER_TOKEN: &str = "__bootstrap_notification__"; -const BOOTSTRAP_LOGOUT_OWNER_TOKEN: &str = "__bootstrap_logout__"; - -static FOREGROUND_CLIENT_COUNTER: AtomicU64 = AtomicU64::new(1); -static MESSAGE_BUS_SEQUENCE_COUNTER: AtomicU64 = AtomicU64::new(1); - -#[derive(Default)] -pub(crate) struct FireMessageBusRuntime { - foreground_client_id: Option, - active_client_id: Option, - active_mode: Option, - runtime_handle: Option, - event_sender: Option>, - subscriptions: BTreeMap, - subscription_revision: u64, - subscription_updates: Option>, - poll_task_token: u64, - poll_task: Option>, -} - -#[derive(Debug, Clone)] -struct RuntimeSubscription { - last_message_id: i64, - owners: BTreeMap, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -struct RuntimeSubscriptionOwner { - scope: MessageBusSubscriptionScope, -} - -#[derive(Clone)] -struct MessageBusPollContext { - core: FireCore, - base_url: Url, - network: FireNetworkLayer, - diagnostics: Arc, - session: Arc>, - runtime: Arc>, - notifications: Arc>, - topic_presence: Arc>, - event_sender: UnboundedSender, - client_id: String, - mode: MessageBusClientMode, - task_token: u64, -} - -enum PollIterationResult { - Continue, - Stop, - Restart, -} - -#[derive(Debug)] -struct RawMessageBusMessage { - channel: String, - message_id: i64, - data: Value, -} - -impl FireCore { - pub fn subscribe_message_bus_channel( - &self, - subscription: MessageBusSubscription, - ) -> Result<(), FireCoreError> { - let snapshot = self.snapshot(); - let mut runtime = self - .message_bus - .lock() - .expect("message bus runtime lock poisoned"); - let mut changed = ensure_bootstrap_subscriptions(&snapshot.bootstrap, &mut runtime); - - let last_message_id = subscription.last_message_id.unwrap_or_else(|| { - bootstrap_message_id_for_channel(&snapshot.bootstrap, &subscription.channel) - .unwrap_or(INITIAL_MESSAGE_ID) - }); - changed |= upsert_runtime_subscription_owner( - &mut runtime, - subscription.owner_token, - subscription.channel, - last_message_id, - subscription.scope, - ); - - if changed { - mark_subscriptions_changed(&mut runtime); - ensure_poll_task_running(self, &mut runtime)?; - } - Ok(()) - } - - pub fn unsubscribe_message_bus_channel( - &self, - owner_token: String, - channel: String, - ) -> Result<(), FireCoreError> { - let mut runtime = self - .message_bus - .lock() - .expect("message bus runtime lock poisoned"); - if remove_runtime_subscription_owner(&mut runtime, &owner_token, &channel) { - let removed_presence_topic_id = presence_topic_id_from_channel(&channel); - mark_subscriptions_changed(&mut runtime); - ensure_poll_task_running(self, &mut runtime)?; - if let Some(topic_id) = removed_presence_topic_id { - // Keep the message bus lock until the cached snapshot is evicted so a - // concurrent re-subscribe cannot reintroduce the same topic between steps. - clear_topic_presence_snapshot(&self.topic_presence, topic_id); - } - } - Ok(()) - } - - pub async fn start_message_bus( - &self, - mode: MessageBusClientMode, - event_sender: UnboundedSender, - topic_tracking_state_meta: Option>, - ) -> Result { - let snapshot = self.snapshot(); - if !snapshot.cookies.can_authenticate_requests() { - return Err(FireCoreError::MissingLoginSession); - } - if message_bus_requires_shared_session_key(&self.base_url, &snapshot.bootstrap)? - && snapshot.bootstrap.shared_session_key.is_none() - { - return Err(FireCoreError::MissingSharedSessionKey); - } - - let runtime_handle = Handle::current(); - let mut runtime = self - .message_bus - .lock() - .expect("message bus runtime lock poisoned"); - let mut bootstrap_changed = - ensure_bootstrap_subscriptions(&snapshot.bootstrap, &mut runtime); - if let Some(meta) = topic_tracking_state_meta { - bootstrap_changed |= apply_topic_tracking_state_meta(&meta, &mut runtime); - } - if bootstrap_changed { - mark_subscriptions_changed(&mut runtime); - } - - stop_poll_task_locked(&mut runtime); - runtime.active_mode = Some(mode); - runtime.runtime_handle = Some(runtime_handle); - runtime.event_sender = Some(event_sender); - - let client_id = client_id_for_mode(&mut runtime, mode); - runtime.active_client_id = Some(client_id.clone()); - - runtime.poll_task = Some(spawn_poll_task(self, &mut runtime, client_id.clone())?); - - info!( - client_id = %client_id, - mode = ?mode, - subscriptions = runtime.subscriptions.len(), - idle = runtime.subscriptions.is_empty(), - "message bus started" - ); - Ok(client_id) - } - - pub fn stop_message_bus(&self, clear_subscriptions: bool) { - let mut runtime = self - .message_bus - .lock() - .expect("message bus runtime lock poisoned"); - stop_poll_task_locked(&mut runtime); - runtime.active_client_id = None; - runtime.active_mode = None; - runtime.event_sender = None; - runtime.runtime_handle = None; - if clear_subscriptions { - runtime.subscriptions.clear(); - runtime.foreground_client_id = None; - } - } - - pub async fn poll_notification_alert_once( - &self, - last_message_id: i64, - ) -> Result { - let snapshot = self.snapshot(); - if !snapshot.cookies.can_authenticate_requests() { - return Err(FireCoreError::MissingLoginSession); - } - if message_bus_requires_shared_session_key(&self.base_url, &snapshot.bootstrap)? - && snapshot.bootstrap.shared_session_key.is_none() - { - return Err(FireCoreError::MissingSharedSessionKey); - } - - let notification_user_id = snapshot - .bootstrap - .current_user_id - .ok_or(FireCoreError::MissingCurrentUserId)?; - let channel = format!("/notification-alert/{notification_user_id}"); - let client_id = generate_ios_background_client_id(); - let traced = build_message_bus_poll_request_for_snapshot( - &self.diagnostics, - &self.base_url, - &snapshot, - self.snapshot_with_epoch().1, - &client_id, - MessageBusClientMode::IosBackground, - &[(channel.clone(), last_message_id)], - )?; - debug!( - trace_id = traced.trace_id, - client_id = %client_id, - channel = %channel, - last_message_id, - "executing background notification-alert poll request" - ); - let (trace_id, response) = self - .network - .execute_traced(traced, FireCallProfile::MessageBusPoll) - .await?; - - if !response.status().is_success() { - match read_message_bus_error_response_for_diagnostics( - &self.diagnostics, - trace_id, - response, - ) - .await - { - Err(error) => return Err(error), - Ok(_) => unreachable!("message bus error response should not succeed"), - } - } - - read_notification_alert_success_response( - &self.diagnostics, - trace_id, - response, - notification_user_id, - &client_id, - &channel, - last_message_id, - ) - .await - } -} - -fn ensure_poll_task_running( - core: &FireCore, - runtime: &mut FireMessageBusRuntime, -) -> Result<(), FireCoreError> { - if runtime.active_mode.is_none() || runtime.poll_task.is_some() { - return Ok(()); - } - let client_id = runtime - .active_client_id - .clone() - .or_else(|| { - runtime - .active_mode - .map(|mode| client_id_for_mode(runtime, mode)) - }) - .expect("message bus active mode should exist"); - runtime.active_client_id = Some(client_id.clone()); - runtime.poll_task = Some(spawn_poll_task(core, runtime, client_id)?); - Ok(()) -} - -fn stop_poll_task_locked(runtime: &mut FireMessageBusRuntime) { - if let Some(task) = runtime.poll_task.take() { - task.abort(); - } -} - -fn spawn_poll_task( - core: &FireCore, - runtime: &mut FireMessageBusRuntime, - client_id: String, -) -> Result, FireCoreError> { - let runtime_handle = runtime - .runtime_handle - .clone() - .ok_or(FireCoreError::MessageBusNotStarted)?; - let event_sender = runtime - .event_sender - .clone() - .ok_or(FireCoreError::MessageBusNotStarted)?; - let subscription_updates = subscription_updates_receiver(runtime); - runtime.poll_task_token = runtime.poll_task_token.saturating_add(1); - let task_token = runtime.poll_task_token; - let mode = runtime - .active_mode - .ok_or(FireCoreError::MessageBusNotStarted)?; - let context = MessageBusPollContext { - core: core.clone(), - base_url: core.base_url.clone(), - network: core.network.clone(), - diagnostics: Arc::clone(&core.diagnostics), - session: Arc::clone(&core.session), - runtime: Arc::clone(&core.message_bus), - notifications: Arc::clone(&core.notifications), - topic_presence: Arc::clone(&core.topic_presence), - event_sender, - client_id, - mode, - task_token, - }; - Ok(runtime_handle.spawn(async move { - run_message_bus_poll_loop(context, subscription_updates).await; - })) -} - -async fn run_message_bus_poll_loop( - context: MessageBusPollContext, - mut subscription_updates: watch::Receiver, -) { - let mut failure_count = 0_u32; - - loop { - let (subscriptions, subscription_revision) = { - let runtime = context - .runtime - .lock() - .expect("message bus runtime lock poisoned"); - if runtime.active_client_id.as_deref() != Some(context.client_id.as_str()) { - break; - } - ( - runtime - .subscriptions - .iter() - .map(|(channel, entry)| (channel.clone(), entry.last_message_id)) - .collect::>(), - runtime.subscription_revision, - ) - }; - - if subscriptions.is_empty() { - if !wait_for_subscription_change(&context, &mut subscription_updates).await { - break; - } - continue; - } - - match execute_poll_once_with_subscription_changes( - &context, - &mut subscription_updates, - &subscriptions, - subscription_revision, - ) - .await - { - Ok(PollIterationResult::Continue) => { - failure_count = 0; - } - Ok(PollIterationResult::Restart) => { - failure_count = 0; - } - Ok(PollIterationResult::Stop) => break, - Err(error) => { - if is_expected_long_poll_timeout(&error) { - debug!( - client_id = %context.client_id, - error = %error, - "message bus poll timed out; continuing without backoff" - ); - failure_count = 0; - continue; - } - - log_message_bus_poll_failure(&context.client_id, &error); - failure_count = failure_count.saturating_add(1); - let delay = backoff_delay(failure_count); - sleep(delay).await; - } - } - } - - clear_poll_task_on_exit(&context.runtime, &context.client_id, context.task_token); -} - -async fn wait_for_subscription_change( - context: &MessageBusPollContext, - subscription_updates: &mut watch::Receiver, -) -> bool { - match subscription_updates.changed().await { - Ok(_) => { - context - .runtime - .lock() - .expect("message bus runtime lock poisoned") - .active_client_id - .as_deref() - == Some(context.client_id.as_str()) - } - Err(_) => false, - } -} - -async fn execute_poll_once_with_subscription_changes( - context: &MessageBusPollContext, - subscription_updates: &mut watch::Receiver, - subscriptions: &[(String, i64)], - subscription_revision: u64, -) -> Result { - let poll_started_at = Instant::now(); - let poll = execute_poll_once(context, subscriptions); - tokio::pin!(poll); - let mut pending_restart = false; - - loop { - if pending_restart { - let remaining = - MESSAGE_BUS_MIN_RESTART_INTERVAL.saturating_sub(poll_started_at.elapsed()); - if remaining.is_zero() { - return Ok(PollIterationResult::Restart); - } - - tokio::select! { - result = &mut poll => { - return result.map(|keep_running| { - if keep_running { - PollIterationResult::Continue - } else { - PollIterationResult::Stop - } - }); - } - changed = subscription_updates.changed() => { - if changed.is_err() { - return Ok(PollIterationResult::Stop); - } - pending_restart |= *subscription_updates.borrow() != subscription_revision; - } - _ = sleep(remaining) => { - return Ok(PollIterationResult::Restart); - } - } - } else { - tokio::select! { - result = &mut poll => { - return result.map(|keep_running| { - if keep_running { - PollIterationResult::Continue - } else { - PollIterationResult::Stop - } - }); - } - changed = subscription_updates.changed() => { - if changed.is_err() { - return Ok(PollIterationResult::Stop); - } - pending_restart = *subscription_updates.borrow() != subscription_revision; - } - } - } - } -} - -async fn execute_poll_once( - context: &MessageBusPollContext, - subscriptions: &[(String, i64)], -) -> Result { - let traced = build_message_bus_poll_request(context, subscriptions)?; - debug!( - trace_id = traced.trace_id, - client_id = %context.client_id, - subscriptions = subscriptions.len(), - "executing message bus poll request" - ); - let (trace_id, response) = context - .network - .execute_traced(traced, FireCallProfile::MessageBusPoll) - .await?; - - if !response.status().is_success() { - return read_message_bus_error_response(context, trace_id, response).await; - } - - read_message_bus_success_response(context, trace_id, response).await -} - -fn build_message_bus_poll_request( - context: &MessageBusPollContext, - subscriptions: &[(String, i64)], -) -> Result { - let state = read_rwlock(&context.session, "session"); - build_message_bus_poll_request_for_snapshot( - &context.diagnostics, - &context.base_url, - &state.snapshot, - state.epoch, - &context.client_id, - context.mode, - subscriptions, - ) -} - -fn build_message_bus_poll_request_for_snapshot( - diagnostics: &Arc, - base_url: &Url, - snapshot: &SessionSnapshot, - epoch: u64, - client_id: &str, - mode: MessageBusClientMode, - subscriptions: &[(String, i64)], -) -> Result { - let poll_base_url = message_bus_poll_base_url(base_url, &snapshot.bootstrap)?; - let uri = poll_base_url.join(&format!("/message-bus/{client_id}/poll"))?; - let same_origin = request_origin(base_url) == request_origin(&poll_base_url); - - let mut serializer = Serializer::new(String::new()); - for (channel, last_message_id) in subscriptions { - serializer.append_pair(channel, &last_message_id.to_string()); - } - let sequence = MESSAGE_BUS_SEQUENCE_COUNTER.fetch_add(1, Ordering::SeqCst); - serializer.append_pair("__seq", &sequence.to_string()); - - let mut builder = Request::builder() - .method(Method::POST) - .uri(uri.as_str()) - .header("Accept", "text/plain, */*; q=0.01") - .header( - "Content-Type", - "application/x-www-form-urlencoded; charset=UTF-8", - ) - .header("X-SILENCE-LOGGER", "true") - .header("Dont-Chunk", "true"); - - if mode == MessageBusClientMode::IosBackground { - builder = builder.header("Discourse-Background", "true"); - } - - if !same_origin { - let shared_session_key = snapshot - .bootstrap - .shared_session_key - .as_ref() - .ok_or(FireCoreError::MissingSharedSessionKey)?; - builder = builder.header("X-Shared-Session-Key", shared_session_key); - } - - let mut request = builder - .body(RequestBody::from(serializer.finish())) - .map_err(FireCoreError::RequestBuild)?; - request - .extensions_mut() - .insert(FireRequestProfile::MessageBusPoll); - request.extensions_mut().insert(FireRequestEpoch(epoch)); - let trace_id = diagnostics.prepare_request_trace(MESSAGE_BUS_OPERATION, &mut request); - Ok(TracedRequest { - trace_id, - operation: MESSAGE_BUS_OPERATION, - request, - }) -} - -async fn read_message_bus_error_response( - context: &MessageBusPollContext, - trace_id: u64, - response: Response, -) -> Result { - read_message_bus_error_response_for_diagnostics(&context.diagnostics, trace_id, response).await -} - -async fn read_message_bus_error_response_for_diagnostics( - diagnostics: &Arc, - trace_id: u64, - response: Response, -) -> Result { - let mut response = response; - let _trace_guard = take_trace_cancellation_guard(&mut response).unwrap_or_else(|| { - diagnostics.cancellation_guard( - trace_id, - "Request cancelled", - "Future dropped while reading the message bus error response body", - ) - }); - let status = response.status().as_u16(); - let response_headers = response.headers().clone(); - let body = match response.into_body().text().await { - Ok(body) => body, - Err(source) => { - diagnostics.record_call_failed(trace_id, &source); - return Err(FireCoreError::Network { source }); - } - }; - diagnostics.record_http_status_error(trace_id, status, &body); - Err(classify_http_status_error( - MESSAGE_BUS_OPERATION, - status, - &response_headers, - body, - )) -} - -async fn read_message_bus_success_response( - context: &MessageBusPollContext, - trace_id: u64, - response: Response, -) -> Result { - let mut response = response; - let _trace_guard = take_trace_cancellation_guard(&mut response).unwrap_or_else(|| { - context.diagnostics.cancellation_guard( - trace_id, - "Request cancelled", - "Future dropped while processing the message bus response body", - ) - }); - let content_type = header_value(response.headers(), "content-type"); - let mut body = response.into_body(); - let mut response_text = String::new(); - let mut chunk_buffer = String::new(); - - while let Some(frame) = body.frame().await { - let frame = match frame { - Ok(frame) => frame, - Err(source) => { - context.diagnostics.record_call_failed(trace_id, &source); - return Err(FireCoreError::Network { source }); - } - }; - let Ok(bytes) = frame.into_data() else { - continue; - }; - let text = String::from_utf8_lossy(&bytes); - response_text.push_str(&text); - chunk_buffer.push_str(&text); - - while let Some(delimiter) = chunk_buffer.find('|') { - let chunk = chunk_buffer[..delimiter].trim().to_string(); - chunk_buffer = chunk_buffer[delimiter + 1..].to_string(); - if !chunk.is_empty() && !process_chunk(context, &chunk)? { - context.diagnostics.record_response_body_text( - trace_id, - &response_text, - content_type.as_deref(), - ); - return Ok(false); - } - } - } - - if !chunk_buffer.trim().is_empty() && !process_chunk(context, chunk_buffer.trim())? { - context.diagnostics.record_response_body_text( - trace_id, - &response_text, - content_type.as_deref(), - ); - return Ok(false); - } - - context.diagnostics.record_response_body_text( - trace_id, - &response_text, - content_type.as_deref(), - ); - Ok(true) -} - -async fn read_notification_alert_success_response( - diagnostics: &Arc, - trace_id: u64, - response: Response, - notification_user_id: u64, - client_id: &str, - channel: &str, - initial_last_message_id: i64, -) -> Result { - let mut response = response; - let _trace_guard = take_trace_cancellation_guard(&mut response).unwrap_or_else(|| { - diagnostics.cancellation_guard( - trace_id, - "Request cancelled", - "Future dropped while processing the notification alert response body", - ) - }); - let content_type = header_value(response.headers(), "content-type"); - let mut body = response.into_body(); - let mut response_text = String::new(); - let mut chunk_buffer = String::new(); - let mut result = NotificationAlertPollResult { - notification_user_id, - client_id: client_id.to_string(), - last_message_id: initial_last_message_id, - alerts: Vec::new(), - }; - - while let Some(frame) = body.frame().await { - let frame = match frame { - Ok(frame) => frame, - Err(source) => { - diagnostics.record_call_failed(trace_id, &source); - return Err(FireCoreError::Network { source }); - } - }; - let Ok(bytes) = frame.into_data() else { - continue; - }; - let text = String::from_utf8_lossy(&bytes); - response_text.push_str(&text); - chunk_buffer.push_str(&text); - - while let Some(delimiter) = chunk_buffer.find('|') { - let chunk = chunk_buffer[..delimiter].trim().to_string(); - chunk_buffer = chunk_buffer[delimiter + 1..].to_string(); - if !chunk.is_empty() { - process_notification_alert_chunk(&mut result, channel, client_id, &chunk); - } - } - } - - if !chunk_buffer.trim().is_empty() { - process_notification_alert_chunk(&mut result, channel, client_id, chunk_buffer.trim()); - } - - diagnostics.record_response_body_text(trace_id, &response_text, content_type.as_deref()); - Ok(result) -} - -fn process_notification_alert_chunk( - result: &mut NotificationAlertPollResult, - channel: &str, - client_id: &str, - chunk: &str, -) { - let Some(messages) = - parse_message_bus_messages(chunk, client_id, "background notification-alert") - else { - return; - }; - - for message in messages { - if message.channel == "/__status" { - if let Some(last_message_id) = message - .data - .get(channel) - .and_then(|value| integer_i64(Some(value))) - { - result.last_message_id = result.last_message_id.max(last_message_id); - } - continue; - } - - if message.channel != channel { - continue; - } - - result.last_message_id = result.last_message_id.max(message.message_id); - result.alerts.push(notification_alert_from_raw(&message)); - } -} - -fn process_chunk(context: &MessageBusPollContext, chunk: &str) -> Result { - let Some(messages) = parse_message_bus_messages(chunk, &context.client_id, "message bus") - else { - return Ok(true); - }; - - for message in messages { - if message.channel == "/__status" { - apply_status_message(&context.runtime, &message.data); - continue; - } - - update_channel_checkpoint(&context.runtime, &message.channel, message.message_id); - if let Some(user_id) = logout_user_id_from_channel(&message.channel) { - if context.core.handle_server_forced_logout(user_id) { - let event = MessageBusEvent { - channel: message.channel.clone(), - message_id: message.message_id, - kind: MessageBusEventKind::SessionLogout, - notification_user_id: Some(user_id), - payload_json: serde_json::to_string(&message.data) - .ok() - .filter(|value| value != "null"), - ..MessageBusEvent::default() - }; - if context.event_sender.send(event).is_err() { - warn!("message bus listener dropped; stopping poll loop"); - return Ok(false); - } - } - continue; - } - if notification_user_id_from_channel(&message.channel).is_some() { - merge_notification_event_data(&context.notifications, &message.data); - } - if let Some(topic_id) = presence_topic_id_from_channel(&message.channel) { - merge_topic_presence_event_data( - &context.topic_presence, - topic_id, - message.message_id, - &message.data, - ); - } - let event = message_bus_event_from_raw(&message); - if context.event_sender.send(event).is_err() { - warn!("message bus listener dropped; stopping poll loop"); - return Ok(false); - } - } - - Ok(true) -} - -fn parse_message_bus_messages( - chunk: &str, - client_id: &str, - chunk_kind: &str, -) -> Option> { - let value: Value = match serde_json::from_str(chunk) { - Ok(value) => value, - Err(error) => { - warn!( - client_id = %client_id, - error = %error, - chunk = %chunk, - chunk_kind, - "failed to parse message bus chunk" - ); - return None; - } - }; - - let Some(messages) = value.as_array() else { - warn!( - client_id = %client_id, - chunk = %chunk, - chunk_kind, - "message bus chunk root was not an array" - ); - return None; - }; - - let mut parsed = Vec::with_capacity(messages.len()); - for (index, value) in messages.iter().enumerate() { - let Some(message) = raw_message_bus_message_from_value(value) else { - warn!( - client_id = %client_id, - chunk_kind, - index, - message = %value, - "skipping malformed message bus item" - ); - continue; - }; - parsed.push(message); - } - Some(parsed) -} - -fn raw_message_bus_message_from_value(value: &Value) -> Option { - let object = value.as_object()?; - let channel = scalar_string(object.get("channel"))?.trim().to_string(); - if channel.is_empty() { - return None; - } - - Some(RawMessageBusMessage { - channel, - message_id: integer_i64(object.get("message_id"))?, - data: object.get("data").cloned().unwrap_or(Value::Null), - }) -} - -fn apply_status_message(runtime: &Arc>, data: &Value) { - let Some(object) = data.as_object() else { - return; - }; - let mut runtime = runtime.lock().expect("message bus runtime lock poisoned"); - for (channel, value) in object { - let Some(last_message_id) = integer_i64(Some(value)) else { - continue; - }; - if let Some(subscription) = runtime.subscriptions.get_mut(channel) { - subscription.last_message_id = subscription.last_message_id.max(last_message_id); - } - } -} - -fn update_channel_checkpoint( - runtime: &Arc>, - channel: &str, - message_id: i64, -) { - let mut runtime = runtime.lock().expect("message bus runtime lock poisoned"); - if let Some(subscription) = runtime.subscriptions.get_mut(channel) { - subscription.last_message_id = subscription.last_message_id.max(message_id); - } -} - -fn message_bus_event_from_raw(message: &RawMessageBusMessage) -> MessageBusEvent { - let payload_json = serde_json::to_string(&message.data) - .ok() - .filter(|value| value != "null"); - - if let Some(topic_list_kind) = topic_list_kind_for_channel(&message.channel) { - return MessageBusEvent { - channel: message.channel.clone(), - message_id: message.message_id, - kind: MessageBusEventKind::TopicList, - topic_list_kind: Some(topic_list_kind), - topic_id: message - .data - .get("topic_id") - .and_then(|value| positive_u64(Some(value))) - .or_else(|| { - message - .data - .get("payload") - .and_then(|value| value.get("topic_id")) - .and_then(|value| positive_u64(Some(value))) - }), - message_type: message - .data - .get("message_type") - .and_then(Value::as_str) - .map(ToOwned::to_owned), - payload_json, - ..MessageBusEvent::default() - }; - } - - if let Some(topic_id) = topic_reaction_topic_id_from_channel(&message.channel) { - return MessageBusEvent { - channel: message.channel.clone(), - message_id: message.message_id, - kind: MessageBusEventKind::TopicReaction, - topic_id: Some(topic_id), - payload_json, - ..MessageBusEvent::default() - }; - } - - if let Some(topic_id) = topic_polls_topic_id_from_channel(&message.channel) { - return MessageBusEvent { - channel: message.channel.clone(), - message_id: message.message_id, - kind: MessageBusEventKind::TopicDetail, - topic_id: Some(topic_id), - detail_event_type: Some("polls".to_string()), - refresh_stream: true, - payload_json, - ..MessageBusEvent::default() - }; - } - - if let Some(topic_id) = topic_id_from_channel(&message.channel) { - return MessageBusEvent { - channel: message.channel.clone(), - message_id: message.message_id, - kind: MessageBusEventKind::TopicDetail, - topic_id: Some(topic_id), - detail_event_type: message - .data - .get("type") - .and_then(Value::as_str) - .map(ToOwned::to_owned), - reload_topic: boolean(message.data.get("reload_topic")), - refresh_stream: boolean(message.data.get("refresh_stream")), - payload_json, - ..MessageBusEvent::default() - }; - } - - if let Some(topic_id) = presence_topic_id_from_channel(&message.channel) { - return MessageBusEvent { - channel: message.channel.clone(), - message_id: message.message_id, - kind: MessageBusEventKind::Presence, - topic_id: Some(topic_id), - payload_json, - ..MessageBusEvent::default() - }; - } - - if let Some(notification_user_id) = notification_user_id_from_channel(&message.channel) { - return MessageBusEvent { - channel: message.channel.clone(), - message_id: message.message_id, - kind: MessageBusEventKind::Notification, - notification_user_id: Some(notification_user_id), - all_unread_notifications_count: message - .data - .get("all_unread_notifications_count") - .and_then(|value| integer_u32(Some(value))), - unread_notifications: message - .data - .get("unread_notifications") - .and_then(|value| integer_u32(Some(value))), - unread_high_priority_notifications: message - .data - .get("unread_high_priority_notifications") - .and_then(|value| integer_u32(Some(value))), - payload_json, - ..MessageBusEvent::default() - }; - } - - if let Some(notification_user_id) = notification_alert_user_id_from_channel(&message.channel) { - return MessageBusEvent { - channel: message.channel.clone(), - message_id: message.message_id, - kind: MessageBusEventKind::NotificationAlert, - notification_user_id: Some(notification_user_id), - payload_json, - ..MessageBusEvent::default() - }; - } - - if message.channel.starts_with("/chat/") || message.channel == "/chat" { - return MessageBusEvent { - channel: message.channel.clone(), - message_id: message.message_id, - kind: MessageBusEventKind::Chat, - // Reuse topic_id slot for chat channel id when the path encodes one - // (`/chat/{id}`, `/chat/{id}/new-messages`, `/chat/{id}/thread/{tid}`). - topic_id: chat_channel_id_from_channel(&message.channel), - detail_event_type: message - .data - .get("type") - .and_then(Value::as_str) - .map(ToOwned::to_owned), - message_type: message - .data - .get("type") - .and_then(Value::as_str) - .map(ToOwned::to_owned), - payload_json, - ..MessageBusEvent::default() - }; - } - - MessageBusEvent { - channel: message.channel.clone(), - message_id: message.message_id, - kind: MessageBusEventKind::Unknown, - payload_json, - ..MessageBusEvent::default() - } -} - -fn chat_channel_id_from_channel(channel: &str) -> Option { - // /chat/{id} - // /chat/{id}/new-messages - // /chat/{id}/thread/{tid} - let rest = channel.strip_prefix("/chat/")?; - let first = rest.split('/').next()?; - first.parse::().ok().filter(|id| *id > 0) -} - -fn logout_user_id_from_channel(channel: &str) -> Option { - let rest = channel.strip_prefix("/logout/")?; - if rest.contains('/') { - return None; - } - rest.parse::().ok().filter(|id| *id > 0) -} - -fn notification_alert_from_raw(message: &RawMessageBusMessage) -> NotificationAlert { - NotificationAlert { - message_id: message.message_id, - notification_type: message - .data - .get("notification_type") - .and_then(|value| integer_u32(Some(value))), - topic_id: message - .data - .get("topic_id") - .and_then(|value| positive_u64(Some(value))), - post_number: message - .data - .get("post_number") - .and_then(|value| integer_u32(Some(value))), - topic_title: message - .data - .get("topic_title") - .and_then(Value::as_str) - .map(ToOwned::to_owned), - excerpt: message - .data - .get("excerpt") - .and_then(Value::as_str) - .map(ToOwned::to_owned), - username: message - .data - .get("username") - .and_then(Value::as_str) - .map(ToOwned::to_owned), - post_url: message - .data - .get("post_url") - .and_then(Value::as_str) - .map(ToOwned::to_owned), - payload_json: serde_json::to_string(&message.data) - .ok() - .filter(|value| value != "null"), - } -} - -fn ensure_bootstrap_subscriptions( - bootstrap: &BootstrapArtifacts, - runtime: &mut FireMessageBusRuntime, -) -> bool { - let mut changed = false; - - for (channel, last_message_id) in bootstrap_tracking_subscriptions(bootstrap) { - changed |= upsert_runtime_subscription_owner( - runtime, - BOOTSTRAP_TRACKING_OWNER_TOKEN.to_string(), - channel, - last_message_id, - MessageBusSubscriptionScope::Durable, - ); - } - - if let (Some(user_id), Some(last_message_id)) = ( - bootstrap.current_user_id, - bootstrap.notification_channel_position, - ) { - changed |= upsert_runtime_subscription_owner( - runtime, - BOOTSTRAP_NOTIFICATION_OWNER_TOKEN.to_string(), - format!("/notification/{user_id}"), - last_message_id, - MessageBusSubscriptionScope::Durable, - ); - } - - if let Some(user_id) = bootstrap.current_user_id.filter(|id| *id > 0) { - let channel = format!("/logout/{user_id}"); - let last_message_id = - bootstrap_message_id_for_channel(bootstrap, &channel).unwrap_or(INITIAL_MESSAGE_ID); - changed |= upsert_runtime_subscription_owner( - runtime, - BOOTSTRAP_LOGOUT_OWNER_TOKEN.to_string(), - channel, - last_message_id, - MessageBusSubscriptionScope::Durable, - ); - } - - changed -} - -fn bootstrap_tracking_subscriptions(bootstrap: &BootstrapArtifacts) -> Vec<(String, i64)> { - let Some(raw) = bootstrap.topic_tracking_state_meta.as_deref() else { - return Vec::new(); - }; - let Ok(value) = serde_json::from_str::(raw) else { - return Vec::new(); - }; - let Some(object) = value.as_object() else { - return Vec::new(); - }; - - object - .iter() - .filter_map(|(channel, value)| { - if !channel.starts_with('/') { - return None; - } - integer_i64(Some(value)).map(|last_message_id| (channel.clone(), last_message_id)) - }) - .collect() -} - -fn apply_topic_tracking_state_meta( - meta: &HashMap, - runtime: &mut FireMessageBusRuntime, -) -> bool { - let mut changed = false; - for (channel, last_message_id) in meta { - if !channel.starts_with('/') { - continue; - } - changed |= upsert_runtime_subscription_owner( - runtime, - BOOTSTRAP_TRACKING_OWNER_TOKEN.to_string(), - channel.clone(), - *last_message_id, - MessageBusSubscriptionScope::Durable, - ); - } - changed -} - -fn bootstrap_message_id_for_channel(bootstrap: &BootstrapArtifacts, channel: &str) -> Option { - if let Some(notification_channel) = bootstrap_notification_channel(bootstrap) { - if notification_channel.0 == channel { - return Some(notification_channel.1); - } - } - - bootstrap_tracking_subscriptions(bootstrap) - .into_iter() - .find_map(|(known_channel, last_message_id)| { - (known_channel == channel).then_some(last_message_id) - }) -} - -fn bootstrap_notification_channel(bootstrap: &BootstrapArtifacts) -> Option<(String, i64)> { - Some(( - format!("/notification/{}", bootstrap.current_user_id?), - bootstrap.notification_channel_position?, - )) -} - -fn client_id_for_mode(runtime: &mut FireMessageBusRuntime, mode: MessageBusClientMode) -> String { - match mode { - MessageBusClientMode::Foreground => runtime - .foreground_client_id - .get_or_insert_with(generate_foreground_client_id) - .clone(), - MessageBusClientMode::IosBackground => generate_ios_background_client_id(), - } -} - -fn generate_foreground_client_id() -> String { - let counter = FOREGROUND_CLIENT_COUNTER.fetch_add(1, Ordering::SeqCst); - format!("fire_{:x}{:x}", now_unix_ms(), counter) -} - -fn generate_ios_background_client_id() -> String { - format!("ios_bg_{}", now_unix_ms()) -} - -fn now_unix_ms() -> u64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .map(|duration| duration.as_millis() as u64) - .unwrap_or_default() -} - -fn backoff_delay(failure_count: u32) -> Duration { - let exponent = failure_count.saturating_sub(1).min(4); - let seconds = 2_u64.saturating_pow(exponent); - let base_delay = Duration::from_secs(seconds).min(MAX_BACKOFF_DELAY); - let base_delay_ms = base_delay.as_millis() as u64; - let jitter_window_ms = base_delay_ms / 4; - if jitter_window_ms == 0 { - return base_delay; - } - - let jitter_seed = now_unix_ms() - ^ u64::from(failure_count) - ^ FOREGROUND_CLIENT_COUNTER.load(Ordering::Relaxed); - let jitter_ms = jitter_seed % (jitter_window_ms.saturating_mul(2) + 1); - let delay_ms = base_delay_ms - .saturating_sub(jitter_window_ms) - .saturating_add(jitter_ms); - Duration::from_millis(delay_ms).min(MAX_BACKOFF_DELAY) -} - -fn upsert_runtime_subscription_owner( - runtime: &mut FireMessageBusRuntime, - owner_token: String, - channel: String, - last_message_id: i64, - scope: MessageBusSubscriptionScope, -) -> bool { - let owner_key = owner_token; - let mut is_new_channel = false; - let entry = runtime.subscriptions.entry(channel).or_insert_with(|| { - is_new_channel = true; - RuntimeSubscription { - last_message_id, - owners: BTreeMap::new(), - } - }); - let previous_last_message_id = entry.last_message_id; - entry.last_message_id = entry.last_message_id.max(last_message_id); - entry - .owners - .insert(owner_key.clone(), RuntimeSubscriptionOwner { scope }); - is_new_channel || entry.last_message_id != previous_last_message_id -} - -fn remove_runtime_subscription_owner( - runtime: &mut FireMessageBusRuntime, - owner_token: &str, - channel: &str, -) -> bool { - let Some(entry) = runtime.subscriptions.get_mut(channel) else { - return false; - }; - - let removed = entry.owners.remove(owner_token).is_some(); - if !removed { - return false; - } - - if entry.owners.is_empty() { - runtime.subscriptions.remove(channel); - return true; - } - - false -} - -fn mark_subscriptions_changed(runtime: &mut FireMessageBusRuntime) { - runtime.subscription_revision = runtime.subscription_revision.saturating_add(1); - if let Some(sender) = &runtime.subscription_updates { - let _ = sender.send(runtime.subscription_revision); - } -} - -fn subscription_updates_receiver(runtime: &mut FireMessageBusRuntime) -> watch::Receiver { - if let Some(sender) = &runtime.subscription_updates { - sender.subscribe() - } else { - let (sender, receiver) = watch::channel(runtime.subscription_revision); - runtime.subscription_updates = Some(sender); - receiver - } -} - -fn is_expected_long_poll_timeout(error: &FireCoreError) -> bool { - matches!( - error, - FireCoreError::Network { source } - if source.kind() == WireErrorKind::Timeout && !source.is_connect_timeout() - ) -} - -fn log_message_bus_poll_failure(client_id: &str, error: &FireCoreError) { - match error { - FireCoreError::HttpStatus { status, .. } if matches!(status, 429 | 502 | 503 | 504) => { - let category = match status { - 429 => "rate_limited", - _ => "server_unavailable", - }; - warn!( - client_id = %client_id, - status = *status, - category, - error = %error, - "message bus poll iteration failed" - ); - } - _ => { - warn!( - client_id = %client_id, - error = %error, - "message bus poll iteration failed" - ); - } - } -} - -fn clear_poll_task_on_exit( - runtime: &Arc>, - client_id: &str, - task_token: u64, -) { - let mut runtime = runtime.lock().expect("message bus runtime lock poisoned"); - if runtime.active_client_id.as_deref() == Some(client_id) - && runtime.poll_task_token == task_token - { - runtime.poll_task = None; - } -} - -fn message_bus_poll_base_url( - base_url: &Url, - bootstrap: &BootstrapArtifacts, -) -> Result { - match bootstrap.long_polling_base_url.as_deref() { - Some(long_polling_base_url) if !long_polling_base_url.is_empty() => { - Url::parse(long_polling_base_url).map_err(Into::into) - } - _ => Ok(base_url.clone()), - } -} - -pub(crate) fn message_bus_requires_shared_session_key( - base_url: &Url, - bootstrap: &BootstrapArtifacts, -) -> Result { - let poll_base_url = message_bus_poll_base_url(base_url, bootstrap)?; - Ok(request_origin(base_url) != request_origin(&poll_base_url)) -} - -fn topic_list_kind_for_channel(channel: &str) -> Option { - match channel { - "/latest" => Some(TopicListKind::Latest), - "/new" => Some(TopicListKind::New), - _ => None, - } -} - -fn topic_id_from_channel(channel: &str) -> Option { - let mut parts = channel.trim_matches('/').split('/'); - match (parts.next(), parts.next(), parts.next(), parts.next()) { - (Some("topic"), Some(topic_id), None, None) => topic_id.parse::().ok(), - _ => None, - } -} - -fn topic_reaction_topic_id_from_channel(channel: &str) -> Option { - let mut parts = channel.trim_matches('/').split('/'); - match (parts.next(), parts.next(), parts.next(), parts.next()) { - (Some("topic"), Some(topic_id), Some("reactions"), None) => topic_id.parse::().ok(), - _ => None, - } -} - -fn topic_polls_topic_id_from_channel(channel: &str) -> Option { - let mut parts = channel.trim_matches('/').split('/'); - match (parts.next(), parts.next(), parts.next()) { - (Some("polls"), Some(topic_id), None) => topic_id.parse::().ok(), - _ => None, - } -} - -pub(crate) fn presence_topic_id_from_channel(channel: &str) -> Option { - let mut parts = channel.trim_matches('/').split('/'); - match ( - parts.next(), - parts.next(), - parts.next(), - parts.next(), - parts.next(), - ) { - (Some("presence"), Some("discourse-presence"), Some("reply"), Some(topic_id), None) => { - topic_id.parse::().ok() - } - _ => None, - } -} - -pub(crate) fn message_bus_presence_channel_for_topic(topic_id: u64) -> String { - format!("/presence/discourse-presence/reply/{topic_id}") -} - -fn notification_user_id_from_channel(channel: &str) -> Option { - let mut parts = channel.trim_matches('/').split('/'); - match (parts.next(), parts.next(), parts.next()) { - (Some("notification"), Some(user_id), None) => user_id.parse::().ok(), - _ => None, - } -} - -fn notification_alert_user_id_from_channel(channel: &str) -> Option { - let mut parts = channel.trim_matches('/').split('/'); - match (parts.next(), parts.next(), parts.next()) { - (Some("notification-alert"), Some(user_id), None) => user_id.parse::().ok(), - _ => None, - } -} - -pub(crate) fn active_message_bus_client_id( - runtime: &Arc>, -) -> Option { - runtime - .lock() - .expect("message bus runtime lock poisoned") - .active_client_id - .clone() -} - -pub(crate) fn upload_client_id(runtime: &Arc>) -> String { - let mut runtime = runtime.lock().expect("message bus runtime lock poisoned"); - runtime - .active_client_id - .clone() - .unwrap_or_else(|| client_id_for_mode(&mut runtime, MessageBusClientMode::Foreground)) -} - -#[cfg(test)] -mod tests { - use openwire::WireError; - - use super::*; - - #[test] - fn call_timeout_is_treated_as_expected_long_poll_timeout() { - let error = FireCoreError::Network { - source: WireError::timeout("call timed out after 75s"), - }; - - assert!(is_expected_long_poll_timeout(&error)); - } - - #[test] - fn connect_timeout_is_not_treated_as_expected_long_poll_timeout() { - let error = FireCoreError::Network { - source: WireError::connect_timeout("connect timed out after 10s"), - }; - - assert!(!is_expected_long_poll_timeout(&error)); - } -} diff --git a/rust/crates/fire-core/src/core/messagebus/channels.rs b/rust/crates/fire-core/src/core/messagebus/channels.rs new file mode 100644 index 00000000..c5a5e248 --- /dev/null +++ b/rust/crates/fire-core/src/core/messagebus/channels.rs @@ -0,0 +1,157 @@ +use std::sync::{ + Arc, Mutex, + }; + +use fire_models::{ + MessageBusClientMode, NotificationAlert, TopicListKind, +}; +use serde_json::Value; + +use super::runtime::client_id_for_mode; +use super::*; +use crate::json_helpers::{integer_u32, positive_u64}; + +pub(super) fn chat_channel_id_from_channel(channel: &str) -> Option { + // /chat/{id} + // /chat/{id}/new-messages + // /chat/{id}/thread/{tid} + let rest = channel.strip_prefix("/chat/")?; + let first = rest.split('/').next()?; + first.parse::().ok().filter(|id| *id > 0) +} + +pub(super) fn logout_user_id_from_channel(channel: &str) -> Option { + let rest = channel.strip_prefix("/logout/")?; + if rest.contains('/') { + return None; + } + rest.parse::().ok().filter(|id| *id > 0) +} + +pub(super) fn notification_alert_from_raw(message: &RawMessageBusMessage) -> NotificationAlert { + NotificationAlert { + message_id: message.message_id, + notification_type: message + .data + .get("notification_type") + .and_then(|value| integer_u32(Some(value))), + topic_id: message + .data + .get("topic_id") + .and_then(|value| positive_u64(Some(value))), + post_number: message + .data + .get("post_number") + .and_then(|value| integer_u32(Some(value))), + topic_title: message + .data + .get("topic_title") + .and_then(Value::as_str) + .map(ToOwned::to_owned), + excerpt: message + .data + .get("excerpt") + .and_then(Value::as_str) + .map(ToOwned::to_owned), + username: message + .data + .get("username") + .and_then(Value::as_str) + .map(ToOwned::to_owned), + post_url: message + .data + .get("post_url") + .and_then(Value::as_str) + .map(ToOwned::to_owned), + payload_json: serde_json::to_string(&message.data) + .ok() + .filter(|value| value != "null"), + } +} + + +pub(super) fn topic_list_kind_for_channel(channel: &str) -> Option { + match channel { + "/latest" => Some(TopicListKind::Latest), + "/new" => Some(TopicListKind::New), + _ => None, + } +} + +pub(super) fn topic_id_from_channel(channel: &str) -> Option { + let mut parts = channel.trim_matches('/').split('/'); + match (parts.next(), parts.next(), parts.next(), parts.next()) { + (Some("topic"), Some(topic_id), None, None) => topic_id.parse::().ok(), + _ => None, + } +} + +pub(super) fn topic_reaction_topic_id_from_channel(channel: &str) -> Option { + let mut parts = channel.trim_matches('/').split('/'); + match (parts.next(), parts.next(), parts.next(), parts.next()) { + (Some("topic"), Some(topic_id), Some("reactions"), None) => topic_id.parse::().ok(), + _ => None, + } +} + +pub(super) fn topic_polls_topic_id_from_channel(channel: &str) -> Option { + let mut parts = channel.trim_matches('/').split('/'); + match (parts.next(), parts.next(), parts.next()) { + (Some("polls"), Some(topic_id), None) => topic_id.parse::().ok(), + _ => None, + } +} + +pub(crate) fn presence_topic_id_from_channel(channel: &str) -> Option { + let mut parts = channel.trim_matches('/').split('/'); + match ( + parts.next(), + parts.next(), + parts.next(), + parts.next(), + parts.next(), + ) { + (Some("presence"), Some("discourse-presence"), Some("reply"), Some(topic_id), None) => { + topic_id.parse::().ok() + } + _ => None, + } +} + +pub(crate) fn message_bus_presence_channel_for_topic(topic_id: u64) -> String { + format!("/presence/discourse-presence/reply/{topic_id}") +} + +pub(super) fn notification_user_id_from_channel(channel: &str) -> Option { + let mut parts = channel.trim_matches('/').split('/'); + match (parts.next(), parts.next(), parts.next()) { + (Some("notification"), Some(user_id), None) => user_id.parse::().ok(), + _ => None, + } +} + +pub(super) fn notification_alert_user_id_from_channel(channel: &str) -> Option { + let mut parts = channel.trim_matches('/').split('/'); + match (parts.next(), parts.next(), parts.next()) { + (Some("notification-alert"), Some(user_id), None) => user_id.parse::().ok(), + _ => None, + } +} + +pub(crate) fn active_message_bus_client_id( + runtime: &Arc>, +) -> Option { + runtime + .lock() + .expect("message bus runtime lock poisoned") + .active_client_id + .clone() +} + +pub(crate) fn upload_client_id(runtime: &Arc>) -> String { + let mut runtime = runtime.lock().expect("message bus runtime lock poisoned"); + runtime + .active_client_id + .clone() + .unwrap_or_else(|| client_id_for_mode(&mut runtime, MessageBusClientMode::Foreground)) +} diff --git a/rust/crates/fire-core/src/core/messagebus/mod.rs b/rust/crates/fire-core/src/core/messagebus/mod.rs new file mode 100644 index 00000000..3894ae6f --- /dev/null +++ b/rust/crates/fire-core/src/core/messagebus/mod.rs @@ -0,0 +1,113 @@ +use std::{ + collections::BTreeMap, + sync::{ + atomic::AtomicU64, + Arc, Mutex, RwLock, + }, + time::Duration, +}; + +use fire_models::{ + MessageBusClientMode, MessageBusEvent, MessageBusSubscriptionScope, +}; +use serde_json::Value; +use tokio::{ + runtime::Handle, + sync::{mpsc::UnboundedSender, watch}, + task::JoinHandle, +}; +use url::Url; + +use super::{ + network::FireNetworkLayer, + notifications::FireNotificationRuntime, + presence::FireTopicPresenceRuntime, + FireCore, FireSessionRuntimeState, +}; +use crate::diagnostics::FireDiagnosticsStore; + +const MESSAGE_BUS_OPERATION: &str = "message bus poll"; +const INITIAL_MESSAGE_ID: i64 = -1; +const MAX_BACKOFF_DELAY: Duration = Duration::from_secs(15); +const MESSAGE_BUS_MIN_RESTART_INTERVAL: Duration = Duration::from_millis(150); +const BOOTSTRAP_TRACKING_OWNER_TOKEN: &str = "__bootstrap_tracking__"; +const BOOTSTRAP_NOTIFICATION_OWNER_TOKEN: &str = "__bootstrap_notification__"; +const BOOTSTRAP_LOGOUT_OWNER_TOKEN: &str = "__bootstrap_logout__"; + +static FOREGROUND_CLIENT_COUNTER: AtomicU64 = AtomicU64::new(1); +static MESSAGE_BUS_SEQUENCE_COUNTER: AtomicU64 = AtomicU64::new(1); + +#[derive(Default)] +pub(crate) struct FireMessageBusRuntime { + foreground_client_id: Option, + active_client_id: Option, + active_mode: Option, + runtime_handle: Option, + event_sender: Option>, + subscriptions: BTreeMap, + subscription_revision: u64, + subscription_updates: Option>, + poll_task_token: u64, + poll_task: Option>, + next_internal_listener_id: u64, + internal_listeners: Vec, +} + +#[derive(Clone)] +pub(crate) struct MessageBusInternalListener { + pub id: u64, + pub on_event: std::sync::Arc, + pub on_stopped: std::sync::Arc, + pub on_started: std::sync::Arc, +} + +#[derive(Debug, Clone)] +struct RuntimeSubscription { + last_message_id: i64, + owners: BTreeMap, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct RuntimeSubscriptionOwner { + scope: MessageBusSubscriptionScope, +} + +#[derive(Clone)] +struct MessageBusPollContext { + core: FireCore, + base_url: Url, + network: FireNetworkLayer, + diagnostics: Arc, + session: Arc>, + runtime: Arc>, + notifications: Arc>, + topic_presence: Arc>, + event_sender: UnboundedSender, + client_id: String, + mode: MessageBusClientMode, + task_token: u64, +} + +enum PollIterationResult { + Continue, + Stop, + Restart, +} + +#[derive(Debug)] +struct RawMessageBusMessage { + channel: String, + message_id: i64, + data: Value, +} + + +mod channels; +mod parse; +mod poll; +mod runtime; + +pub(crate) use channels::{ + active_message_bus_client_id, message_bus_presence_channel_for_topic, upload_client_id, +}; +pub(crate) use runtime::message_bus_requires_shared_session_key; diff --git a/rust/crates/fire-core/src/core/messagebus/parse.rs b/rust/crates/fire-core/src/core/messagebus/parse.rs new file mode 100644 index 00000000..395531ec --- /dev/null +++ b/rust/crates/fire-core/src/core/messagebus/parse.rs @@ -0,0 +1,251 @@ +use std::sync::{ + Arc, Mutex, + }; + +use fire_models::{ + MessageBusEvent, MessageBusEventKind, +}; +use serde_json::Value; +use tracing::warn; + +use super::channels::*; +use super::*; +use crate::json_helpers::{boolean, integer_i64, integer_u32, positive_u64, scalar_string}; + +pub(super) fn parse_message_bus_messages( + chunk: &str, + client_id: &str, + chunk_kind: &str, +) -> Option> { + let value: Value = match serde_json::from_str(chunk) { + Ok(value) => value, + Err(error) => { + warn!( + client_id = %client_id, + error = %error, + chunk = %chunk, + chunk_kind, + "failed to parse message bus chunk" + ); + return None; + } + }; + + let Some(messages) = value.as_array() else { + warn!( + client_id = %client_id, + chunk = %chunk, + chunk_kind, + "message bus chunk root was not an array" + ); + return None; + }; + + let mut parsed = Vec::with_capacity(messages.len()); + for (index, value) in messages.iter().enumerate() { + let Some(message) = raw_message_bus_message_from_value(value) else { + warn!( + client_id = %client_id, + chunk_kind, + index, + message = %value, + "skipping malformed message bus item" + ); + continue; + }; + parsed.push(message); + } + Some(parsed) +} + +pub(super) fn raw_message_bus_message_from_value(value: &Value) -> Option { + let object = value.as_object()?; + let channel = scalar_string(object.get("channel"))?.trim().to_string(); + if channel.is_empty() { + return None; + } + + Some(RawMessageBusMessage { + channel, + message_id: integer_i64(object.get("message_id"))?, + data: object.get("data").cloned().unwrap_or(Value::Null), + }) +} + +pub(super) fn apply_status_message(runtime: &Arc>, data: &Value) { + let Some(object) = data.as_object() else { + return; + }; + let mut runtime = runtime.lock().expect("message bus runtime lock poisoned"); + for (channel, value) in object { + let Some(last_message_id) = integer_i64(Some(value)) else { + continue; + }; + if let Some(subscription) = runtime.subscriptions.get_mut(channel) { + subscription.last_message_id = subscription.last_message_id.max(last_message_id); + } + } +} + +pub(super) fn update_channel_checkpoint( + runtime: &Arc>, + channel: &str, + message_id: i64, +) { + let mut runtime = runtime.lock().expect("message bus runtime lock poisoned"); + if let Some(subscription) = runtime.subscriptions.get_mut(channel) { + subscription.last_message_id = subscription.last_message_id.max(message_id); + } +} + +pub(super) fn message_bus_event_from_raw(message: &RawMessageBusMessage) -> MessageBusEvent { + let payload_json = serde_json::to_string(&message.data) + .ok() + .filter(|value| value != "null"); + + if let Some(topic_list_kind) = topic_list_kind_for_channel(&message.channel) { + return MessageBusEvent { + channel: message.channel.clone(), + message_id: message.message_id, + kind: MessageBusEventKind::TopicList, + topic_list_kind: Some(topic_list_kind), + topic_id: message + .data + .get("topic_id") + .and_then(|value| positive_u64(Some(value))) + .or_else(|| { + message + .data + .get("payload") + .and_then(|value| value.get("topic_id")) + .and_then(|value| positive_u64(Some(value))) + }), + message_type: message + .data + .get("message_type") + .and_then(Value::as_str) + .map(ToOwned::to_owned), + payload_json, + ..MessageBusEvent::default() + }; + } + + if let Some(topic_id) = topic_reaction_topic_id_from_channel(&message.channel) { + return MessageBusEvent { + channel: message.channel.clone(), + message_id: message.message_id, + kind: MessageBusEventKind::TopicReaction, + topic_id: Some(topic_id), + payload_json, + ..MessageBusEvent::default() + }; + } + + if let Some(topic_id) = topic_polls_topic_id_from_channel(&message.channel) { + return MessageBusEvent { + channel: message.channel.clone(), + message_id: message.message_id, + kind: MessageBusEventKind::TopicDetail, + topic_id: Some(topic_id), + detail_event_type: Some("polls".to_string()), + refresh_stream: true, + payload_json, + ..MessageBusEvent::default() + }; + } + + if let Some(topic_id) = topic_id_from_channel(&message.channel) { + return MessageBusEvent { + channel: message.channel.clone(), + message_id: message.message_id, + kind: MessageBusEventKind::TopicDetail, + topic_id: Some(topic_id), + detail_event_type: message + .data + .get("type") + .and_then(Value::as_str) + .map(ToOwned::to_owned), + reload_topic: boolean(message.data.get("reload_topic")), + refresh_stream: boolean(message.data.get("refresh_stream")), + payload_json, + ..MessageBusEvent::default() + }; + } + + if let Some(topic_id) = presence_topic_id_from_channel(&message.channel) { + return MessageBusEvent { + channel: message.channel.clone(), + message_id: message.message_id, + kind: MessageBusEventKind::Presence, + topic_id: Some(topic_id), + payload_json, + ..MessageBusEvent::default() + }; + } + + if let Some(notification_user_id) = notification_user_id_from_channel(&message.channel) { + return MessageBusEvent { + channel: message.channel.clone(), + message_id: message.message_id, + kind: MessageBusEventKind::Notification, + notification_user_id: Some(notification_user_id), + all_unread_notifications_count: message + .data + .get("all_unread_notifications_count") + .and_then(|value| integer_u32(Some(value))), + unread_notifications: message + .data + .get("unread_notifications") + .and_then(|value| integer_u32(Some(value))), + unread_high_priority_notifications: message + .data + .get("unread_high_priority_notifications") + .and_then(|value| integer_u32(Some(value))), + payload_json, + ..MessageBusEvent::default() + }; + } + + if let Some(notification_user_id) = notification_alert_user_id_from_channel(&message.channel) { + return MessageBusEvent { + channel: message.channel.clone(), + message_id: message.message_id, + kind: MessageBusEventKind::NotificationAlert, + notification_user_id: Some(notification_user_id), + payload_json, + ..MessageBusEvent::default() + }; + } + + if message.channel.starts_with("/chat/") || message.channel == "/chat" { + return MessageBusEvent { + channel: message.channel.clone(), + message_id: message.message_id, + kind: MessageBusEventKind::Chat, + // Reuse topic_id slot for chat channel id when the path encodes one + // (`/chat/{id}`, `/chat/{id}/new-messages`, `/chat/{id}/thread/{tid}`). + topic_id: chat_channel_id_from_channel(&message.channel), + detail_event_type: message + .data + .get("type") + .and_then(Value::as_str) + .map(ToOwned::to_owned), + message_type: message + .data + .get("type") + .and_then(Value::as_str) + .map(ToOwned::to_owned), + payload_json, + ..MessageBusEvent::default() + }; + } + + MessageBusEvent { + channel: message.channel.clone(), + message_id: message.message_id, + kind: MessageBusEventKind::Unknown, + payload_json, + ..MessageBusEvent::default() + } +} + diff --git a/rust/crates/fire-core/src/core/messagebus/poll.rs b/rust/crates/fire-core/src/core/messagebus/poll.rs new file mode 100644 index 00000000..25b237fe --- /dev/null +++ b/rust/crates/fire-core/src/core/messagebus/poll.rs @@ -0,0 +1,639 @@ +use std::sync::{ + atomic::Ordering, + Arc, + }; + +use fire_models::{ + MessageBusClientMode, MessageBusEvent, MessageBusEventKind, + NotificationAlertPollResult, SessionSnapshot, +}; +use http::{Method, Request, Response}; +use http_body_util::BodyExt; +use openwire::{RequestBody, ResponseBody}; +use tokio::{ + sync::watch, + task::JoinHandle, + time::{sleep, Instant}, +}; +use tracing::{debug, warn}; +use url::{form_urlencoded::Serializer, Url}; + +use super::super::{ + network::{ + classify_http_status_error, header_value, request_origin, take_trace_cancellation_guard, + FireCallProfile, FireRequestEpoch, FireRequestProfile, TracedRequest, + }, + notifications::merge_notification_event_data, + presence::merge_topic_presence_event_data, + FireCore, +}; +use super::*; +use crate::{ + diagnostics::FireDiagnosticsStore, + error::FireCoreError, + json_helpers::integer_i64, + sync_utils::read_rwlock, +}; + +use super::channels::*; +use super::parse::*; +use super::runtime::*; + +pub(super) fn ensure_poll_task_running( + core: &FireCore, + runtime: &mut FireMessageBusRuntime, +) -> Result<(), FireCoreError> { + if runtime.active_mode.is_none() || runtime.poll_task.is_some() { + return Ok(()); + } + let client_id = runtime + .active_client_id + .clone() + .or_else(|| { + runtime + .active_mode + .map(|mode| client_id_for_mode(runtime, mode)) + }) + .expect("message bus active mode should exist"); + runtime.active_client_id = Some(client_id.clone()); + runtime.poll_task = Some(spawn_poll_task(core, runtime, client_id)?); + Ok(()) +} + +pub(super) fn stop_poll_task_locked(runtime: &mut FireMessageBusRuntime) { + if let Some(task) = runtime.poll_task.take() { + task.abort(); + } +} + +pub(super) fn spawn_poll_task( + core: &FireCore, + runtime: &mut FireMessageBusRuntime, + client_id: String, +) -> Result, FireCoreError> { + let runtime_handle = runtime + .runtime_handle + .clone() + .ok_or(FireCoreError::MessageBusNotStarted)?; + let event_sender = runtime + .event_sender + .clone() + .ok_or(FireCoreError::MessageBusNotStarted)?; + let subscription_updates = subscription_updates_receiver(runtime); + runtime.poll_task_token = runtime.poll_task_token.saturating_add(1); + let task_token = runtime.poll_task_token; + let mode = runtime + .active_mode + .ok_or(FireCoreError::MessageBusNotStarted)?; + let context = MessageBusPollContext { + core: core.clone(), + base_url: core.base_url.clone(), + network: core.network.clone(), + diagnostics: Arc::clone(&core.diagnostics), + session: Arc::clone(&core.session), + runtime: Arc::clone(&core.message_bus), + notifications: Arc::clone(&core.notifications), + topic_presence: Arc::clone(&core.topic_presence), + event_sender, + client_id, + mode, + task_token, + }; + Ok(runtime_handle.spawn(async move { + run_message_bus_poll_loop(context, subscription_updates).await; + })) +} + +async fn run_message_bus_poll_loop( + context: MessageBusPollContext, + mut subscription_updates: watch::Receiver, +) { + let mut failure_count = 0_u32; + + loop { + let (subscriptions, subscription_revision) = { + let runtime = context + .runtime + .lock() + .expect("message bus runtime lock poisoned"); + if runtime.active_client_id.as_deref() != Some(context.client_id.as_str()) { + break; + } + ( + runtime + .subscriptions + .iter() + .map(|(channel, entry)| (channel.clone(), entry.last_message_id)) + .collect::>(), + runtime.subscription_revision, + ) + }; + + if subscriptions.is_empty() { + if !wait_for_subscription_change(&context, &mut subscription_updates).await { + break; + } + continue; + } + + match execute_poll_once_with_subscription_changes( + &context, + &mut subscription_updates, + &subscriptions, + subscription_revision, + ) + .await + { + Ok(PollIterationResult::Continue) => { + failure_count = 0; + } + Ok(PollIterationResult::Restart) => { + failure_count = 0; + } + Ok(PollIterationResult::Stop) => break, + Err(error) => { + if is_expected_long_poll_timeout(&error) { + debug!( + client_id = %context.client_id, + error = %error, + "message bus poll timed out; continuing without backoff" + ); + failure_count = 0; + continue; + } + + log_message_bus_poll_failure(&context.client_id, &error); + failure_count = failure_count.saturating_add(1); + let delay = backoff_delay(failure_count); + sleep(delay).await; + } + } + } + + clear_poll_task_on_exit(&context.runtime, &context.client_id, context.task_token); +} + +async fn wait_for_subscription_change( + context: &MessageBusPollContext, + subscription_updates: &mut watch::Receiver, +) -> bool { + match subscription_updates.changed().await { + Ok(_) => { + context + .runtime + .lock() + .expect("message bus runtime lock poisoned") + .active_client_id + .as_deref() + == Some(context.client_id.as_str()) + } + Err(_) => false, + } +} + +async fn execute_poll_once_with_subscription_changes( + context: &MessageBusPollContext, + subscription_updates: &mut watch::Receiver, + subscriptions: &[(String, i64)], + subscription_revision: u64, +) -> Result { + let poll_started_at = Instant::now(); + let poll = execute_poll_once(context, subscriptions); + tokio::pin!(poll); + let mut pending_restart = false; + + loop { + if pending_restart { + let remaining = + MESSAGE_BUS_MIN_RESTART_INTERVAL.saturating_sub(poll_started_at.elapsed()); + if remaining.is_zero() { + return Ok(PollIterationResult::Restart); + } + + tokio::select! { + result = &mut poll => { + return result.map(|keep_running| { + if keep_running { + PollIterationResult::Continue + } else { + PollIterationResult::Stop + } + }); + } + changed = subscription_updates.changed() => { + if changed.is_err() { + return Ok(PollIterationResult::Stop); + } + pending_restart |= *subscription_updates.borrow() != subscription_revision; + } + _ = sleep(remaining) => { + return Ok(PollIterationResult::Restart); + } + } + } else { + tokio::select! { + result = &mut poll => { + return result.map(|keep_running| { + if keep_running { + PollIterationResult::Continue + } else { + PollIterationResult::Stop + } + }); + } + changed = subscription_updates.changed() => { + if changed.is_err() { + return Ok(PollIterationResult::Stop); + } + pending_restart = *subscription_updates.borrow() != subscription_revision; + } + } + } + } +} + +async fn execute_poll_once( + context: &MessageBusPollContext, + subscriptions: &[(String, i64)], +) -> Result { + let traced = build_message_bus_poll_request(context, subscriptions)?; + debug!( + trace_id = traced.trace_id, + client_id = %context.client_id, + subscriptions = subscriptions.len(), + "executing message bus poll request" + ); + let (trace_id, response) = context + .network + .execute_traced(traced, FireCallProfile::MessageBusPoll) + .await?; + + if !response.status().is_success() { + return read_message_bus_error_response(context, trace_id, response).await; + } + + read_message_bus_success_response(context, trace_id, response).await +} + +pub(super) fn build_message_bus_poll_request( + context: &MessageBusPollContext, + subscriptions: &[(String, i64)], +) -> Result { + let state = read_rwlock(&context.session, "session"); + build_message_bus_poll_request_for_snapshot( + &context.diagnostics, + &context.base_url, + &state.snapshot, + state.epoch, + &context.client_id, + context.mode, + subscriptions, + ) +} + +pub(super) fn build_message_bus_poll_request_for_snapshot( + diagnostics: &Arc, + base_url: &Url, + snapshot: &SessionSnapshot, + epoch: u64, + client_id: &str, + mode: MessageBusClientMode, + subscriptions: &[(String, i64)], +) -> Result { + let poll_base_url = message_bus_poll_base_url(base_url, &snapshot.bootstrap)?; + let uri = poll_base_url.join(&format!("/message-bus/{client_id}/poll"))?; + let same_origin = request_origin(base_url) == request_origin(&poll_base_url); + + let mut serializer = Serializer::new(String::new()); + for (channel, last_message_id) in subscriptions { + serializer.append_pair(channel, &last_message_id.to_string()); + } + let sequence = MESSAGE_BUS_SEQUENCE_COUNTER.fetch_add(1, Ordering::SeqCst); + serializer.append_pair("__seq", &sequence.to_string()); + + let mut builder = Request::builder() + .method(Method::POST) + .uri(uri.as_str()) + .header("Accept", "text/plain, */*; q=0.01") + .header( + "Content-Type", + "application/x-www-form-urlencoded; charset=UTF-8", + ) + .header("X-SILENCE-LOGGER", "true") + .header("Dont-Chunk", "true"); + + if mode == MessageBusClientMode::IosBackground { + builder = builder.header("Discourse-Background", "true"); + } + + if !same_origin { + let shared_session_key = snapshot + .bootstrap + .shared_session_key + .as_ref() + .ok_or(FireCoreError::MissingSharedSessionKey)?; + builder = builder.header("X-Shared-Session-Key", shared_session_key); + } + + let mut request = builder + .body(RequestBody::from(serializer.finish())) + .map_err(FireCoreError::RequestBuild)?; + request + .extensions_mut() + .insert(FireRequestProfile::MessageBusPoll); + request.extensions_mut().insert(FireRequestEpoch(epoch)); + let trace_id = diagnostics.prepare_request_trace(MESSAGE_BUS_OPERATION, &mut request); + Ok(TracedRequest { + trace_id, + operation: MESSAGE_BUS_OPERATION, + request, + }) +} + +async fn read_message_bus_error_response( + context: &MessageBusPollContext, + trace_id: u64, + response: Response, +) -> Result { + read_message_bus_error_response_for_diagnostics(&context.diagnostics, trace_id, response).await +} + +pub(super) async fn read_message_bus_error_response_for_diagnostics( + diagnostics: &Arc, + trace_id: u64, + response: Response, +) -> Result { + let mut response = response; + let _trace_guard = take_trace_cancellation_guard(&mut response).unwrap_or_else(|| { + diagnostics.cancellation_guard( + trace_id, + "Request cancelled", + "Future dropped while reading the message bus error response body", + ) + }); + let status = response.status().as_u16(); + let response_headers = response.headers().clone(); + let body = match response.into_body().text().await { + Ok(body) => body, + Err(source) => { + diagnostics.record_call_failed(trace_id, &source); + return Err(FireCoreError::Network { source }); + } + }; + diagnostics.record_http_status_error(trace_id, status, &body); + Err(classify_http_status_error( + MESSAGE_BUS_OPERATION, + status, + &response_headers, + body, + )) +} + +async fn read_message_bus_success_response( + context: &MessageBusPollContext, + trace_id: u64, + response: Response, +) -> Result { + let mut response = response; + let _trace_guard = take_trace_cancellation_guard(&mut response).unwrap_or_else(|| { + context.diagnostics.cancellation_guard( + trace_id, + "Request cancelled", + "Future dropped while processing the message bus response body", + ) + }); + let content_type = header_value(response.headers(), "content-type"); + let mut body = response.into_body(); + let mut response_text = String::new(); + let mut chunk_buffer = String::new(); + + while let Some(frame) = body.frame().await { + let frame = match frame { + Ok(frame) => frame, + Err(source) => { + context.diagnostics.record_call_failed(trace_id, &source); + return Err(FireCoreError::Network { source }); + } + }; + let Ok(bytes) = frame.into_data() else { + continue; + }; + let text = String::from_utf8_lossy(&bytes); + response_text.push_str(&text); + chunk_buffer.push_str(&text); + + while let Some(delimiter) = chunk_buffer.find('|') { + let chunk = chunk_buffer[..delimiter].trim().to_string(); + chunk_buffer = chunk_buffer[delimiter + 1..].to_string(); + if !chunk.is_empty() && !process_chunk(context, &chunk)? { + context.diagnostics.record_response_body_text( + trace_id, + &response_text, + content_type.as_deref(), + ); + return Ok(false); + } + } + } + + if !chunk_buffer.trim().is_empty() && !process_chunk(context, chunk_buffer.trim())? { + context.diagnostics.record_response_body_text( + trace_id, + &response_text, + content_type.as_deref(), + ); + return Ok(false); + } + + context.diagnostics.record_response_body_text( + trace_id, + &response_text, + content_type.as_deref(), + ); + Ok(true) +} + +pub(super) async fn read_notification_alert_success_response( + diagnostics: &Arc, + trace_id: u64, + response: Response, + notification_user_id: u64, + client_id: &str, + channel: &str, + initial_last_message_id: i64, +) -> Result { + let mut response = response; + let _trace_guard = take_trace_cancellation_guard(&mut response).unwrap_or_else(|| { + diagnostics.cancellation_guard( + trace_id, + "Request cancelled", + "Future dropped while processing the notification alert response body", + ) + }); + let content_type = header_value(response.headers(), "content-type"); + let mut body = response.into_body(); + let mut response_text = String::new(); + let mut chunk_buffer = String::new(); + let mut result = NotificationAlertPollResult { + notification_user_id, + client_id: client_id.to_string(), + last_message_id: initial_last_message_id, + alerts: Vec::new(), + }; + + while let Some(frame) = body.frame().await { + let frame = match frame { + Ok(frame) => frame, + Err(source) => { + diagnostics.record_call_failed(trace_id, &source); + return Err(FireCoreError::Network { source }); + } + }; + let Ok(bytes) = frame.into_data() else { + continue; + }; + let text = String::from_utf8_lossy(&bytes); + response_text.push_str(&text); + chunk_buffer.push_str(&text); + + while let Some(delimiter) = chunk_buffer.find('|') { + let chunk = chunk_buffer[..delimiter].trim().to_string(); + chunk_buffer = chunk_buffer[delimiter + 1..].to_string(); + if !chunk.is_empty() { + process_notification_alert_chunk(&mut result, channel, client_id, &chunk); + } + } + } + + if !chunk_buffer.trim().is_empty() { + process_notification_alert_chunk(&mut result, channel, client_id, chunk_buffer.trim()); + } + + diagnostics.record_response_body_text(trace_id, &response_text, content_type.as_deref()); + Ok(result) +} + +pub(super) fn process_notification_alert_chunk( + result: &mut NotificationAlertPollResult, + channel: &str, + client_id: &str, + chunk: &str, +) { + let Some(messages) = + parse_message_bus_messages(chunk, client_id, "background notification-alert") + else { + return; + }; + + for message in messages { + if message.channel == "/__status" { + if let Some(last_message_id) = message + .data + .get(channel) + .and_then(|value| integer_i64(Some(value))) + { + result.last_message_id = result.last_message_id.max(last_message_id); + } + continue; + } + + if message.channel != channel { + continue; + } + + result.last_message_id = result.last_message_id.max(message.message_id); + result.alerts.push(notification_alert_from_raw(&message)); + } +} + +pub(super) fn process_chunk(context: &MessageBusPollContext, chunk: &str) -> Result { + let Some(messages) = parse_message_bus_messages(chunk, &context.client_id, "message bus") + else { + return Ok(true); + }; + + for message in messages { + if message.channel == "/__status" { + apply_status_message(&context.runtime, &message.data); + continue; + } + + update_channel_checkpoint(&context.runtime, &message.channel, message.message_id); + if let Some(user_id) = logout_user_id_from_channel(&message.channel) { + if context.core.handle_server_forced_logout(user_id) { + let event = MessageBusEvent { + channel: message.channel.clone(), + message_id: message.message_id, + kind: MessageBusEventKind::SessionLogout, + notification_user_id: Some(user_id), + payload_json: serde_json::to_string(&message.data) + .ok() + .filter(|value| value != "null"), + ..MessageBusEvent::default() + }; + if context.event_sender.send(event).is_err() { + warn!("message bus listener dropped; stopping poll loop"); + return Ok(false); + } + } + continue; + } + if notification_user_id_from_channel(&message.channel).is_some() { + merge_notification_event_data(&context.notifications, &message.data); + } + if let Some(topic_id) = presence_topic_id_from_channel(&message.channel) { + merge_topic_presence_event_data( + &context.topic_presence, + topic_id, + message.message_id, + &message.data, + ); + } + let event = message_bus_event_from_raw(&message); + let listeners = { + let runtime = context + .runtime + .lock() + .expect("message bus runtime lock poisoned"); + runtime.internal_listeners.clone() + }; + for listener in listeners { + let event = event.clone(); + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + (listener.on_event)(&event); + })); + } + if context.event_sender.send(event).is_err() { + warn!("message bus listener dropped; stopping poll loop"); + return Ok(false); + } + } + + Ok(true) +} + + +#[cfg(test)] +mod tests { + use openwire::WireError; + + use super::*; + + #[test] + fn call_timeout_is_treated_as_expected_long_poll_timeout() { + let error = FireCoreError::Network { + source: WireError::timeout("call timed out after 75s"), + }; + + assert!(is_expected_long_poll_timeout(&error)); + } + + #[test] + fn connect_timeout_is_not_treated_as_expected_long_poll_timeout() { + let error = FireCoreError::Network { + source: WireError::connect_timeout("connect timed out after 10s"), + }; + + assert!(!is_expected_long_poll_timeout(&error)); + } +} diff --git a/rust/crates/fire-core/src/core/messagebus/runtime.rs b/rust/crates/fire-core/src/core/messagebus/runtime.rs new file mode 100644 index 00000000..652995a1 --- /dev/null +++ b/rust/crates/fire-core/src/core/messagebus/runtime.rs @@ -0,0 +1,559 @@ +use std::{ + collections::{BTreeMap, HashMap}, + sync::{ + atomic::Ordering, + Arc, Mutex, + }, + time::{Duration, SystemTime, UNIX_EPOCH}, +}; + +use fire_models::{ + BootstrapArtifacts, MessageBusClientMode, MessageBusEvent, + MessageBusSubscription, MessageBusSubscriptionScope, + NotificationAlertPollResult, +}; +use http_body_util::BodyExt; +use openwire::WireErrorKind; +use serde_json::Value; +use tokio::{ + runtime::Handle, + sync::{mpsc::UnboundedSender, watch}, +}; +use tracing::{debug, info, warn}; +use url::Url; + +use super::super::{ + network::{ + request_origin, + FireCallProfile, + }, + presence::clear_topic_presence_snapshot, + FireCore, +}; +use super::channels::*; +use super::poll::*; +use super::*; +use crate::{ + error::FireCoreError, + json_helpers::integer_i64, +}; + +impl FireCore { + pub fn subscribe_message_bus_channel( + &self, + subscription: MessageBusSubscription, + ) -> Result<(), FireCoreError> { + let snapshot = self.snapshot(); + let mut runtime = self + .message_bus + .lock() + .expect("message bus runtime lock poisoned"); + let mut changed = ensure_bootstrap_subscriptions(&snapshot.bootstrap, &mut runtime); + + let last_message_id = subscription.last_message_id.unwrap_or_else(|| { + bootstrap_message_id_for_channel(&snapshot.bootstrap, &subscription.channel) + .unwrap_or(INITIAL_MESSAGE_ID) + }); + changed |= upsert_runtime_subscription_owner( + &mut runtime, + subscription.owner_token, + subscription.channel, + last_message_id, + subscription.scope, + ); + + if changed { + mark_subscriptions_changed(&mut runtime); + ensure_poll_task_running(self, &mut runtime)?; + } + Ok(()) + } + + pub fn unsubscribe_message_bus_channel( + &self, + owner_token: String, + channel: String, + ) -> Result<(), FireCoreError> { + let mut runtime = self + .message_bus + .lock() + .expect("message bus runtime lock poisoned"); + if remove_runtime_subscription_owner(&mut runtime, &owner_token, &channel) { + let removed_presence_topic_id = presence_topic_id_from_channel(&channel); + mark_subscriptions_changed(&mut runtime); + ensure_poll_task_running(self, &mut runtime)?; + if let Some(topic_id) = removed_presence_topic_id { + // Keep the message bus lock until the cached snapshot is evicted so a + // concurrent re-subscribe cannot reintroduce the same topic between steps. + clear_topic_presence_snapshot(&self.topic_presence, topic_id); + } + } + Ok(()) + } + + pub async fn start_message_bus( + &self, + mode: MessageBusClientMode, + event_sender: UnboundedSender, + topic_tracking_state_meta: Option>, + ) -> Result { + let snapshot = self.snapshot(); + if !snapshot.cookies.can_authenticate_requests() { + return Err(FireCoreError::MissingLoginSession); + } + if message_bus_requires_shared_session_key(&self.base_url, &snapshot.bootstrap)? + && snapshot.bootstrap.shared_session_key.is_none() + { + return Err(FireCoreError::MissingSharedSessionKey); + } + + let runtime_handle = Handle::current(); + let mut runtime = self + .message_bus + .lock() + .expect("message bus runtime lock poisoned"); + let mut bootstrap_changed = + ensure_bootstrap_subscriptions(&snapshot.bootstrap, &mut runtime); + if let Some(meta) = topic_tracking_state_meta { + bootstrap_changed |= apply_topic_tracking_state_meta(&meta, &mut runtime); + } + if bootstrap_changed { + mark_subscriptions_changed(&mut runtime); + } + + stop_poll_task_locked(&mut runtime); + runtime.active_mode = Some(mode); + runtime.runtime_handle = Some(runtime_handle); + runtime.event_sender = Some(event_sender); + + let client_id = client_id_for_mode(&mut runtime, mode); + runtime.active_client_id = Some(client_id.clone()); + + runtime.poll_task = Some(spawn_poll_task(self, &mut runtime, client_id.clone())?); + + info!( + client_id = %client_id, + mode = ?mode, + subscriptions = runtime.subscriptions.len(), + idle = runtime.subscriptions.is_empty(), + "message bus started" + ); + let listeners = runtime.internal_listeners.clone(); + drop(runtime); + for listener in listeners { + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + (listener.on_started)(); + })); + } + Ok(client_id) + } + + pub fn stop_message_bus(&self, clear_subscriptions: bool) { + let mut runtime = self + .message_bus + .lock() + .expect("message bus runtime lock poisoned"); + stop_poll_task_locked(&mut runtime); + runtime.active_client_id = None; + runtime.active_mode = None; + runtime.event_sender = None; + runtime.runtime_handle = None; + if clear_subscriptions { + runtime.subscriptions.clear(); + runtime.foreground_client_id = None; + } + let listeners = runtime.internal_listeners.clone(); + drop(runtime); + for listener in listeners { + let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + (listener.on_stopped)(); + })); + } + } + + pub(crate) fn add_message_bus_internal_listener( + &self, + on_event: std::sync::Arc, + on_stopped: std::sync::Arc, + on_started: std::sync::Arc, + ) -> u64 { + let mut runtime = self + .message_bus + .lock() + .expect("message bus runtime lock poisoned"); + runtime.next_internal_listener_id = runtime + .next_internal_listener_id + .saturating_add(1) + .max(1); + let id = runtime.next_internal_listener_id; + runtime + .internal_listeners + .push(MessageBusInternalListener { + id, + on_event, + on_stopped, + on_started, + }); + id + } + + pub(crate) fn remove_message_bus_internal_listener(&self, id: u64) { + let mut runtime = self + .message_bus + .lock() + .expect("message bus runtime lock poisoned"); + runtime + .internal_listeners + .retain(|listener| listener.id != id); + } + + pub async fn poll_notification_alert_once( + &self, + last_message_id: i64, + ) -> Result { + let snapshot = self.snapshot(); + if !snapshot.cookies.can_authenticate_requests() { + return Err(FireCoreError::MissingLoginSession); + } + if message_bus_requires_shared_session_key(&self.base_url, &snapshot.bootstrap)? + && snapshot.bootstrap.shared_session_key.is_none() + { + return Err(FireCoreError::MissingSharedSessionKey); + } + + let notification_user_id = snapshot + .bootstrap + .current_user_id + .ok_or(FireCoreError::MissingCurrentUserId)?; + let channel = format!("/notification-alert/{notification_user_id}"); + let client_id = generate_ios_background_client_id(); + let traced = build_message_bus_poll_request_for_snapshot( + &self.diagnostics, + &self.base_url, + &snapshot, + self.snapshot_with_epoch().1, + &client_id, + MessageBusClientMode::IosBackground, + &[(channel.clone(), last_message_id)], + )?; + debug!( + trace_id = traced.trace_id, + client_id = %client_id, + channel = %channel, + last_message_id, + "executing background notification-alert poll request" + ); + let (trace_id, response) = self + .network + .execute_traced(traced, FireCallProfile::MessageBusPoll) + .await?; + + if !response.status().is_success() { + match read_message_bus_error_response_for_diagnostics( + &self.diagnostics, + trace_id, + response, + ) + .await + { + Err(error) => return Err(error), + Ok(_) => unreachable!("message bus error response should not succeed"), + } + } + + read_notification_alert_success_response( + &self.diagnostics, + trace_id, + response, + notification_user_id, + &client_id, + &channel, + last_message_id, + ) + .await + } +} + + +fn ensure_bootstrap_subscriptions( + bootstrap: &BootstrapArtifacts, + runtime: &mut FireMessageBusRuntime, +) -> bool { + let mut changed = false; + + for (channel, last_message_id) in bootstrap_tracking_subscriptions(bootstrap) { + changed |= upsert_runtime_subscription_owner( + runtime, + BOOTSTRAP_TRACKING_OWNER_TOKEN.to_string(), + channel, + last_message_id, + MessageBusSubscriptionScope::Durable, + ); + } + + if let (Some(user_id), Some(last_message_id)) = ( + bootstrap.current_user_id, + bootstrap.notification_channel_position, + ) { + changed |= upsert_runtime_subscription_owner( + runtime, + BOOTSTRAP_NOTIFICATION_OWNER_TOKEN.to_string(), + format!("/notification/{user_id}"), + last_message_id, + MessageBusSubscriptionScope::Durable, + ); + } + + if let Some(user_id) = bootstrap.current_user_id.filter(|id| *id > 0) { + let channel = format!("/logout/{user_id}"); + let last_message_id = + bootstrap_message_id_for_channel(bootstrap, &channel).unwrap_or(INITIAL_MESSAGE_ID); + changed |= upsert_runtime_subscription_owner( + runtime, + BOOTSTRAP_LOGOUT_OWNER_TOKEN.to_string(), + channel, + last_message_id, + MessageBusSubscriptionScope::Durable, + ); + } + + changed +} + +pub(super) fn bootstrap_tracking_subscriptions(bootstrap: &BootstrapArtifacts) -> Vec<(String, i64)> { + let Some(raw) = bootstrap.topic_tracking_state_meta.as_deref() else { + return Vec::new(); + }; + let Ok(value) = serde_json::from_str::(raw) else { + return Vec::new(); + }; + let Some(object) = value.as_object() else { + return Vec::new(); + }; + + object + .iter() + .filter_map(|(channel, value)| { + if !channel.starts_with('/') { + return None; + } + integer_i64(Some(value)).map(|last_message_id| (channel.clone(), last_message_id)) + }) + .collect() +} + +pub(super) fn apply_topic_tracking_state_meta( + meta: &HashMap, + runtime: &mut FireMessageBusRuntime, +) -> bool { + let mut changed = false; + for (channel, last_message_id) in meta { + if !channel.starts_with('/') { + continue; + } + changed |= upsert_runtime_subscription_owner( + runtime, + BOOTSTRAP_TRACKING_OWNER_TOKEN.to_string(), + channel.clone(), + *last_message_id, + MessageBusSubscriptionScope::Durable, + ); + } + changed +} + +pub(super) fn bootstrap_message_id_for_channel(bootstrap: &BootstrapArtifacts, channel: &str) -> Option { + if let Some(notification_channel) = bootstrap_notification_channel(bootstrap) { + if notification_channel.0 == channel { + return Some(notification_channel.1); + } + } + + bootstrap_tracking_subscriptions(bootstrap) + .into_iter() + .find_map(|(known_channel, last_message_id)| { + (known_channel == channel).then_some(last_message_id) + }) +} + +pub(super) fn bootstrap_notification_channel(bootstrap: &BootstrapArtifacts) -> Option<(String, i64)> { + Some(( + format!("/notification/{}", bootstrap.current_user_id?), + bootstrap.notification_channel_position?, + )) +} + +pub(super) fn client_id_for_mode(runtime: &mut FireMessageBusRuntime, mode: MessageBusClientMode) -> String { + match mode { + MessageBusClientMode::Foreground => runtime + .foreground_client_id + .get_or_insert_with(generate_foreground_client_id) + .clone(), + MessageBusClientMode::IosBackground => generate_ios_background_client_id(), + } +} + +pub(super) fn generate_foreground_client_id() -> String { + let counter = FOREGROUND_CLIENT_COUNTER.fetch_add(1, Ordering::SeqCst); + format!("fire_{:x}{:x}", now_unix_ms(), counter) +} + +pub(super) fn generate_ios_background_client_id() -> String { + format!("ios_bg_{}", now_unix_ms()) +} + +pub(super) fn now_unix_ms() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|duration| duration.as_millis() as u64) + .unwrap_or_default() +} + +pub(super) fn backoff_delay(failure_count: u32) -> Duration { + let exponent = failure_count.saturating_sub(1).min(4); + let seconds = 2_u64.saturating_pow(exponent); + let base_delay = Duration::from_secs(seconds).min(MAX_BACKOFF_DELAY); + let base_delay_ms = base_delay.as_millis() as u64; + let jitter_window_ms = base_delay_ms / 4; + if jitter_window_ms == 0 { + return base_delay; + } + + let jitter_seed = now_unix_ms() + ^ u64::from(failure_count) + ^ FOREGROUND_CLIENT_COUNTER.load(Ordering::Relaxed); + let jitter_ms = jitter_seed % (jitter_window_ms.saturating_mul(2) + 1); + let delay_ms = base_delay_ms + .saturating_sub(jitter_window_ms) + .saturating_add(jitter_ms); + Duration::from_millis(delay_ms).min(MAX_BACKOFF_DELAY) +} + +pub(super) fn upsert_runtime_subscription_owner( + runtime: &mut FireMessageBusRuntime, + owner_token: String, + channel: String, + last_message_id: i64, + scope: MessageBusSubscriptionScope, +) -> bool { + let owner_key = owner_token; + let mut is_new_channel = false; + let entry = runtime.subscriptions.entry(channel).or_insert_with(|| { + is_new_channel = true; + RuntimeSubscription { + last_message_id, + owners: BTreeMap::new(), + } + }); + let previous_last_message_id = entry.last_message_id; + entry.last_message_id = entry.last_message_id.max(last_message_id); + entry + .owners + .insert(owner_key.clone(), RuntimeSubscriptionOwner { scope }); + is_new_channel || entry.last_message_id != previous_last_message_id +} + +pub(super) fn remove_runtime_subscription_owner( + runtime: &mut FireMessageBusRuntime, + owner_token: &str, + channel: &str, +) -> bool { + let Some(entry) = runtime.subscriptions.get_mut(channel) else { + return false; + }; + + let removed = entry.owners.remove(owner_token).is_some(); + if !removed { + return false; + } + + if entry.owners.is_empty() { + runtime.subscriptions.remove(channel); + return true; + } + + false +} + +pub(super) fn mark_subscriptions_changed(runtime: &mut FireMessageBusRuntime) { + runtime.subscription_revision = runtime.subscription_revision.saturating_add(1); + if let Some(sender) = &runtime.subscription_updates { + let _ = sender.send(runtime.subscription_revision); + } +} + +pub(super) fn subscription_updates_receiver(runtime: &mut FireMessageBusRuntime) -> watch::Receiver { + if let Some(sender) = &runtime.subscription_updates { + sender.subscribe() + } else { + let (sender, receiver) = watch::channel(runtime.subscription_revision); + runtime.subscription_updates = Some(sender); + receiver + } +} + +pub(super) fn is_expected_long_poll_timeout(error: &FireCoreError) -> bool { + matches!( + error, + FireCoreError::Network { source } + if source.kind() == WireErrorKind::Timeout && !source.is_connect_timeout() + ) +} + +pub(super) fn log_message_bus_poll_failure(client_id: &str, error: &FireCoreError) { + match error { + FireCoreError::HttpStatus { status, .. } if matches!(status, 429 | 502 | 503 | 504) => { + let category = match status { + 429 => "rate_limited", + _ => "server_unavailable", + }; + warn!( + client_id = %client_id, + status = *status, + category, + error = %error, + "message bus poll iteration failed" + ); + } + _ => { + warn!( + client_id = %client_id, + error = %error, + "message bus poll iteration failed" + ); + } + } +} + +pub(super) fn clear_poll_task_on_exit( + runtime: &Arc>, + client_id: &str, + task_token: u64, +) { + let mut runtime = runtime.lock().expect("message bus runtime lock poisoned"); + if runtime.active_client_id.as_deref() == Some(client_id) + && runtime.poll_task_token == task_token + { + runtime.poll_task = None; + } +} + +pub(super) fn message_bus_poll_base_url( + base_url: &Url, + bootstrap: &BootstrapArtifacts, +) -> Result { + match bootstrap.long_polling_base_url.as_deref() { + Some(long_polling_base_url) if !long_polling_base_url.is_empty() => { + Url::parse(long_polling_base_url).map_err(Into::into) + } + _ => Ok(base_url.clone()), + } +} + +pub(crate) fn message_bus_requires_shared_session_key( + base_url: &Url, + bootstrap: &BootstrapArtifacts, +) -> Result { + let poll_base_url = message_bus_poll_base_url(base_url, bootstrap)?; + Ok(request_origin(base_url) != request_origin(&poll_base_url)) +} diff --git a/rust/crates/fire-core/src/core/mod.rs b/rust/crates/fire-core/src/core/mod.rs index 2523c063..57908853 100644 --- a/rust/crates/fire-core/src/core/mod.rs +++ b/rust/crates/fire-core/src/core/mod.rs @@ -17,9 +17,15 @@ mod presence; mod rate_limit; mod search; mod session; +mod topic_detail_project; +mod topic_detail; mod topics; mod users; +pub use topic_detail::{ + TopicDetailObserver, TopicDetailOpenRequest, TopicDetailSession, TopicDetailSessionRegistry, +}; + use std::{ fs, path::{Path, PathBuf}, @@ -139,6 +145,8 @@ pub(crate) struct FireSessionRuntimeState { pub(crate) last_response_auth_change: Option, pub(crate) auth_strike: auth_strike::AuthStrikeState, pub(crate) last_auth_runtime_signal: Option, + pub(crate) read_path_login_request: Option, + pub(crate) read_path_login_generation: u64, } #[derive(Clone)] @@ -154,6 +162,7 @@ pub struct FireCore { topic_presence: Arc>, topic_timing: Arc>, topic_detail_source: Arc>, + pub(crate) topic_detail_sessions: Arc, pub(crate) shared_store: Arc>, home_topic_list_scope: Arc>, state_observers: FireStateObserverRegistry, @@ -189,6 +198,7 @@ impl FireCore { ..BootstrapArtifacts::default() }, browser_user_agent: None, + read_path_login_request: None, }, epoch: 1, snapshot_revision: 1, @@ -197,6 +207,8 @@ impl FireCore { last_response_auth_change: None, auth_strike: auth_strike::AuthStrikeState::default(), last_auth_runtime_signal: None, + read_path_login_request: None, + read_path_login_generation: 0, }; let session = Arc::new(RwLock::new(session)); let shared_store = open_shared_store(workspace_path.as_deref())?; @@ -233,6 +245,7 @@ impl FireCore { topic_detail_source: Arc::new(Mutex::new( topics::FireTopicDetailSourceRuntime::default(), )), + topic_detail_sessions: Arc::new(TopicDetailSessionRegistry::default()), shared_store, home_topic_list_scope: Arc::new(Mutex::new(HomeTopicListScope::default())), state_observers: FireStateObserverRegistry::default(), @@ -706,7 +719,7 @@ fn update_session_persistence_revisions( session: &mut FireSessionRuntimeState, before_snapshot: &SessionSnapshot, ) { - if session.snapshot != *before_snapshot { + if persistence_snapshot_changed(before_snapshot, &session.snapshot) { session.snapshot_revision = session.snapshot_revision.saturating_add(1); } @@ -715,6 +728,12 @@ fn update_session_persistence_revisions( } } +fn persistence_snapshot_changed(before: &SessionSnapshot, after: &SessionSnapshot) -> bool { + before.cookies != after.cookies + || before.bootstrap != after.bootstrap + || before.browser_user_agent != after.browser_user_agent +} + fn auth_cookie_persistence_changed( before_snapshot: &SessionSnapshot, after_snapshot: &SessionSnapshot, diff --git a/rust/crates/fire-core/src/core/persistence.rs b/rust/crates/fire-core/src/core/persistence.rs index 9c30dcb2..d38b251f 100644 --- a/rust/crates/fire-core/src/core/persistence.rs +++ b/rust/crates/fire-core/src/core/persistence.rs @@ -37,6 +37,8 @@ impl FireCore { session.snapshot = snapshot; update_session_persistence_revisions(&mut session, &before_snapshot); session.auth_recovery_hint = None; + session.read_path_login_request = None; + session.snapshot.read_path_login_request = None; session.last_response_auth_change = None; debug!( phase = ?session.snapshot.login_phase(), diff --git a/rust/crates/fire-core/src/core/topic_detail/actor.rs b/rust/crates/fire-core/src/core/topic_detail/actor.rs new file mode 100644 index 00000000..dc725daa --- /dev/null +++ b/rust/crates/fire-core/src/core/topic_detail/actor.rs @@ -0,0 +1,425 @@ +use std::collections::{HashMap, HashSet}; + +use fire_models::TopicDetailPhase; +use tokio::sync::mpsc; + +use super::super::FireCore; +use super::*; +use super::bus::presence_channel; + +impl ActorState { + pub(super) fn new(topic_id: u64) -> Self { + Self { + topic_id, + owners: HashMap::new(), + slug_hint: None, + generation: 0, + collection_revision: 0, + chrome_revision: 0, + sidecar_revision: 0, + interaction_revision: 0, + phase: TopicDetailPhase::Loading, + load_error: None, + notice: None, + scroll_target: None, + scroll_exhausted: false, + window: TopicWindow { + requested: 0..0, + anchor: None, + }, + scroll_active: false, + deferred: DeferredRefresh::None, + defer_publish: false, + refresh_inflight: false, + loading_more: false, + load_more_error: None, + summary: None, + summary_loading: false, + summary_error: None, + typing_users: Vec::new(), + submitting: false, + mutating: HashSet::new(), + loading_reply_context: HashSet::new(), + reply_context: None, + flag_types: Vec::new(), + rollback: HashMap::new(), + inflight_posts: HashMap::new(), + http_epoch: 0, + visible_generation: 0, + refresh_generation: 0, + pending_visible: Vec::new(), + track_visit: true, + published: None, + header: None, + bus_listener_id: None, + bus_subscribed: false, + typing: false, + alive: true, + } + } + + pub(super) async fn handle( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + command: Command, + ) -> bool { + match command { + Command::Shutdown => { + self.alive = false; + return false; + } + Command::Flush(reply) => { + let _ = reply.send(()); + } + Command::SyncOwners { owners, open } => { + self.owners = owners; + if let Some(request) = open { + self.slug_hint = request.slug_hint.clone().or(self.slug_hint.clone()); + self.open(core, tx, request).await; + } + } + Command::CancelHttp => { + self.http_epoch = self.http_epoch.saturating_add(1); + self.refresh_inflight = false; + if self.phase == TopicDetailPhase::Loading { + if self.published.as_ref().is_some_and(|snapshot| { + snapshot.phase == TopicDetailPhase::Ready + }) { + self.phase = TopicDetailPhase::Ready; + self.load_error = None; + self.publish(core, false); + } + } + } + Command::Reload { + target_post_number, + force_load, + track_visit, + allow_suggested_unread_root, + } => { + self.scroll_target = target_post_number.or(self.scroll_target); + self.load_http( + core, + tx, + target_post_number, + force_load, + track_visit, + allow_suggested_unread_root, + false, + ) + .await; + } + Command::LoginReload { track_visit } => { + self.load_http(core, tx, None, true, track_visit, false, false) + .await; + } + Command::LoadMore => { + self.load_more(core).await; + } + Command::NoteVisible(post_numbers) => { + self.pending_visible = post_numbers; + self.visible_generation = self.visible_generation.saturating_add(1); + let generation = self.visible_generation; + let tx = tx.clone(); + tokio::spawn(async move { + tokio::time::sleep(TOPIC_DETAIL_VISIBLE_DEBOUNCE).await; + let _ = tx.send(Command::VisibleFired(generation)); + }); + } + Command::VisibleFired(generation) if generation == self.visible_generation => { + let posts = self.pending_visible.clone(); + self.hydrate_visible(core, &posts).await; + } + Command::VisibleFired(_) => {} + Command::NoteTail { + item_count, + visible_max_item, + } => { + if self.should_load_tail(item_count, visible_max_item) { + self.load_more(core).await; + } + } + Command::NoteScroll(active) => { + self.scroll_active = active; + if !active { + match std::mem::replace(&mut self.deferred, DeferredRefresh::None) { + DeferredRefresh::Ready(snapshot) => { + self.defer_publish = false; + self.publish_snapshot(core, snapshot); + } + DeferredRefresh::Pending => { + self.arm_refresh(tx); + } + DeferredRefresh::None => {} + } + } + } + Command::AckScroll(post_number) => { + if self.scroll_target == Some(post_number) { + self.scroll_target = None; + self.publish(core, false); + } + } + Command::ClearScroll => { + self.scroll_target = None; + self.scroll_exhausted = false; + self.publish(core, false); + } + Command::BeginTyping => { + self.typing = true; + let topic_id = self.topic_id; + let _ = core + .bootstrap_topic_reply_presence(topic_id, self.bus_owner()) + .await; + let _ = core.update_topic_reply_presence(topic_id, true).await; + self.refresh_presence(core); + let tx = tx.clone(); + tokio::spawn(async move { + tokio::time::sleep(TOPIC_DETAIL_PRESENCE_HEARTBEAT).await; + let _ = tx.send(Command::PresenceHeartbeat); + }); + } + Command::EndTyping => { + self.typing = false; + let _ = core + .update_topic_reply_presence(self.topic_id, false) + .await; + let _ = core.unsubscribe_message_bus_channel( + self.bus_owner(), + presence_channel(self.topic_id), + ); + self.refresh_presence(core); + } + Command::PresenceHeartbeat => { + if self.typing { + let _ = core + .update_topic_reply_presence(self.topic_id, true) + .await; + let tx = tx.clone(); + tokio::spawn(async move { + tokio::time::sleep(TOPIC_DETAIL_PRESENCE_HEARTBEAT).await; + let _ = tx.send(Command::PresenceHeartbeat); + }); + } + } + Command::BusRefresh => { + if self.scroll_active { + if self.refresh_inflight { + self.deferred = DeferredRefresh::Pending; + } else { + self.defer_publish = true; + self.load_http(core, tx, None, false, false, false, true) + .await; + } + } else { + self.arm_refresh(tx); + } + } + Command::RefreshFired(generation) if generation == self.refresh_generation => { + if self.scroll_active { + self.deferred = DeferredRefresh::Pending; + } else { + self.load_http(core, tx, None, false, false, false, true) + .await; + } + } + Command::RefreshFired(_) => {} + Command::BusStarted => { + self.subscribe_channels(core); + } + Command::RefreshPresence => { + self.refresh_presence(core); + } + Command::ReloadAi { skip_age_check } => { + self.fetch_summary(core, skip_age_check).await; + } + Command::LoadReplyContext(post_id) => { + self.load_reply_context(core, post_id).await; + } + Command::PrepareEdit { post_id, reply } => { + let _ = reply.send(self.prepare_edit(core, post_id).await); + } + Command::EnsureFlags { reply } => { + let _ = reply.send(self.ensure_flags(core).await); + } + Command::SubmitReply { + raw, + reply_to_post_number, + scroll_to_created, + reply, + } => { + let _ = reply.send( + self.submit_reply(core, tx, raw, reply_to_post_number, scroll_to_created) + .await, + ); + } + Command::CreateBoost { post_id, raw, reply } => { + let _ = reply.send(self.create_boost(core, tx, post_id, raw).await); + } + Command::DeleteBoost { + post_id, + boost_id, + reply, + } => { + let _ = reply.send(self.delete_boost(core, tx, post_id, boost_id).await); + } + Command::UpdatePost { + post_id, + raw, + edit_reason, + reply, + } => { + let _ = reply.send(self.update_post(core, tx, post_id, raw, edit_reason).await); + } + Command::DeletePost { post_id, reply } => { + let _ = reply.send(self.delete_post(core, tx, post_id).await); + } + Command::RecoverPost { post_id, reply } => { + let _ = reply.send(self.recover_post(core, tx, post_id).await); + } + Command::FlagPost { + post_id, + flag_type_id, + message, + reply, + } => { + let _ = reply.send( + self.flag_post(core, tx, post_id, flag_type_id, message) + .await, + ); + } + Command::SetLiked { + post_id, + liked, + reply, + } => { + let _ = reply.send(self.set_liked(core, post_id, liked).await); + } + Command::ToggleReaction { + post_id, + reaction_id, + reply, + } => { + let _ = reply.send(self.toggle_reaction(core, post_id, reaction_id).await); + } + Command::VotePoll { + post_id, + poll_name, + options, + reply, + } => { + let _ = reply.send(self.vote_poll(core, tx, post_id, poll_name, options).await); + } + Command::UnvotePoll { + post_id, + poll_name, + reply, + } => { + let _ = reply.send(self.unvote_poll(core, tx, post_id, poll_name).await); + } + Command::VoteTopic { voted, reply } => { + let _ = reply.send(self.vote_topic(core, tx, voted).await); + } + Command::AcceptSolution { + post_id, + accepted, + reply, + } => { + let _ = reply.send(self.accept_solution(core, tx, post_id, accepted).await); + } + Command::CreateBookmark { + bookmarkable_id, + bookmarkable_type, + name, + reminder_at, + auto_delete_preference, + reply, + } => { + let _ = reply.send( + self.create_bookmark( + core, + tx, + bookmarkable_id, + bookmarkable_type, + name, + reminder_at, + auto_delete_preference, + ) + .await, + ); + } + Command::UpdateBookmark { + bookmark_id, + name, + reminder_at, + auto_delete_preference, + reply, + } => { + let _ = reply.send( + self.update_bookmark( + core, + tx, + bookmark_id, + name, + reminder_at, + auto_delete_preference, + ) + .await, + ); + } + Command::DeleteBookmark { bookmark_id, reply } => { + let _ = reply.send(self.delete_bookmark(core, tx, bookmark_id).await); + } + Command::SetNotificationLevel { level, reply } => { + let _ = reply.send(self.set_notification_level(core, tx, level).await); + } + Command::UpdateTopic { + title, + category_id, + tags, + reply, + } => { + let _ = reply.send(self.update_topic(core, tx, title, category_id, tags).await); + } + Command::ReportTimings { + topic_time_ms, + timings, + reply, + } => { + let result = core + .report_topic_timings(fire_models::TopicTimingsRequest { + topic_id: self.topic_id, + topic_time_ms, + timings, + }) + .await + .unwrap_or(false); + let _ = reply.send(Ok(result)); + } + } + true + } + + +} + +pub(super) async fn run_actor( + core: FireCore, + topic_id: u64, + tx: mpsc::UnboundedSender, + mut rx: mpsc::UnboundedReceiver, +) { + let mut state = ActorState::new(topic_id); + state.install_bus_listener(&core, tx.clone()); + while let Some(command) = rx.recv().await { + let keep_running = state.handle(&core, &tx, command).await; + if !keep_running || !state.alive { + break; + } + } + state.unsubscribe(&core); + if let Some(id) = state.bus_listener_id.take() { + core.remove_message_bus_internal_listener(id); + } +} diff --git a/rust/crates/fire-core/src/core/topic_detail/bus.rs b/rust/crates/fire-core/src/core/topic_detail/bus.rs new file mode 100644 index 00000000..fe4a1f9f --- /dev/null +++ b/rust/crates/fire-core/src/core/topic_detail/bus.rs @@ -0,0 +1,119 @@ +use std::sync::Arc; + +use fire_models::{ + MessageBusEvent, MessageBusEventKind, MessageBusSubscription, + MessageBusSubscriptionScope, +}; +use tokio::sync::mpsc; + +use super::super::FireCore; +use super::*; + +impl ActorState { + pub(super) fn arm_refresh(&mut self, tx: &mpsc::UnboundedSender) { + self.refresh_generation = self.refresh_generation.saturating_add(1); + let generation = self.refresh_generation; + let tx = tx.clone(); + tokio::spawn(async move { + tokio::time::sleep(TOPIC_DETAIL_REFRESH_DEBOUNCE).await; + let _ = tx.send(Command::RefreshFired(generation)); + }); + } + + pub(super) fn install_bus_listener(&mut self, core: &FireCore, tx: mpsc::UnboundedSender) { + let topic_id = self.topic_id; + let on_event_tx = tx.clone(); + let on_started_tx = tx; + let id = core.add_message_bus_internal_listener( + Arc::new(move |event: &MessageBusEvent| { + if !event_matches_topic(event, topic_id) { + return; + } + match event.kind { + MessageBusEventKind::TopicDetail | MessageBusEventKind::TopicReaction => { + let _ = on_event_tx.send(Command::BusRefresh); + } + MessageBusEventKind::Presence => { + let _ = on_event_tx.send(Command::RefreshPresence); + } + _ => {} + } + }), + Arc::new(|| {}), + Arc::new(move || { + let _ = on_started_tx.send(Command::BusStarted); + }), + ); + self.bus_listener_id = Some(id); + } + + pub(super) fn subscribe_channels(&mut self, core: &FireCore) { + let Some(header) = self.header.clone() else { + return; + }; + let owner = self.bus_owner(); + let topic_id = self.topic_id; + let _ = core.subscribe_message_bus_channel(MessageBusSubscription { + owner_token: owner.clone(), + channel: format!("/topic/{topic_id}"), + last_message_id: header.message_bus_last_id, + scope: MessageBusSubscriptionScope::Transient, + }); + let _ = core.subscribe_message_bus_channel(MessageBusSubscription { + owner_token: owner.clone(), + channel: format!("/topic/{topic_id}/reactions"), + last_message_id: None, + scope: MessageBusSubscriptionScope::Transient, + }); + let _ = core.subscribe_message_bus_channel(MessageBusSubscription { + owner_token: owner, + channel: format!("/polls/{topic_id}"), + last_message_id: Some(0), + scope: MessageBusSubscriptionScope::Transient, + }); + self.bus_subscribed = true; + } + + pub(super) fn unsubscribe(&self, core: &FireCore) { + if !self.bus_subscribed && !self.typing { + return; + } + let owner = self.bus_owner(); + let topic_id = self.topic_id; + for channel in [ + format!("/topic/{topic_id}"), + format!("/topic/{topic_id}/reactions"), + format!("/polls/{topic_id}"), + presence_channel(topic_id), + ] { + let _ = core.unsubscribe_message_bus_channel(owner.clone(), channel); + } + } + + pub(super) fn bus_owner(&self) -> String { + format!("topic-detail-session:{}", self.topic_id) + } + + pub(super) fn refresh_presence(&mut self, core: &FireCore) { + self.typing_users = core.topic_reply_presence_state(self.topic_id).users; + self.publish(core, false); + } + + +} + +pub(super) fn event_matches_topic(event: &MessageBusEvent, topic_id: u64) -> bool { + if event.topic_id == Some(topic_id) { + return true; + } + event.channel == format!("/topic/{topic_id}") + || event.channel == format!("/topic/{topic_id}/reactions") + || event.channel == format!("/polls/{topic_id}") + || event.channel == presence_channel(topic_id) + || event.detail_event_type.as_deref() == Some("polls") + && event.channel.starts_with(&format!("/polls/{topic_id}")) +} + +pub(super) fn presence_channel(topic_id: u64) -> String { + format!("/presence/discourse-presence/reply/{topic_id}") +} diff --git a/rust/crates/fire-core/src/core/topic_detail/load.rs b/rust/crates/fire-core/src/core/topic_detail/load.rs new file mode 100644 index 00000000..6dd64230 --- /dev/null +++ b/rust/crates/fire-core/src/core/topic_detail/load.rs @@ -0,0 +1,266 @@ +use std::collections::HashSet; + +use fire_models::{ + LoadMoreTopicPostsQuery, + TopicDetailLoadError, TopicDetailPhase, TopicDetailSourceQuery, +}; +use tokio::sync::mpsc; + +use super::super::topics::{ + load_more_topic_detail_posts, + load_topic_detail_page, +}; +use super::super::FireCore; +use super::*; +use crate::error::FireCoreError; + +impl ActorState { + pub(super) async fn open( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + request: TopicDetailOpenRequest, + ) { + self.scroll_target = request.target_post_number; + self.scroll_exhausted = false; + self.track_visit = request.track_visit; + if !request.bypass_cache + && core.topic_source_contains_target(self.topic_id, request.target_post_number) + { + self.phase = TopicDetailPhase::Ready; + self.load_error = None; + self.capture_header(core); + self.reset_window(core); + self.publish(core, false); + self.maybe_fetch_summary(core).await; + return; + } + self.load_http( + core, + tx, + request.target_post_number, + request.force_load, + request.track_visit, + request.allow_suggested_unread_root, + false, + ) + .await; + } + + pub(super) async fn load_http( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + target_post_number: Option, + force_load: bool, + track_visit: bool, + allow_suggested_unread_root: bool, + from_bus: bool, + ) { + if self.published.is_none() { + self.phase = TopicDetailPhase::Loading; + self.load_error = None; + self.publish(core, false); + } + self.track_visit = track_visit; + self.refresh_inflight = from_bus || self.refresh_inflight; + let epoch = self.http_epoch; + let query = actor_query( + self.topic_id, + target_post_number, + force_load, + track_visit, + allow_suggested_unread_root, + ); + let core_for_load = core.clone(); + let loaded = tokio::time::timeout(TOPIC_DETAIL_REQUEST_TIMEOUT, async move { + load_page_with_stale_retry(&core_for_load, query).await + }) + .await; + if epoch != self.http_epoch || !self.alive { + self.refresh_inflight = false; + return; + } + self.refresh_inflight = false; + match loaded { + Ok(Ok(_)) => { + self.restore_inflight_posts(core); + self.phase = TopicDetailPhase::Ready; + self.load_error = None; + self.capture_header(core); + self.reset_window(core); + self.subscribe_channels(core); + if self.defer_publish && self.scroll_active { + let snapshot = self.make_snapshot(core); + self.deferred = DeferredRefresh::Ready(snapshot); + self.defer_publish = false; + } else { + self.defer_publish = false; + self.publish(core, false); + } + if self.scroll_target.is_some() && !self.scroll_exhausted { + let posts = self.pending_visible.clone(); + self.hydrate_visible(core, &posts).await; + } + self.maybe_fetch_summary(core).await; + } + Ok(Err(error)) => self.fail_load(core, &error), + Err(_) => { + self.load_error = Some(TopicDetailLoadError::Network); + self.phase = TopicDetailPhase::Failed; + self.publish(core, true); + } + } + let _ = tx; + } + + pub(super) fn fail_load(&mut self, core: &FireCore, error: &FireCoreError) { + if let FireCoreError::LoginRequired { operation, .. } = error { + let generation = core.request_read_path_login(operation); + core.topic_detail_sessions + .register_waiter(generation, self.topic_id, self.track_visit); + self.load_error = Some(TopicDetailLoadError::LoginRequired); + } else if matches!( + error, + FireCoreError::Network { .. } + | FireCoreError::HttpStatus { .. } + | FireCoreError::CloudflareChallenge { .. } + | FireCoreError::CloudflareChallengeInProgress { .. } + ) { + self.load_error = Some(TopicDetailLoadError::Network); + } else { + self.load_error = Some(TopicDetailLoadError::Unrecoverable { + message: error.to_string(), + }); + } + self.phase = TopicDetailPhase::Failed; + self.publish(core, true); + } + + pub(super) async fn load_more(&mut self, core: &FireCore) { + if self.loading_more { + return; + } + let Some(snapshot) = core.clone_topic_source_snapshot(self.topic_id) else { + return; + }; + let Some(cursor) = snapshot.source_cursor.clone() else { + return; + }; + self.loading_more = true; + self.load_more_error = None; + self.publish(core, true); + let epoch = self.http_epoch; + let result = tokio::time::timeout( + TOPIC_DETAIL_REQUEST_TIMEOUT, + load_more_topic_detail_posts(core, LoadMoreTopicPostsQuery { cursor }), + ) + .await; + if epoch != self.http_epoch { + self.loading_more = false; + return; + } + self.loading_more = false; + match result { + Ok(Ok(_)) => { + self.restore_inflight_posts(core); + self.load_more_error = None; + self.capture_header(core); + self.extend_window_to_loaded(core); + self.publish(core, true); + } + Ok(Err(error)) => { + self.load_more_error = Some(error.to_string()); + self.publish(core, true); + } + Err(_) => { + self.load_more_error = Some("topic detail load more timed out".to_string()); + self.publish(core, true); + } + } + } + + pub(super) async fn hydrate_visible(&mut self, core: &FireCore, visible: &[u32]) { + self.expand_window_for_visible(core, visible); + if let Some(target) = self.scroll_target { + if !core.topic_source_contains_target(self.topic_id, Some(target)) { + self.advance_toward_target(core, target); + } + } + for _ in 0..TOPIC_DETAIL_HYDRATION_ITERS { + let missing = core + .with_topic_source_session_mut(self.topic_id, None, |session| { + session.missing_ids_in_range(self.window.requested.clone()) + }) + .unwrap_or_default(); + if missing.is_empty() { + if let Some(target) = self.scroll_target { + if core.topic_source_contains_target(self.topic_id, Some(target)) { + break; + } + if !self.advance_toward_target(core, target) { + self.scroll_exhausted = true; + break; + } + continue; + } + break; + } + let batch = missing + .into_iter() + .take(TOPIC_DETAIL_HYDRATION_PAGE) + .collect::>(); + let fetched = match core.fetch_topic_posts(self.topic_id, batch.clone()).await { + Ok(posts) => posts, + Err(_) => break, + }; + let fetched_ids = fetched.iter().map(|post| post.id).collect::>(); + let missing_ids = batch + .into_iter() + .filter(|post_id| !fetched_ids.contains(post_id)) + .collect::>(); + core.with_topic_source_session_mut(self.topic_id, None, |session| { + session.mark_unavailable(missing_ids); + session.recompute_loaded_state(); + }); + } + self.publish(core, false); + } + + +} + +fn actor_query( + topic_id: u64, + target_post_number: Option, + force_load: bool, + track_visit: bool, + allow_suggested_unread_root: bool, +) -> TopicDetailSourceQuery { + TopicDetailSourceQuery { + topic_id, + target_post_number, + allow_suggested_unread_root, + track_visit, + force_load, + initial_batch_size: TOPIC_DETAIL_INITIAL_BATCH, + load_more_batch_size: TOPIC_DETAIL_LOAD_MORE_BATCH, + max_auto_batches_per_gesture: TOPIC_DETAIL_MAX_AUTO_BATCHES, + max_auto_posts_per_gesture: TOPIC_DETAIL_MAX_AUTO_POSTS, + } +} + +async fn load_page_with_stale_retry( + core: &FireCore, + mut query: TopicDetailSourceQuery, +) -> Result { + let track_visit = query.track_visit; + match load_topic_detail_page(core, query.clone()).await { + Err(FireCoreError::StaleSessionResponse { .. }) => { + query.force_load = true; + query.track_visit = track_visit; + load_topic_detail_page(core, query).await + } + other => other, + } +} diff --git a/rust/crates/fire-core/src/core/topic_detail/mod.rs b/rust/crates/fire-core/src/core/topic_detail/mod.rs new file mode 100644 index 00000000..00b6826e --- /dev/null +++ b/rust/crates/fire-core/src/core/topic_detail/mod.rs @@ -0,0 +1,268 @@ +use std::{ + collections::{HashMap, HashSet}, + ops::Range, + sync::Arc, + time::Duration, +}; + +use fire_models::{ + PostActionType, TopicAiSummary, + TopicDetailLoadError, TopicDetailPhase, + TopicDetailUiSnapshot, TopicHeader, TopicPost, + TopicPresenceUser, +}; +use tokio::sync::oneshot; + +use crate::error::FireCoreError; + +pub const TOPIC_DETAIL_INITIAL_BATCH: u16 = 40; +pub const TOPIC_DETAIL_LOAD_MORE_BATCH: u16 = 40; +pub const TOPIC_DETAIL_MAX_AUTO_BATCHES: u8 = 3; +pub const TOPIC_DETAIL_MAX_AUTO_POSTS: u16 = 120; +pub const TOPIC_DETAIL_PREFETCH_THRESHOLD: u32 = 10; +pub const TOPIC_DETAIL_FORWARD_EXPANSION: u32 = 60; +pub const TOPIC_DETAIL_HYDRATION_PAGE: usize = 30; +pub const TOPIC_DETAIL_HYDRATION_ITERS: u8 = 8; +pub const TOPIC_DETAIL_VISIBLE_DEBOUNCE: Duration = Duration::from_millis(120); +pub const TOPIC_DETAIL_LIST_TAIL_THRESHOLD: u32 = 5; +pub const TOPIC_DETAIL_REPLY_CONTEXT_BATCH: usize = 20; +pub const TOPIC_DETAIL_REFRESH_DEBOUNCE: Duration = Duration::from_millis(1500); +pub const TOPIC_DETAIL_PRESENCE_HEARTBEAT: Duration = Duration::from_secs(30); +pub const TOPIC_DETAIL_REQUEST_TIMEOUT: Duration = Duration::from_secs(30); +const TOPIC_DETAIL_MAX_WINDOW: usize = 200; +const HEART_REACTION_ID: &str = "heart"; + +pub struct TopicDetailOpenRequest { + pub topic_id: u64, + pub owner_token: String, + pub slug_hint: Option, + pub target_post_number: Option, + pub bypass_cache: bool, + pub force_load: bool, + pub track_visit: bool, + pub allow_suggested_unread_root: bool, +} + +pub trait TopicDetailObserver: Send + Sync { + fn on_snapshot(&self, snapshot: TopicDetailUiSnapshot); +} + +enum DeferredRefresh { + None, + Pending, + Ready(TopicDetailUiSnapshot), +} + +struct TopicWindow { + requested: Range, + anchor: Option, +} + +struct ActorState { + topic_id: u64, + owners: HashMap>, + slug_hint: Option, + generation: u64, + collection_revision: u64, + chrome_revision: u64, + sidecar_revision: u64, + interaction_revision: u64, + phase: TopicDetailPhase, + load_error: Option, + notice: Option, + scroll_target: Option, + scroll_exhausted: bool, + window: TopicWindow, + scroll_active: bool, + deferred: DeferredRefresh, + defer_publish: bool, + refresh_inflight: bool, + loading_more: bool, + load_more_error: Option, + summary: Option, + summary_loading: bool, + summary_error: Option, + typing_users: Vec, + submitting: bool, + mutating: HashSet, + loading_reply_context: HashSet, + reply_context: Option, + flag_types: Vec, + rollback: HashMap, + inflight_posts: HashMap, + http_epoch: u64, + visible_generation: u64, + refresh_generation: u64, + pending_visible: Vec, + track_visit: bool, + published: Option, + header: Option, + bus_listener_id: Option, + bus_subscribed: bool, + typing: bool, + alive: bool, +} + +enum Command { + SyncOwners { + owners: HashMap>, + open: Option, + }, + Shutdown, + CancelHttp, + Reload { + target_post_number: Option, + force_load: bool, + track_visit: bool, + allow_suggested_unread_root: bool, + }, + LoadMore, + NoteVisible(Vec), + VisibleFired(u64), + NoteTail { + item_count: u32, + visible_max_item: Option, + }, + NoteScroll(bool), + AckScroll(u32), + ClearScroll, + BeginTyping, + EndTyping, + PresenceHeartbeat, + BusRefresh, + RefreshFired(u64), + BusStarted, + RefreshPresence, + ReloadAi { + skip_age_check: bool, + }, + LoadReplyContext(u64), + PrepareEdit { + post_id: u64, + reply: oneshot::Sender>, + }, + EnsureFlags { + reply: oneshot::Sender>, + }, + SubmitReply { + raw: String, + reply_to_post_number: Option, + scroll_to_created: bool, + reply: oneshot::Sender>, + }, + CreateBoost { + post_id: u64, + raw: String, + reply: oneshot::Sender>, + }, + DeleteBoost { + post_id: u64, + boost_id: u64, + reply: oneshot::Sender>, + }, + UpdatePost { + post_id: u64, + raw: String, + edit_reason: Option, + reply: oneshot::Sender>, + }, + DeletePost { + post_id: u64, + reply: oneshot::Sender>, + }, + RecoverPost { + post_id: u64, + reply: oneshot::Sender>, + }, + FlagPost { + post_id: u64, + flag_type_id: u32, + message: Option, + reply: oneshot::Sender>, + }, + SetLiked { + post_id: u64, + liked: bool, + reply: oneshot::Sender>, + }, + ToggleReaction { + post_id: u64, + reaction_id: String, + reply: oneshot::Sender>, + }, + VotePoll { + post_id: u64, + poll_name: String, + options: Vec, + reply: oneshot::Sender>, + }, + UnvotePoll { + post_id: u64, + poll_name: String, + reply: oneshot::Sender>, + }, + VoteTopic { + voted: bool, + reply: oneshot::Sender>, + }, + AcceptSolution { + post_id: u64, + accepted: bool, + reply: oneshot::Sender>, + }, + CreateBookmark { + bookmarkable_id: u64, + bookmarkable_type: String, + name: Option, + reminder_at: Option, + auto_delete_preference: Option, + reply: oneshot::Sender>, + }, + UpdateBookmark { + bookmark_id: u64, + name: Option, + reminder_at: Option, + auto_delete_preference: Option, + reply: oneshot::Sender>, + }, + DeleteBookmark { + bookmark_id: u64, + reply: oneshot::Sender>, + }, + SetNotificationLevel { + level: i32, + reply: oneshot::Sender>, + }, + UpdateTopic { + title: String, + category_id: u64, + tags: Vec, + reply: oneshot::Sender>, + }, + ReportTimings { + topic_time_ms: u32, + timings: Vec, + reply: oneshot::Sender>, + }, + LoginReload { + track_visit: bool, + }, + Flush(oneshot::Sender<()>), +} + +mod actor; +mod bus; +mod load; +mod mutations; +mod publish; +mod reactions; +mod registry; +mod session; +mod summary; +mod window; + +pub use registry::TopicDetailSessionRegistry; +pub use session::TopicDetailSession; + +#[cfg(test)] +mod tests; diff --git a/rust/crates/fire-core/src/core/topic_detail/mutations.rs b/rust/crates/fire-core/src/core/topic_detail/mutations.rs new file mode 100644 index 00000000..df9285a3 --- /dev/null +++ b/rust/crates/fire-core/src/core/topic_detail/mutations.rs @@ -0,0 +1,449 @@ + +use fire_models::{ + TopicReplyRequest, TopicUpdateRequest, +}; +use tokio::sync::mpsc; + +use super::super::FireCore; +use super::*; +use crate::error::FireCoreError; + +impl ActorState { + pub(super) async fn submit_reply( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + raw: String, + reply_to_post_number: Option, + scroll_to_created: bool, + ) -> Result<(), FireCoreError> { + if raw.trim().is_empty() { + return Err(FireCoreError::InvalidArgument { + operation: "submit reply", + details: "reply body is empty".to_string(), + }); + } + self.submitting = true; + self.publish(core, false); + let created = core + .create_reply(TopicReplyRequest { + topic_id: self.topic_id, + raw, + reply_to_post_number, + }) + .await; + self.submitting = false; + let post = match created { + Ok(post) => post, + Err(error) => { + self.publish(core, false); + return Err(error); + } + }; + let post_number = post.post_number; + let previous_len = core + .with_topic_source_session_mut(self.topic_id, None, |session| session.raw_stream_len()) + .unwrap_or(0); + core.with_topic_source_session_mut(self.topic_id, None, |session| { + let is_new = session.append_stream_post(post); + if is_new { + let stream_len = u32::try_from(session.raw_stream_len()).unwrap_or(u32::MAX); + let header = session.header_mut(); + header.posts_count = header.posts_count.saturating_add(1).max(stream_len); + header.reply_count = header + .reply_count + .saturating_add(1) + .max(header.posts_count.saturating_sub(1)); + header.highest_post_number = header.highest_post_number.max(post_number); + header.last_read_post_number = + Some(header.last_read_post_number.unwrap_or(0).max(post_number)); + } + }); + if self.window.requested.end >= previous_len { + self.window.requested.end = self.window.requested.end.saturating_add(1); + } + if scroll_to_created { + self.scroll_target = Some(post_number); + self.scroll_exhausted = false; + } + self.capture_header(core); + self.publish(core, true); + self.load_http(core, tx, None, false, false, false, false) + .await; + Ok(()) + } + + pub(super) async fn create_boost( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + post_id: u64, + raw: String, + ) -> Result<(), FireCoreError> { + let boost = core.create_boost(post_id, raw).await?; + core.with_topic_source_session_mut(self.topic_id, None, |session| { + if let Some(post) = session.post_mut(post_id) { + if !post.boosts.iter().any(|existing| existing.id == boost.id) { + post.boosts.push(boost); + } + post.can_boost = false; + } + }); + self.publish(core, true); + self.load_http(core, tx, None, false, false, false, false) + .await; + Ok(()) + } + + pub(super) async fn delete_boost( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + post_id: u64, + boost_id: u64, + ) -> Result<(), FireCoreError> { + core.delete_boost(boost_id).await?; + core.with_topic_source_session_mut(self.topic_id, None, |session| { + if let Some(post) = session.post_mut(post_id) { + post.boosts.retain(|boost| boost.id != boost_id); + } + }); + self.publish(core, true); + self.load_http(core, tx, None, false, false, false, false) + .await; + Ok(()) + } + + pub(super) async fn update_post( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + post_id: u64, + raw: String, + edit_reason: Option, + ) -> Result<(), FireCoreError> { + let updated = core + .update_post(fire_models::PostUpdateRequest { + post_id, + raw, + edit_reason, + }) + .await?; + core.with_topic_source_session_mut(self.topic_id, None, |session| { + session.merge_posts(std::iter::once(updated)); + }); + self.publish(core, false); + self.load_http(core, tx, None, false, false, false, false) + .await; + Ok(()) + } + + pub(super) async fn delete_post( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + post_id: u64, + ) -> Result<(), FireCoreError> { + core.delete_post(post_id).await?; + self.load_http(core, tx, None, false, false, false, false) + .await; + Ok(()) + } + + pub(super) async fn recover_post( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + post_id: u64, + ) -> Result<(), FireCoreError> { + core.recover_post(post_id).await?; + self.load_http(core, tx, None, false, false, false, false) + .await; + Ok(()) + } + + pub(super) async fn flag_post( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + post_id: u64, + flag_type_id: u32, + message: Option, + ) -> Result<(), FireCoreError> { + core.flag_post(fire_models::PostFlagRequest { + post_id, + flag_type_id, + message, + }) + .await?; + self.load_http(core, tx, None, false, false, false, false) + .await; + Ok(()) + } + + + pub(super) async fn vote_poll( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + post_id: u64, + poll_name: String, + options: Vec, + ) -> Result<(), FireCoreError> { + let poll = core.vote_poll(post_id, &poll_name, options).await?; + core.with_topic_source_session_mut(self.topic_id, None, |session| { + if let Some(post) = session.post_mut(post_id) { + if let Some(slot) = post.polls.iter_mut().find(|item| item.name == poll.name) { + *slot = poll; + } + } + }); + self.load_http(core, tx, None, false, false, false, false) + .await; + Ok(()) + } + + pub(super) async fn unvote_poll( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + post_id: u64, + poll_name: String, + ) -> Result<(), FireCoreError> { + let poll = core.unvote_poll(post_id, &poll_name).await?; + core.with_topic_source_session_mut(self.topic_id, None, |session| { + if let Some(post) = session.post_mut(post_id) { + if let Some(slot) = post.polls.iter_mut().find(|item| item.name == poll.name) { + *slot = poll; + } + } + }); + self.load_http(core, tx, None, false, false, false, false) + .await; + Ok(()) + } + + pub(super) async fn vote_topic( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + voted: bool, + ) -> Result<(), FireCoreError> { + let response = if voted { + core.vote_topic(self.topic_id).await? + } else { + core.unvote_topic(self.topic_id).await? + }; + core.with_topic_source_session_mut(self.topic_id, None, |session| { + let header = session.header_mut(); + header.vote_count = response.vote_count; + header.can_vote = response.can_vote; + header.user_voted = voted; + }); + self.capture_header(core); + self.publish(core, false); + self.load_http(core, tx, None, false, false, false, false) + .await; + Ok(()) + } + + pub(super) async fn accept_solution( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + post_id: u64, + accepted: bool, + ) -> Result<(), FireCoreError> { + if accepted { + core.accept_solution(post_id).await?; + } else { + core.unaccept_solution(post_id).await?; + } + self.load_http(core, tx, None, false, false, false, false) + .await; + Ok(()) + } + + pub(super) async fn create_bookmark( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + bookmarkable_id: u64, + bookmarkable_type: String, + name: Option, + reminder_at: Option, + auto_delete_preference: Option, + ) -> Result<(), FireCoreError> { + let bookmark_id = core + .create_bookmark( + bookmarkable_id, + &bookmarkable_type, + name.as_deref(), + reminder_at.as_deref(), + auto_delete_preference, + ) + .await?; + let is_topic = bookmarkable_type.eq_ignore_ascii_case("Topic"); + core.with_topic_source_session_mut(self.topic_id, None, |session| { + if is_topic { + let header = session.header_mut(); + header.bookmarked = true; + header.bookmark_id = Some(bookmark_id); + header.bookmark_name = name.clone(); + header.bookmark_reminder_at = reminder_at.clone(); + } else if let Some(post) = session.post_mut(bookmarkable_id) { + post.bookmarked = true; + post.bookmark_id = Some(bookmark_id); + post.bookmark_name = name.clone(); + post.bookmark_reminder_at = reminder_at.clone(); + } + }); + self.capture_header(core); + self.publish(core, false); + self.load_http(core, tx, None, false, false, false, false) + .await; + Ok(()) + } + + pub(super) async fn update_bookmark( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + bookmark_id: u64, + name: Option, + reminder_at: Option, + auto_delete_preference: Option, + ) -> Result<(), FireCoreError> { + core.update_bookmark( + bookmark_id, + name.clone(), + reminder_at.clone(), + auto_delete_preference, + ) + .await?; + core.with_topic_source_session_mut(self.topic_id, None, |session| { + if session.header().bookmark_id == Some(bookmark_id) { + let header = session.header_mut(); + header.bookmark_name = name.clone(); + header.bookmark_reminder_at = reminder_at.clone(); + } + let post_ids = session + .raw_stream_ids() + .iter() + .copied() + .filter(|post_id| { + session + .post(*post_id) + .is_some_and(|post| post.bookmark_id == Some(bookmark_id)) + }) + .collect::>(); + for post_id in post_ids { + if let Some(post) = session.post_mut(post_id) { + post.bookmark_name = name.clone(); + post.bookmark_reminder_at = reminder_at.clone(); + } + } + }); + self.capture_header(core); + self.publish(core, false); + self.load_http(core, tx, None, false, false, false, false) + .await; + Ok(()) + } + + pub(super) async fn delete_bookmark( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + bookmark_id: u64, + ) -> Result<(), FireCoreError> { + core.delete_bookmark(bookmark_id).await?; + core.with_topic_source_session_mut(self.topic_id, None, |session| { + if session.header().bookmark_id == Some(bookmark_id) { + let header = session.header_mut(); + header.bookmarked = false; + header.bookmark_id = None; + header.bookmark_name = None; + header.bookmark_reminder_at = None; + } + let post_ids = session + .raw_stream_ids() + .iter() + .copied() + .filter(|post_id| { + session + .post(*post_id) + .is_some_and(|post| post.bookmark_id == Some(bookmark_id)) + }) + .collect::>(); + for post_id in post_ids { + if let Some(post) = session.post_mut(post_id) { + post.bookmarked = false; + post.bookmark_id = None; + post.bookmark_name = None; + post.bookmark_reminder_at = None; + } + } + }); + self.capture_header(core); + self.publish(core, false); + self.load_http(core, tx, None, false, false, false, false) + .await; + Ok(()) + } + + pub(super) async fn set_notification_level( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + level: i32, + ) -> Result<(), FireCoreError> { + core.set_topic_notification_level(self.topic_id, level) + .await?; + core.with_topic_source_session_mut(self.topic_id, None, |session| { + session.header_mut().details.notification_level = Some(level); + }); + self.capture_header(core); + self.publish(core, false); + self.load_http(core, tx, None, false, false, false, false) + .await; + Ok(()) + } + + pub(super) async fn update_topic( + &mut self, + core: &FireCore, + tx: &mpsc::UnboundedSender, + title: String, + category_id: u64, + tags: Vec, + ) -> Result<(), FireCoreError> { + core.update_topic(TopicUpdateRequest { + topic_id: self.topic_id, + title: title.clone(), + category_id, + tags: tags.clone(), + }) + .await?; + core.with_topic_source_session_mut(self.topic_id, None, |session| { + let header = session.header_mut(); + header.title = title; + header.category_id = Some(category_id); + header.tags = tags + .into_iter() + .map(|name| fire_models::TopicTag { + id: None, + name, + slug: None, + }) + .collect(); + }); + self.capture_header(core); + self.publish(core, false); + self.load_http(core, tx, None, false, false, false, false) + .await; + Ok(()) + } + + +} diff --git a/rust/crates/fire-core/src/core/topic_detail/publish.rs b/rust/crates/fire-core/src/core/topic_detail/publish.rs new file mode 100644 index 00000000..75256d99 --- /dev/null +++ b/rust/crates/fire-core/src/core/topic_detail/publish.rs @@ -0,0 +1,161 @@ +use std::panic::{self, AssertUnwindSafe}; + +use fire_models::{ + TopicDetailSourceSnapshot, + TopicDetailUiSnapshot, TopicHeader, TopicTreePresentation, +}; + +use super::super::topic_detail_project::{ + chrome_fields_changed, header_counts_changed, + home_row_patch_for_header, interaction_checksums_changed, layout_checksums_changed, project_topic_detail_snapshot, sidecar_changed, structure_changed, + ProjectionChrome, +}; +use super::super::topics::build_topic_tree_presentation_from_source_snapshot; +use super::super::FireCore; +use super::*; + +impl ActorState { + pub(super) fn publish(&mut self, core: &FireCore, structural_hint: bool) { + let _ = structural_hint; + if self.defer_publish && self.scroll_active { + let mut snapshot = self.make_snapshot(core); + self.assign_revisions(&mut snapshot); + self.deferred = DeferredRefresh::Ready(snapshot); + return; + } + let mut snapshot = self.make_snapshot(core); + self.assign_revisions(&mut snapshot); + self.publish_snapshot(core, snapshot); + } + + pub(super) fn publish_snapshot(&mut self, core: &FireCore, snapshot: TopicDetailUiSnapshot) { + if let Some(patch) = snapshot.home_row_patch.clone() { + core.patch_cached_home_topic_counts(&patch); + } + self.published = Some(snapshot.clone()); + let owners = self.owners.values().cloned().collect::>(); + for owner in owners { + let snapshot = snapshot.clone(); + let _ = panic::catch_unwind(AssertUnwindSafe(|| owner.on_snapshot(snapshot))); + } + let _ = core; + } + + pub(super) fn assign_revisions(&mut self, snapshot: &mut TopicDetailUiSnapshot) { + let previous = self.published.as_ref(); + if structure_changed(previous, snapshot) { + self.collection_revision = self.collection_revision.saturating_add(1); + } + let layout_changed = layout_checksums_changed(previous, snapshot); + let interaction_changed = interaction_checksums_changed(previous, snapshot); + if interaction_changed || (layout_changed && !structure_changed(previous, snapshot)) { + self.interaction_revision = self.interaction_revision.saturating_add(1); + } + if previous.is_none_or(|previous| chrome_fields_changed(&previous.chrome, &snapshot.chrome)) + { + self.chrome_revision = self.chrome_revision.saturating_add(1); + } + if previous.is_none_or(|previous| { + sidecar_changed( + &previous.sidecar, + &snapshot.sidecar, + &previous.notice, + &snapshot.notice, + ) && !(snapshot.sidecar.is_loading + && previous.sidecar.summarized_text == snapshot.sidecar.summarized_text + && previous.sidecar.error == snapshot.sidecar.error + && previous.notice == snapshot.notice) + }) { + self.sidecar_revision = self.sidecar_revision.saturating_add(1); + } + self.generation = self.generation.saturating_add(1); + snapshot.generation = self.generation; + snapshot.collection_revision = self.collection_revision; + snapshot.chrome_revision = self.chrome_revision; + snapshot.sidecar_revision = self.sidecar_revision; + snapshot.interaction_revision = self.interaction_revision; + } + + pub(super) fn make_snapshot(&mut self, core: &FireCore) -> TopicDetailUiSnapshot { + let source = core + .clone_topic_source_snapshot(self.topic_id) + .unwrap_or_else(|| TopicDetailSourceSnapshot { + header: self.header.clone().unwrap_or_else(|| TopicHeader { + topic_id: self.topic_id, + slug: self.slug_hint.clone().unwrap_or_default(), + ..TopicHeader::default() + }), + ..TopicDetailSourceSnapshot::default() + }); + let previous_header = self.header.clone(); + let home_row_patch = previous_header + .as_ref() + .filter(|previous| header_counts_changed(previous, &source.header)) + .map(|_| home_row_patch_for_header(&source.header)); + if source.header.topic_id == self.topic_id && source.header.posts_count > 0 { + self.header = Some(source.header.clone()); + } + let tree = if source.loaded_posts.is_empty() && source.body.post.id == 0 { + TopicTreePresentation::default() + } else { + build_topic_tree_presentation_from_source_snapshot(&source) + }; + let mut chrome = ProjectionChrome { + phase: self.phase, + load_error: self.load_error.clone(), + notice: self.notice.clone(), + is_loading_more: self.loading_more, + load_more_error: self.load_more_error.clone(), + scroll_target_post_number: self.scroll_target.filter(|_| !self.scroll_exhausted), + summary: self.summary.clone(), + summary_loading: self.summary_loading, + summary_error: self.summary_error.clone(), + typing_users: self.typing_users.clone(), + current_user_id: core.snapshot().bootstrap.current_user_id, + is_submitting: self.submitting, + mutating: self.mutating.clone(), + loading_reply_context: self.loading_reply_context.clone(), + reply_context: self.reply_context.clone(), + flag_types: self.flag_types.clone(), + home_row_patch, + generation: self.generation, + collection_revision: self.collection_revision, + chrome_revision: self.chrome_revision, + sidecar_revision: self.sidecar_revision, + interaction_revision: self.interaction_revision, + }; + if self.reply_context.is_some() { + chrome.reply_context = self.reply_context.clone(); + } + project_topic_detail_snapshot(&source, &tree, &chrome) + } + + + pub(super) fn projection_chrome(&self, core: &FireCore) -> ProjectionChrome { + ProjectionChrome { + phase: self.phase, + load_error: self.load_error.clone(), + notice: self.notice.clone(), + is_loading_more: self.loading_more, + load_more_error: self.load_more_error.clone(), + scroll_target_post_number: self.scroll_target, + summary: self.summary.clone(), + summary_loading: self.summary_loading, + summary_error: self.summary_error.clone(), + typing_users: self.typing_users.clone(), + current_user_id: core.snapshot().bootstrap.current_user_id, + is_submitting: self.submitting, + mutating: self.mutating.clone(), + loading_reply_context: self.loading_reply_context.clone(), + reply_context: self.reply_context.clone(), + flag_types: self.flag_types.clone(), + home_row_patch: None, + generation: self.generation, + collection_revision: self.collection_revision, + chrome_revision: self.chrome_revision, + sidecar_revision: self.sidecar_revision, + interaction_revision: self.interaction_revision, + } + } + +} diff --git a/rust/crates/fire-core/src/core/topic_detail/reactions.rs b/rust/crates/fire-core/src/core/topic_detail/reactions.rs new file mode 100644 index 00000000..1cb799a2 --- /dev/null +++ b/rust/crates/fire-core/src/core/topic_detail/reactions.rs @@ -0,0 +1,179 @@ + +use tokio::sync::mpsc; + +use super::super::FireCore; +use super::*; +use crate::error::FireCoreError; + +impl ActorState { + pub(super) async fn set_liked( + &mut self, + core: &FireCore, + post_id: u64, + liked: bool, + ) -> Result<(), FireCoreError> { + let desired = liked.then(|| HEART_REACTION_ID.to_string()); + self.apply_optimistic_reaction(core, post_id, desired); + let result = if liked { + core.like_post(post_id).await + } else { + core.unlike_post(post_id).await + }; + match result { + Ok(Some(update)) => { + self.apply_reaction_update(core, post_id, &update); + Ok(()) + } + Ok(None) => { + self.clear_mutation(core, post_id, false); + self.load_http( + core, + &mpsc::unbounded_channel().0, + None, + false, + false, + false, + false, + ) + .await; + Ok(()) + } + Err(error) => { + self.clear_mutation(core, post_id, true); + Err(error) + } + } + } + + pub(super) async fn toggle_reaction( + &mut self, + core: &FireCore, + post_id: u64, + reaction_id: String, + ) -> Result<(), FireCoreError> { + let current = core.with_topic_source_session_mut(self.topic_id, None, |session| { + session + .post(post_id) + .and_then(|post| post.current_user_reaction.as_ref().map(|reaction| reaction.id.clone())) + }); + let desired = match current.flatten() { + Some(current) if current == reaction_id => None, + _ => Some(reaction_id.clone()), + }; + self.apply_optimistic_reaction(core, post_id, desired); + match core.toggle_post_reaction(post_id, reaction_id).await { + Ok(update) => { + self.apply_reaction_update(core, post_id, &update); + Ok(()) + } + Err(error) => { + self.clear_mutation(core, post_id, true); + Err(error) + } + } + } + + pub(super) fn apply_optimistic_reaction( + &mut self, + core: &FireCore, + post_id: u64, + desired: Option, + ) { + core.with_topic_source_session_mut(self.topic_id, None, |session| { + let Some(post) = session.post(post_id).cloned() else { + return; + }; + self.rollback.insert(post_id, post.clone()); + let mut updated = post; + let current = updated + .current_user_reaction + .as_ref() + .map(|reaction| reaction.id.clone()); + if current == desired { + self.inflight_posts.insert(post_id, updated); + return; + } + adjust_reaction_count(&mut updated.reactions, current.as_deref(), -1); + if let Some(desired_id) = desired.clone() { + adjust_reaction_count(&mut updated.reactions, Some(&desired_id), 1); + updated.current_user_reaction = Some(fire_models::TopicReaction { + id: desired_id, + kind: None, + count: 1, + can_undo: Some(true), + }); + } else { + updated.current_user_reaction = None; + } + updated.like_count = updated + .reactions + .iter() + .find(|reaction| reaction.id == HEART_REACTION_ID) + .map(|reaction| reaction.count) + .unwrap_or(0); + self.inflight_posts.insert(post_id, updated.clone()); + session.merge_posts(std::iter::once(updated)); + }); + self.mutating.insert(post_id); + self.publish(core, false); + } + + pub(super) fn apply_reaction_update( + &mut self, + core: &FireCore, + post_id: u64, + update: &fire_models::PostReactionUpdate, + ) { + core.with_topic_source_session_mut(self.topic_id, None, |session| { + if let Some(post) = session.post_mut(post_id) { + post.reactions = update.reactions.clone(); + post.current_user_reaction = update.current_user_reaction.clone(); + post.like_count = post + .reactions + .iter() + .find(|reaction| reaction.id == HEART_REACTION_ID) + .map(|reaction| reaction.count) + .unwrap_or(0); + } + }); + self.clear_mutation(core, post_id, false); + } + + pub(super) fn clear_mutation(&mut self, core: &FireCore, post_id: u64, rollback: bool) { + if rollback { + if let Some(post) = self.rollback.remove(&post_id) { + core.with_topic_source_session_mut(self.topic_id, None, |session| { + session.merge_posts(std::iter::once(post)); + }); + } + } else { + self.rollback.remove(&post_id); + } + self.inflight_posts.remove(&post_id); + self.mutating.remove(&post_id); + self.publish(core, false); + } + + +} + +fn adjust_reaction_count(reactions: &mut Vec, id: Option<&str>, delta: i32) { + let Some(id) = id else { + return; + }; + if let Some(index) = reactions.iter().position(|reaction| reaction.id == id) { + let next = reactions[index].count as i32 + delta; + if next <= 0 { + reactions.remove(index); + } else { + reactions[index].count = next as u32; + } + } else if delta > 0 { + reactions.push(fire_models::TopicReaction { + id: id.to_string(), + kind: None, + count: delta as u32, + can_undo: Some(true), + }); + } +} diff --git a/rust/crates/fire-core/src/core/topic_detail/registry.rs b/rust/crates/fire-core/src/core/topic_detail/registry.rs new file mode 100644 index 00000000..fdc426c2 --- /dev/null +++ b/rust/crates/fire-core/src/core/topic_detail/registry.rs @@ -0,0 +1,360 @@ +use std::{ + collections::HashMap, + sync::{Arc, Mutex, OnceLock}, +}; + +use fire_models::{ + ReadPathLoginRequest, TopicHomeRowCountPatch, TopicListResponse, +}; +use tokio::sync::mpsc; +use tracing::warn; + +use super::super::topic_detail_project::{ + apply_patch_to_row, apply_patch_to_summary, +}; +use super::super::topics::topic_list_cache_scope_key; +use super::super::FireCore; +use super::*; +use super::actor::run_actor; + +struct Slot { + session: Arc, + owners: HashMap>, +} + +struct LoginWaiter { + generation: u64, + topic_id: u64, + track_visit: bool, +} + +#[derive(Default)] +struct RegistryInner { + sessions: HashMap, + login_waiters: Vec, +} + +pub struct TopicDetailSessionRegistry { + inner: Mutex, +} + +impl Default for TopicDetailSessionRegistry { + fn default() -> Self { + Self { + inner: Mutex::new(RegistryInner::default()), + } + } +} + +impl TopicDetailSessionRegistry { + pub fn open( + &self, + core: &FireCore, + request: TopicDetailOpenRequest, + observer: Arc, + ) -> Arc { + let topic_id = request.topic_id; + let owner = request.owner_token.clone(); + let mut guard = self.inner.lock().expect("topic detail registry poisoned"); + if let Some(slot) = guard.sessions.get_mut(&topic_id) { + slot.owners.insert(owner, observer); + let owners = slot.owners.clone(); + let session = Arc::clone(&slot.session); + drop(guard); + let _ = session.tx.send(Command::SyncOwners { + owners, + open: Some(request), + }); + return session; + } + let (tx, rx) = mpsc::unbounded_channel(); + let session = Arc::new(TopicDetailSession { + topic_id, + owner_token: owner.clone(), + tx, + }); + let mut owners = HashMap::new(); + owners.insert(owner, observer); + guard.sessions.insert( + topic_id, + Slot { + session: Arc::clone(&session), + owners: owners.clone(), + }, + ); + drop(guard); + let core = core.clone(); + let command_tx = session.tx.clone(); + spawn_actor(async move { + run_actor(core, topic_id, command_tx, rx).await; + }); + let _ = session.tx.send(Command::SyncOwners { + owners, + open: Some(request), + }); + session + } + + pub fn release(&self, topic_id: u64, owner_token: &str) { + let mut guard = self.inner.lock().expect("topic detail registry poisoned"); + let Some(slot) = guard.sessions.get_mut(&topic_id) else { + return; + }; + slot.owners.remove(owner_token); + if slot.owners.is_empty() { + let session = guard + .sessions + .remove(&topic_id) + .map(|slot| slot.session); + self.inner_clear_waiters(&mut guard, topic_id); + drop(guard); + if let Some(session) = session { + let _ = session.tx.send(Command::Shutdown); + } + } else { + let owners = slot.owners.clone(); + let session = Arc::clone(&slot.session); + drop(guard); + let _ = session.tx.send(Command::SyncOwners { + owners, + open: None, + }); + } + } + + pub fn close_all(&self) { + let mut guard = self.inner.lock().expect("topic detail registry poisoned"); + let sessions = guard + .sessions + .drain() + .map(|(_, slot)| slot.session) + .collect::>(); + guard.login_waiters.clear(); + drop(guard); + for session in sessions { + let _ = session.tx.send(Command::Shutdown); + } + } + + pub fn cancel_inflight_http(&self) { + let guard = self.inner.lock().expect("topic detail registry poisoned"); + let senders = guard + .sessions + .values() + .map(|slot| slot.session.tx.clone()) + .collect::>(); + drop(guard); + for tx in senders { + let _ = tx.send(Command::CancelHttp); + } + } + + pub fn complete_login(&self, generation: u64, succeeded: bool) { + let mut guard = self.inner.lock().expect("topic detail registry poisoned"); + let waiters = guard + .login_waiters + .iter() + .filter(|waiter| waiter.generation == generation) + .cloned() + .collect::>(); + guard + .login_waiters + .retain(|waiter| waiter.generation != generation); + let sessions = guard + .sessions + .iter() + .map(|(id, slot)| (*id, slot.session.tx.clone())) + .collect::>(); + drop(guard); + if !succeeded { + return; + } + for waiter in waiters { + if let Some(tx) = sessions.get(&waiter.topic_id) { + let _ = tx.send(Command::LoginReload { + track_visit: waiter.track_visit, + }); + } + } + } + + pub(super) fn register_waiter(&self, generation: u64, topic_id: u64, track_visit: bool) { + let mut guard = self.inner.lock().expect("topic detail registry poisoned"); + if guard.login_waiters.iter().any(|waiter| { + waiter.generation == generation && waiter.topic_id == topic_id + }) { + return; + } + guard.login_waiters.push(LoginWaiter { + generation, + topic_id, + track_visit, + }); + } + + fn inner_clear_waiters(&self, guard: &mut RegistryInner, topic_id: u64) { + guard + .login_waiters + .retain(|waiter| waiter.topic_id != topic_id); + } + + pub fn session_count(&self) -> usize { + self.inner + .lock() + .expect("topic detail registry poisoned") + .sessions + .len() + } +} + +impl Clone for LoginWaiter { + fn clone(&self) -> Self { + Self { + generation: self.generation, + topic_id: self.topic_id, + track_visit: self.track_visit, + } + } +} + +fn spawn_actor(future: impl std::future::Future + Send + 'static) { + if let Ok(handle) = tokio::runtime::Handle::try_current() { + handle.spawn(future); + return; + } + static RUNTIME: OnceLock = OnceLock::new(); + let runtime = RUNTIME.get_or_init(|| { + tokio::runtime::Builder::new_multi_thread() + .enable_all() + .thread_name("fire-topic-detail") + .build() + .expect("topic detail runtime") + }); + runtime.spawn(future); +} + +impl FireCore { + pub fn open_topic_detail( + &self, + request: TopicDetailOpenRequest, + observer: Arc, + ) -> Arc { + self.topic_detail_sessions.open(self, request, observer) + } + + pub fn release_topic_detail_owner(&self, topic_id: u64, owner_token: &str) { + self.topic_detail_sessions.release(topic_id, owner_token); + } + + pub fn close_all_topic_detail_sessions(&self) { + self.topic_detail_sessions.close_all(); + } + + pub fn cancel_topic_detail_http(&self) { + self.topic_detail_sessions.cancel_inflight_http(); + } + + pub fn request_read_path_login(&self, operation: &str) -> u64 { + let snapshot = { + let mut session = crate::sync_utils::write_rwlock(&self.session, "session"); + if let Some(existing) = session.read_path_login_request.clone() { + session.snapshot.read_path_login_request = Some(existing.clone()); + let generation = existing.generation; + let snapshot = session.snapshot.clone(); + (snapshot, generation, false) + } else { + session.read_path_login_generation = session + .read_path_login_generation + .saturating_add(1) + .max(1); + let request = ReadPathLoginRequest { + generation: session.read_path_login_generation, + operation: operation.to_string(), + }; + session.read_path_login_request = Some(request.clone()); + session.snapshot.read_path_login_request = Some(request); + let generation = session.read_path_login_generation; + (session.snapshot.clone(), generation, true) + } + }; + self.state_observers().notify_session(snapshot.0); + snapshot.1 + } + + pub fn complete_read_path_login(&self, generation: u64, succeeded: bool) { + let snapshot = { + let mut session = crate::sync_utils::write_rwlock(&self.session, "session"); + let matches = session + .read_path_login_request + .as_ref() + .is_some_and(|request| request.generation == generation); + if !matches { + return; + } + session.read_path_login_request = None; + session.snapshot.read_path_login_request = None; + session.snapshot.clone() + }; + self.state_observers().notify_session(snapshot); + self.topic_detail_sessions + .complete_login(generation, succeeded); + } + + pub(crate) fn patch_cached_home_topic_counts(&self, patch: &TopicHomeRowCountPatch) { + let auth_scope_hash = self.current_auth_scope_hash(); + let scope_key = topic_list_cache_scope_key(&self.current_home_topic_list_query()); + let pages = { + let store = self + .shared_store + .lock() + .expect("shared store mutex poisoned"); + match store.topic_list_cache_list_pages(&auth_scope_hash, &scope_key) { + Ok(pages) => pages, + Err(error) => { + warn!(error = %error, "failed to list cached home topic pages"); + return; + } + } + }; + for (page, payload) in pages { + let mut cached: TopicListResponse = match serde_json::from_str(&payload) { + Ok(cached) => cached, + Err(_) => continue, + }; + let row_flag = cached + .rows + .iter() + .find(|row| row.topic.id == patch.topic_id) + .map(|row| row.has_unread_posts); + let mut changed = false; + for topic in &mut cached.topics { + if topic.id == patch.topic_id { + apply_patch_to_summary(topic, patch, row_flag); + changed = true; + } + } + for row in &mut cached.rows { + if row.topic.id == patch.topic_id { + apply_patch_to_row(row, patch); + changed = true; + } + } + if !changed { + continue; + } + let Ok(payload) = serde_json::to_string(&cached) else { + continue; + }; + let store = self + .shared_store + .lock() + .expect("shared store mutex poisoned"); + if let Err(error) = + store.topic_list_cache_write(&auth_scope_hash, &scope_key, page, &payload) + { + warn!(error = %error, "failed to write patched home topic page"); + } + } + } +} + diff --git a/rust/crates/fire-core/src/core/topic_detail/session.rs b/rust/crates/fire-core/src/core/topic_detail/session.rs new file mode 100644 index 00000000..0a30b7b7 --- /dev/null +++ b/rust/crates/fire-core/src/core/topic_detail/session.rs @@ -0,0 +1,324 @@ + +use tokio::sync::{mpsc, oneshot}; + +use super::*; +use crate::error::FireCoreError; + +pub struct TopicDetailSession { + pub(super) topic_id: u64, + pub(super) owner_token: String, + pub(super) tx: mpsc::UnboundedSender, +} + +impl TopicDetailSession { + pub fn topic_id(&self) -> u64 { + self.topic_id + } + + pub fn owner_token(&self) -> &str { + &self.owner_token + } + + pub fn release_owner(&self, owner_token: &str) { + let _ = owner_token; + } + + pub fn reload( + &self, + target_post_number: Option, + force_load: bool, + track_visit: bool, + allow_suggested_unread_root: bool, + ) { + let _ = self.tx.send(Command::Reload { + target_post_number, + force_load, + track_visit, + allow_suggested_unread_root, + }); + } + + pub fn load_more(&self) { + let _ = self.tx.send(Command::LoadMore); + } + + pub fn note_visible_posts(&self, post_numbers: Vec) { + let _ = self.tx.send(Command::NoteVisible(post_numbers)); + } + + pub fn note_filtered_feed_tail(&self, item_count: u32, visible_max_item: Option) { + let _ = self.tx.send(Command::NoteTail { + item_count, + visible_max_item, + }); + } + + pub fn note_scroll_interaction(&self, active: bool) { + let _ = self.tx.send(Command::NoteScroll(active)); + } + + pub fn acknowledge_scroll_target(&self, post_number: u32) { + let _ = self.tx.send(Command::AckScroll(post_number)); + } + + pub fn clear_scroll_target(&self) { + let _ = self.tx.send(Command::ClearScroll); + } + + pub fn begin_reply_typing(&self) { + let _ = self.tx.send(Command::BeginTyping); + } + + pub fn end_reply_typing(&self) { + let _ = self.tx.send(Command::EndTyping); + } + + pub fn reload_ai_summary(&self, skip_age_check: bool) { + let _ = self.tx.send(Command::ReloadAi { skip_age_check }); + } + + pub fn load_reply_context(&self, post_id: u64) { + let _ = self.tx.send(Command::LoadReplyContext(post_id)); + } + + pub async fn prepare_edit(&self, post_id: u64) -> Result { + self.roundtrip(|reply| Command::PrepareEdit { post_id, reply }) + .await + } + + pub async fn ensure_flag_types(&self) -> Result<(), FireCoreError> { + self.roundtrip(|reply| Command::EnsureFlags { reply }).await + } + + pub async fn submit_reply( + &self, + raw: String, + reply_to_post_number: Option, + scroll_to_created: bool, + ) -> Result<(), FireCoreError> { + self.roundtrip(|reply| Command::SubmitReply { + raw, + reply_to_post_number, + scroll_to_created, + reply, + }) + .await + } + + pub async fn create_boost(&self, post_id: u64, raw: String) -> Result<(), FireCoreError> { + self.roundtrip(|reply| Command::CreateBoost { + post_id, + raw, + reply, + }) + .await + } + + pub async fn delete_boost(&self, post_id: u64, boost_id: u64) -> Result<(), FireCoreError> { + self.roundtrip(|reply| Command::DeleteBoost { + post_id, + boost_id, + reply, + }) + .await + } + + pub async fn update_post( + &self, + post_id: u64, + raw: String, + edit_reason: Option, + ) -> Result<(), FireCoreError> { + self.roundtrip(|reply| Command::UpdatePost { + post_id, + raw, + edit_reason, + reply, + }) + .await + } + + pub async fn delete_post(&self, post_id: u64) -> Result<(), FireCoreError> { + self.roundtrip(|reply| Command::DeletePost { post_id, reply }) + .await + } + + pub async fn recover_post(&self, post_id: u64) -> Result<(), FireCoreError> { + self.roundtrip(|reply| Command::RecoverPost { post_id, reply }) + .await + } + + pub async fn flag_post( + &self, + post_id: u64, + flag_type_id: u32, + message: Option, + ) -> Result<(), FireCoreError> { + self.roundtrip(|reply| Command::FlagPost { + post_id, + flag_type_id, + message, + reply, + }) + .await + } + + pub async fn set_liked(&self, post_id: u64, liked: bool) -> Result<(), FireCoreError> { + self.roundtrip(|reply| Command::SetLiked { + post_id, + liked, + reply, + }) + .await + } + + pub async fn toggle_reaction( + &self, + post_id: u64, + reaction_id: String, + ) -> Result<(), FireCoreError> { + self.roundtrip(|reply| Command::ToggleReaction { + post_id, + reaction_id, + reply, + }) + .await + } + + pub async fn vote_poll( + &self, + post_id: u64, + poll_name: String, + options: Vec, + ) -> Result<(), FireCoreError> { + self.roundtrip(|reply| Command::VotePoll { + post_id, + poll_name, + options, + reply, + }) + .await + } + + pub async fn unvote_poll(&self, post_id: u64, poll_name: String) -> Result<(), FireCoreError> { + self.roundtrip(|reply| Command::UnvotePoll { + post_id, + poll_name, + reply, + }) + .await + } + + pub async fn vote_topic(&self, voted: bool) -> Result<(), FireCoreError> { + self.roundtrip(|reply| Command::VoteTopic { voted, reply }) + .await + } + + pub async fn accept_solution(&self, post_id: u64, accepted: bool) -> Result<(), FireCoreError> { + self.roundtrip(|reply| Command::AcceptSolution { + post_id, + accepted, + reply, + }) + .await + } + + pub async fn create_bookmark( + &self, + bookmarkable_id: u64, + bookmarkable_type: String, + name: Option, + reminder_at: Option, + auto_delete_preference: Option, + ) -> Result<(), FireCoreError> { + self.roundtrip(|reply| Command::CreateBookmark { + bookmarkable_id, + bookmarkable_type, + name, + reminder_at, + auto_delete_preference, + reply, + }) + .await + } + + pub async fn update_bookmark( + &self, + bookmark_id: u64, + name: Option, + reminder_at: Option, + auto_delete_preference: Option, + ) -> Result<(), FireCoreError> { + self.roundtrip(|reply| Command::UpdateBookmark { + bookmark_id, + name, + reminder_at, + auto_delete_preference, + reply, + }) + .await + } + + pub async fn delete_bookmark(&self, bookmark_id: u64) -> Result<(), FireCoreError> { + self.roundtrip(|reply| Command::DeleteBookmark { bookmark_id, reply }) + .await + } + + pub async fn set_notification_level(&self, level: i32) -> Result<(), FireCoreError> { + self.roundtrip(|reply| Command::SetNotificationLevel { level, reply }) + .await + } + + pub async fn update_topic( + &self, + title: String, + category_id: u64, + tags: Vec, + ) -> Result<(), FireCoreError> { + self.roundtrip(|reply| Command::UpdateTopic { + title, + category_id, + tags, + reply, + }) + .await + } + + pub async fn report_timings( + &self, + topic_time_ms: u32, + timings: Vec, + ) -> Result { + self.roundtrip(|reply| Command::ReportTimings { + topic_time_ms, + timings, + reply, + }) + .await + } + + pub async fn sync_for_test(&self) { + let (tx, rx) = oneshot::channel(); + if self.tx.send(Command::Flush(tx)).is_err() { + return; + } + let _ = rx.await; + } + + async fn roundtrip(&self, command: F) -> Result + where + T: Send + 'static, + F: FnOnce(oneshot::Sender>) -> Command, + { + let (tx, rx) = oneshot::channel(); + self.tx.send(command(tx)).map_err(|_| session_closed())?; + rx.await.map_err(|_| session_closed())? + } +} + +fn session_closed() -> FireCoreError { + FireCoreError::InvalidArgument { + operation: "topic detail session", + details: "session is closed".to_string(), + } +} diff --git a/rust/crates/fire-core/src/core/topic_detail/summary.rs b/rust/crates/fire-core/src/core/topic_detail/summary.rs new file mode 100644 index 00000000..3aee8f39 --- /dev/null +++ b/rust/crates/fire-core/src/core/topic_detail/summary.rs @@ -0,0 +1,103 @@ + + +use super::super::topic_detail_project::project_history_rows; +use super::super::FireCore; +use super::*; +use crate::error::FireCoreError; + +impl ActorState { + pub(super) async fn maybe_fetch_summary(&mut self, core: &FireCore) { + let summarizable = self + .header + .as_ref() + .is_some_and(|header| header.summarizable); + if summarizable && self.summary.is_none() && !self.summary_loading { + self.fetch_summary(core, false).await; + } + } + + pub(super) async fn fetch_summary(&mut self, core: &FireCore, skip_age_check: bool) { + self.summary_loading = true; + self.summary_error = None; + self.publish(core, false); + match core + .fetch_topic_ai_summary(self.topic_id, skip_age_check) + .await + { + Ok(summary) => { + self.summary = summary; + self.summary_loading = false; + self.summary_error = None; + } + Err(error) => { + self.summary_loading = false; + self.summary_error = Some(error.to_string()); + } + } + self.publish(core, false); + } + + pub(super) async fn prepare_edit(&self, core: &FireCore, post_id: u64) -> Result { + if let Some(raw) = core.with_topic_source_session_mut(self.topic_id, None, |session| { + session + .post(post_id) + .and_then(|post| post.raw.clone()) + .filter(|raw| !raw.is_empty()) + }) { + if let Some(raw) = raw { + return Ok(raw); + } + } + let post = core.fetch_post(post_id).await?; + let raw = post.raw.clone().unwrap_or_default(); + core.with_topic_source_session_mut(self.topic_id, None, |session| { + session.merge_posts(std::iter::once(post)); + }); + Ok(raw) + } + + pub(super) async fn ensure_flags(&mut self, core: &FireCore) -> Result<(), FireCoreError> { + if !self.flag_types.is_empty() { + return Ok(()); + } + self.flag_types = core.fetch_post_action_types().await?; + self.publish(core, false); + Ok(()) + } + + + pub(super) async fn load_reply_context(&mut self, core: &FireCore, post_id: u64) { + self.loading_reply_context.insert(post_id); + self.publish(core, false); + let root_number = core + .with_topic_source_session_mut(self.topic_id, None, |session| { + session.post(post_id).map(|post| post.post_number) + }) + .flatten() + .unwrap_or(0); + let reply_ids = core.fetch_post_reply_ids(post_id).await.unwrap_or_default(); + let mut replies = Vec::new(); + for chunk in reply_ids.chunks(TOPIC_DETAIL_REPLY_CONTEXT_BATCH) { + if let Ok(posts) = core.fetch_topic_posts(self.topic_id, chunk.to_vec()).await { + replies.extend(posts); + } + } + let history = core + .fetch_post_reply_history(post_id) + .await + .unwrap_or_default(); + core.with_topic_source_session_mut(self.topic_id, None, |session| { + session.merge_posts(replies.iter().cloned()); + session.recompute_loaded_state(); + }); + let chrome = self.projection_chrome(core); + self.reply_context = Some(fire_models::TopicDetailReplyContext { + root_post_id: post_id, + appended_post_ids: replies.iter().map(|post| post.id).collect(), + history_rows: project_history_rows(&history, root_number, &chrome), + }); + self.loading_reply_context.remove(&post_id); + self.publish(core, true); + } + +} diff --git a/rust/crates/fire-core/src/core/topic_detail/tests.rs b/rust/crates/fire-core/src/core/topic_detail/tests.rs new file mode 100644 index 00000000..cac50c3d --- /dev/null +++ b/rust/crates/fire-core/src/core/topic_detail/tests.rs @@ -0,0 +1,112 @@ +use std::sync::{Arc, Mutex as StdMutex}; + +use fire_models::{TopicDetailUiSnapshot, TopicHeader, TopicPost}; + +use super::super::FireCore; +use super::{TopicDetailObserver, TopicDetailOpenRequest}; +use crate::config::FireCoreConfig; + + struct RecordingObserver { + snapshots: StdMutex>, + } + + impl TopicDetailObserver for RecordingObserver { + fn on_snapshot(&self, snapshot: TopicDetailUiSnapshot) { + self.snapshots.lock().expect("observer").push(snapshot); + } + } + + fn test_core() -> FireCore { + FireCore::new(FireCoreConfig::default()).expect("core") + } + + fn seed(core: &FireCore) { + let body = TopicPost { + id: 1, + username: "alice".into(), + cooked: "

op

".into(), + post_number: 1, + ..TopicPost::default() + }; + core.seed_topic_detail_source_for_test( + TopicHeader { + topic_id: 42, + title: "topic".into(), + slug: "topic".into(), + posts_count: 1, + ..TopicHeader::default() + }, + body, + Vec::new(), + vec![1], + ); + } + + fn open_request(owner: &str) -> TopicDetailOpenRequest { + TopicDetailOpenRequest { + topic_id: 42, + owner_token: owner.into(), + slug_hint: None, + target_post_number: None, + bypass_cache: false, + force_load: false, + track_visit: false, + allow_suggested_unread_root: false, + } + } + + #[tokio::test] + async fn same_owner_reopen_replaces_observer_and_release_keeps_the_other() { + let core = test_core(); + seed(&core); + let first = Arc::new(RecordingObserver { + snapshots: StdMutex::new(Vec::new()), + }); + let second = Arc::new(RecordingObserver { + snapshots: StdMutex::new(Vec::new()), + }); + let third = Arc::new(RecordingObserver { + snapshots: StdMutex::new(Vec::new()), + }); + let session = core.topic_detail_sessions.open( + &core, + open_request("owner-a"), + first.clone() as Arc, + ); + session.sync_for_test().await; + let first_count = first.snapshots.lock().expect("first").len(); + assert!(first_count >= 1); + + core.topic_detail_sessions.open( + &core, + open_request("owner-a"), + second.clone() as Arc, + ); + session.sync_for_test().await; + let first_after_replace = first.snapshots.lock().expect("first").len(); + assert!(second.snapshots.lock().expect("second").len() >= 1); + + core.topic_detail_sessions.open( + &core, + open_request("owner-b"), + third.clone() as Arc, + ); + session.sync_for_test().await; + assert_eq!(core.topic_detail_sessions.session_count(), 1); + + core.topic_detail_sessions.release(42, "owner-a"); + session.sync_for_test().await; + assert_eq!(core.topic_detail_sessions.session_count(), 1); + let third_before = third.snapshots.lock().expect("third").len(); + session.clear_scroll_target(); + session.sync_for_test().await; + assert!(third.snapshots.lock().expect("third").len() > third_before); + assert_eq!( + first.snapshots.lock().expect("first").len(), + first_after_replace + ); + + core.topic_detail_sessions.release(42, "owner-b"); + session.sync_for_test().await; + assert_eq!(core.topic_detail_sessions.session_count(), 0); + } diff --git a/rust/crates/fire-core/src/core/topic_detail/window.rs b/rust/crates/fire-core/src/core/topic_detail/window.rs new file mode 100644 index 00000000..8316dce6 --- /dev/null +++ b/rust/crates/fire-core/src/core/topic_detail/window.rs @@ -0,0 +1,253 @@ +use std::ops::Range; + + +use super::super::FireCore; +use super::*; + +impl ActorState { + pub(super) fn expand_window_for_visible(&mut self, core: &FireCore, visible: &[u32]) { + let Some(total) = core.with_topic_source_session_mut(self.topic_id, None, |session| { + session.raw_stream_len() + }) else { + return; + }; + let indices = visible + .iter() + .filter_map(|post_number| { + core.with_topic_source_session_mut(self.topic_id, None, |session| { + session.stream_index_for_post_number(*post_number) + }) + .flatten() + }) + .collect::>(); + let Some(min_index) = indices.iter().copied().min() else { + return; + }; + let Some(max_index) = indices.iter().copied().max() else { + return; + }; + let threshold = TOPIC_DETAIL_PREFETCH_THRESHOLD as usize; + let expand_back = self.window.requested.start > 0 + && min_index <= self.window.requested.start.saturating_add(threshold); + let expand_forward = self.window.requested.end < total + && max_index + 1 + >= self + .window + .requested + .end + .saturating_sub(threshold.saturating_add(1)) + .max(self.window.requested.start); + if expand_back || expand_forward { + let lower = if expand_back { + self.window + .requested + .start + .saturating_sub(TOPIC_DETAIL_HYDRATION_PAGE) + } else { + self.window.requested.start + }; + let upper = if expand_forward { + self.window.requested.end + TOPIC_DETAIL_FORWARD_EXPANSION as usize + } else { + self.window.requested.end + }; + let anchor = self.anchor_index(core); + self.window.requested = bounded_range(lower, upper, total, anchor); + } + } + + pub(super) fn advance_toward_target(&mut self, core: &FireCore, target: u32) -> bool { + let Some((total, current, loaded)) = + core.with_topic_source_session_mut(self.topic_id, None, |session| { + ( + session.raw_stream_len(), + self.window.requested.clone(), + session.loaded_post_numbers_in_range(self.window.requested.clone()), + ) + }) + else { + return false; + }; + let Some(next) = next_range_for_target(target, ¤t, total, &loaded) else { + return false; + }; + if next == self.window.requested { + return false; + } + self.window.requested = next; + true + } + + pub(super) fn reset_window(&mut self, core: &FireCore) { + let Some((total, loaded, anchor_index)) = + core.with_topic_source_session_mut(self.topic_id, None, |session| { + let total = session.raw_stream_len(); + let loaded = (0..total) + .filter(|index| session.missing_ids_in_range(*index..index + 1).is_empty()) + .collect::>(); + let anchor = self + .scroll_target + .and_then(|post_number| session.stream_index_for_post_number(post_number)); + (total, loaded, anchor) + }) + else { + return; + }; + self.window.anchor = self.scroll_target; + self.window.requested = initial_range(total, anchor_index, &loaded); + } + + pub(super) fn extend_window_to_loaded(&mut self, core: &FireCore) { + let Some(total) = core.with_topic_source_session_mut(self.topic_id, None, |session| { + session.raw_stream_len() + }) else { + return; + }; + if self.window.requested.end >= total.saturating_sub(TOPIC_DETAIL_HYDRATION_PAGE) { + self.window.requested.end = total; + self.window.requested = bounded_range( + self.window.requested.start, + self.window.requested.end, + total, + self.anchor_index(core), + ); + } + } + + pub(super) fn anchor_index(&self, core: &FireCore) -> Option { + let anchor = self.window.anchor.or(self.scroll_target)?; + core.with_topic_source_session_mut(self.topic_id, None, |session| { + session.stream_index_for_post_number(anchor) + }) + .flatten() + } + + pub(super) fn should_load_tail(&self, item_count: u32, visible_max_item: Option) -> bool { + let Some(visible_max_item) = visible_max_item else { + return false; + }; + let has_more = self + .published + .as_ref() + .is_some_and(|snapshot| snapshot.has_more); + item_count > 0 + && has_more + && item_count.saturating_sub(visible_max_item) <= TOPIC_DETAIL_LIST_TAIL_THRESHOLD + } + + pub(super) fn capture_header(&mut self, core: &FireCore) { + self.header = core + .clone_topic_source_snapshot(self.topic_id) + .map(|snapshot| snapshot.header); + } + + pub(super) fn restore_inflight_posts(&self, core: &FireCore) { + if self.inflight_posts.is_empty() { + return; + } + let posts = self.inflight_posts.clone(); + core.with_topic_source_session_mut(self.topic_id, None, |session| { + for (post_id, post) in posts { + if self.mutating.contains(&post_id) { + session.merge_posts(std::iter::once(post)); + } + } + }); + } + +} + +fn bounded_range(mut lower: usize, mut upper: usize, total: usize, anchor: Option) -> Range { + if total == 0 { + return 0..0; + } + lower = lower.min(total); + upper = upper.max(lower).min(total); + if lower == upper { + upper = (lower + 1).min(total); + } + if upper - lower <= TOPIC_DETAIL_MAX_WINDOW { + return lower..upper; + } + if let Some(anchor) = anchor { + let max_lower = total.saturating_sub(TOPIC_DETAIL_MAX_WINDOW); + let minimum = anchor.saturating_sub(TOPIC_DETAIL_MAX_WINDOW - 1); + let maximum = anchor.min(max_lower); + lower = minimum.max(lower.min(maximum)); + upper = (lower + TOPIC_DETAIL_MAX_WINDOW).min(total); + lower = upper.saturating_sub(TOPIC_DETAIL_MAX_WINDOW); + return lower..upper; + } + upper = (lower + TOPIC_DETAIL_MAX_WINDOW).min(total); + lower = upper.saturating_sub(TOPIC_DETAIL_MAX_WINDOW); + lower..upper +} + +fn initial_range(total: usize, anchor: Option, loaded: &[usize]) -> Range { + if total == 0 { + return 0..0; + } + let loaded_lower = loaded.first().copied().unwrap_or(anchor.unwrap_or(0)); + let loaded_upper = loaded + .last() + .map(|index| index + 1) + .unwrap_or((loaded_lower + 1).min(total)); + let desired_lower = if let Some(anchor) = anchor { + anchor.saturating_sub(TOPIC_DETAIL_HYDRATION_PAGE / 2) + } else { + loaded_lower.min(loaded_upper.saturating_sub(TOPIC_DETAIL_HYDRATION_PAGE)) + }; + bounded_range( + desired_lower.min(loaded_lower), + loaded_upper.max(loaded_lower + TOPIC_DETAIL_HYDRATION_PAGE), + total, + anchor, + ) +} + +fn next_range_for_target( + post_number: u32, + current: &Range, + total: usize, + loaded: &[u32], +) -> Option> { + if total == 0 || (current.start == 0 && current.end >= total) { + return None; + } + let estimated = (post_number.saturating_sub(1) as usize).min(total - 1); + if !current.contains(&estimated) { + return Some(bounded_range( + estimated.saturating_sub(TOPIC_DETAIL_HYDRATION_PAGE / 2), + estimated + TOPIC_DETAIL_HYDRATION_PAGE / 2 + 1, + total, + None, + )); + } + let forward = if let Some(max_loaded) = loaded.iter().copied().max() { + if post_number > max_loaded { + true + } else if loaded.iter().copied().min().is_some_and(|min| post_number < min) { + false + } else { + total - current.end >= current.start + } + } else { + true + }; + let next = if forward { + bounded_range( + current.start, + current.end + TOPIC_DETAIL_FORWARD_EXPANSION as usize, + total, + None, + ) + } else { + bounded_range( + current.start.saturating_sub(TOPIC_DETAIL_HYDRATION_PAGE), + current.end, + total, + None, + ) + }; + (next != *current).then_some(next) +} diff --git a/rust/crates/fire-core/src/core/topic_detail_project.rs b/rust/crates/fire-core/src/core/topic_detail_project.rs new file mode 100644 index 00000000..7fbee418 --- /dev/null +++ b/rust/crates/fire-core/src/core/topic_detail_project.rs @@ -0,0 +1,697 @@ +use std::collections::{HashMap, HashSet}; + +use fire_models::{ + TopicAiSummary, TopicDetailAuthorDisplay, TopicDetailBoostDisplay, TopicDetailBoostUserDisplay, + TopicDetailChrome, TopicDetailComposerModel, TopicDetailLoadError, TopicDetailNotice, + TopicDetailParticipantDisplay, TopicDetailPhase, TopicDetailPollDisplay, + TopicDetailReactionChip, TopicDetailReplyContext, TopicDetailReplyUserDisplay, + TopicDetailSidecarModel, TopicDetailSourceSnapshot, TopicDetailTypingUser, TopicDetailUiRow, + TopicDetailUiSnapshot, TopicHeader, TopicHomeRowCountPatch, TopicHomeUnreadDecision, TopicPost, + TopicPresenceUser, TopicTreePresentation, TopicTreeRow, +}; + +pub(crate) struct ProjectionChrome { + pub phase: TopicDetailPhase, + pub load_error: Option, + pub notice: Option, + pub is_loading_more: bool, + pub load_more_error: Option, + pub scroll_target_post_number: Option, + pub summary: Option, + pub summary_loading: bool, + pub summary_error: Option, + pub typing_users: Vec, + pub current_user_id: Option, + pub is_submitting: bool, + pub mutating: HashSet, + pub loading_reply_context: HashSet, + pub reply_context: Option, + pub flag_types: Vec, + pub home_row_patch: Option, + pub generation: u64, + pub collection_revision: u64, + pub chrome_revision: u64, + pub sidecar_revision: u64, + pub interaction_revision: u64, +} + +pub(crate) fn project_topic_detail_snapshot( + source: &TopicDetailSourceSnapshot, + tree: &TopicTreePresentation, + chrome: &ProjectionChrome, +) -> TopicDetailUiSnapshot { + let posts = posts_by_id(source); + let original_id = tree.original_post_id; + let mut rows = Vec::new(); + if let Some(post) = posts.get(&original_id).or_else(|| posts.get(&source.body.post.id)) { + rows.push(project_row( + post, + &TopicTreeRow { + post_id: post.id, + post_number: post.post_number, + root_post_number: post.post_number, + parent_post_number: None, + depth: 0, + preorder_index: 0, + has_children: tree.reply_rows.iter().any(|row| { + row.parent_post_number == Some(post.post_number) || row.depth == 1 + }), + sibling_index: 0, + is_last_sibling: true, + descendant_count: post.reply_count, + }, + true, + chrome, + )); + } + for tree_row in &tree.reply_rows { + if tree_row.post_id == original_id { + continue; + } + if let Some(post) = posts.get(&tree_row.post_id) { + rows.push(project_row(post, tree_row, false, chrome)); + } + } + + let header = &source.header; + TopicDetailUiSnapshot { + topic_id: header.topic_id, + generation: chrome.generation, + phase: chrome.phase, + load_error: chrome.load_error.clone(), + notice: chrome.notice.clone(), + has_more: !source.source_exhausted, + is_loading_more: chrome.is_loading_more, + load_more_error: chrome.load_more_error.clone(), + scroll_target_post_number: chrome.scroll_target_post_number, + collection_revision: chrome.collection_revision, + chrome_revision: chrome.chrome_revision, + sidecar_revision: chrome.sidecar_revision, + interaction_revision: chrome.interaction_revision, + chrome: project_chrome(header), + composer: TopicDetailComposerModel { + typing_users: chrome + .typing_users + .iter() + .filter(|user| Some(user.id) != chrome.current_user_id) + .map(|user| TopicDetailTypingUser { + id: user.id, + username: user.username.clone(), + avatar_template: user.avatar_template.clone(), + }) + .collect(), + is_submitting: chrome.is_submitting, + }, + sidecar: project_sidecar(chrome), + rows, + focused_reply_context: chrome.reply_context.clone(), + flag_types: chrome.flag_types.clone(), + home_row_patch: chrome.home_row_patch.clone(), + } +} + +pub(crate) fn project_history_rows( + posts: &[TopicPost], + root_post_number: u32, + chrome: &ProjectionChrome, +) -> Vec { + posts + .iter() + .map(|post| { + project_row( + post, + &TopicTreeRow { + post_id: post.id, + post_number: post.post_number, + root_post_number, + parent_post_number: post.reply_to_post_number, + depth: 1, + preorder_index: 0, + has_children: post.reply_count > 0, + sibling_index: 0, + is_last_sibling: true, + descendant_count: post.reply_count, + }, + false, + chrome, + ) + }) + .collect() +} + +fn project_sidecar(chrome: &ProjectionChrome) -> TopicDetailSidecarModel { + match &chrome.summary { + Some(summary) => TopicDetailSidecarModel { + summarized_text: Some(summary.summarized_text.clone()), + algorithm: summary.algorithm.clone(), + outdated: summary.outdated, + can_regenerate: summary.can_regenerate, + new_posts_since_summary: summary.new_posts_since_summary, + updated_at: summary.updated_at.clone(), + is_loading: chrome.summary_loading, + error: chrome.summary_error.clone(), + }, + None => TopicDetailSidecarModel { + summarized_text: None, + is_loading: chrome.summary_loading, + error: chrome.summary_error.clone(), + ..TopicDetailSidecarModel::default() + }, + } +} + +fn project_chrome(header: &TopicHeader) -> TopicDetailChrome { + TopicDetailChrome { + title: header.title.clone(), + slug: header.slug.clone(), + archetype: header.archetype.clone(), + bookmarked: header.bookmarked, + bookmark_id: header.bookmark_id, + bookmark_name: header.bookmark_name.clone(), + bookmark_reminder_at: header.bookmark_reminder_at.clone(), + notification_level: header.details.notification_level, + can_edit: header.details.can_edit, + category_id: header.category_id, + tags: header.tags.iter().map(|tag| tag.name.clone()).collect(), + views: header.views, + posts_count: header.posts_count, + reply_count: header.reply_count, + like_count: header.like_count, + vote_count: header.vote_count, + user_voted: header.user_voted, + can_vote: header.can_vote, + has_accepted_answer: header.has_accepted_answer, + created_at: header.created_at.clone(), + highest_post_number: header.highest_post_number, + last_read_post_number: header.last_read_post_number, + participants: header + .details + .participants + .iter() + .map(|participant| TopicDetailParticipantDisplay { + user_id: participant.user_id, + username: participant.username.clone().unwrap_or_default(), + name: participant.name.clone(), + }) + .collect(), + summarizable: header.summarizable, + } +} + +fn project_row( + post: &TopicPost, + tree_row: &TopicTreeRow, + is_original_post: bool, + chrome: &ProjectionChrome, +) -> TopicDetailUiRow { + let selected_id = post + .current_user_reaction + .as_ref() + .map(|reaction| reaction.id.clone()); + let reactions = post + .reactions + .iter() + .map(|reaction| { + TopicDetailReactionChip::from_reaction(reaction, Some(&reaction.id) == selected_id.as_ref()) + }) + .collect::>(); + let author = author_display(post); + let polls = post + .polls + .iter() + .map(TopicDetailPollDisplay::from) + .collect::>(); + let boosts = post + .boosts + .iter() + .map(|boost| TopicDetailBoostDisplay { + id: boost.id, + display_text: boost.display_text.clone(), + user: TopicDetailBoostUserDisplay { + id: boost.user.id, + username: boost.user.username.clone(), + name: boost.user.name.clone(), + avatar_template: boost.user.avatar_template.clone(), + }, + can_delete: boost.can_delete, + can_flag: boost.can_flag, + user_flag_status: boost.user_flag_status, + available_flags: boost.available_flags.clone(), + presentation: boost.presented.clone(), + }) + .collect::>(); + let is_mutating = chrome.mutating.contains(&post.id); + let is_loading_reply_context = chrome.loading_reply_context.contains(&post.id); + let mut row = TopicDetailUiRow { + post_id: post.id, + post_number: post.post_number, + root_post_number: tree_row.root_post_number, + parent_post_number: tree_row.parent_post_number, + depth: tree_row.depth, + has_children: tree_row.has_children, + is_last_sibling: tree_row.is_last_sibling, + descendant_count: tree_row.descendant_count, + author: author.clone(), + presentation: post.presented.clone(), + layout_checksum: 0, + interaction_checksum: 0, + created_at: post.created_at.clone(), + updated_at: post.updated_at.clone(), + post_type: post.post_type, + reply_count: post.reply_count, + reply_to_username: post + .reply_to_user + .as_ref() + .map(|user| user.username.clone()) + .or_else(|| { + post.reply_to_post_number + .map(|number| format!("#{number}")) + }), + reply_to_user: post.reply_to_user.as_ref().map(|user| TopicDetailReplyUserDisplay { + username: user.username.clone(), + name: user.name.clone(), + avatar_template: user.avatar_template.clone(), + }), + like_count: post.like_count, + reactions, + current_reaction_id: selected_id, + polls, + boosts, + accepted_answer: post.accepted_answer, + can_accept_answer: post.can_accept_answer, + can_unaccept_answer: post.can_unaccept_answer, + can_edit: post.can_edit, + can_delete: post.can_delete, + can_recover: post.can_recover, + can_boost: post.can_boost, + bookmarked: post.bookmarked, + bookmark_id: post.bookmark_id, + bookmark_name: post.bookmark_name.clone(), + bookmark_reminder_at: post.bookmark_reminder_at.clone(), + hidden: post.hidden, + is_mutating, + is_loading_reply_context, + is_original_post, + }; + row.layout_checksum = layout_checksum(&row); + row.interaction_checksum = interaction_checksum(&row); + row +} + +fn author_display(post: &TopicPost) -> TopicDetailAuthorDisplay { + let metadata = &post.author_metadata; + TopicDetailAuthorDisplay { + username: post.username.clone(), + name: post.name.clone(), + avatar_template: post.avatar_template.clone(), + user_id: metadata.user_id, + user_title: metadata.user_title.clone(), + primary_group_name: metadata.primary_group_name.clone(), + flair_url: metadata.flair_url.clone(), + flair_name: metadata.flair_name.clone(), + flair_bg_color: metadata.flair_bg_color.clone(), + flair_color: metadata.flair_color.clone(), + flair_group_id: metadata.flair_group_id, + moderator: metadata.moderator, + admin: metadata.admin, + group_moderator: metadata.group_moderator, + user_status_emoji: metadata.user_status_emoji.clone(), + user_status_description: metadata.user_status_description.clone(), + } +} + +fn posts_by_id(source: &TopicDetailSourceSnapshot) -> HashMap { + let mut posts = HashMap::new(); + posts.insert(source.body.post.id, source.body.post.clone()); + for post in &source.loaded_posts { + posts.insert(post.id, post.clone()); + } + posts +} + +pub(crate) fn unread_decision( + last_read: Option, + highest: u32, +) -> TopicHomeUnreadDecision { + match last_read { + None => TopicHomeUnreadDecision::WhenLastReadMissing, + Some(last_read) if last_read >= highest => TopicHomeUnreadDecision::CaughtUp, + Some(_) => TopicHomeUnreadDecision::StillUnread, + } +} + +pub(crate) fn home_row_patch_for_header(header: &TopicHeader) -> TopicHomeRowCountPatch { + TopicHomeRowCountPatch { + topic_id: header.topic_id, + posts_count: header.posts_count, + reply_count: header.reply_count, + views: header.views, + last_read_post_number: header.last_read_post_number, + highest_post_number: header.highest_post_number, + unread: unread_decision(header.last_read_post_number, header.highest_post_number), + } +} + +pub(crate) fn header_counts_changed(previous: &TopicHeader, next: &TopicHeader) -> bool { + previous.posts_count != next.posts_count + || previous.reply_count != next.reply_count + || previous.views != next.views + || previous.last_read_post_number != next.last_read_post_number + || previous.highest_post_number != next.highest_post_number +} + +/// Applies the patched-row unread formula. `has_unread_posts` is the row flag. +pub(crate) fn apply_home_unread_counts( + has_unread_posts: bool, + decision: TopicHomeUnreadDecision, + unread_posts: u32, + new_posts: u32, +) -> (u32, u32, bool) { + match decision { + TopicHomeUnreadDecision::WhenLastReadMissing => { + if has_unread_posts { + (unread_posts, new_posts, has_unread_posts) + } else { + (0, 0, has_unread_posts) + } + } + TopicHomeUnreadDecision::CaughtUp => (0, 0, false), + TopicHomeUnreadDecision::StillUnread => (unread_posts, new_posts, true), + } +} + +pub(crate) fn apply_patch_to_summary( + summary: &mut fire_models::TopicSummary, + patch: &TopicHomeRowCountPatch, + row_has_unread: Option, +) { + summary.posts_count = patch.posts_count; + summary.reply_count = patch.reply_count; + summary.views = patch.views; + summary.last_read_post_number = patch.last_read_post_number; + summary.highest_post_number = patch.highest_post_number; + let has_unread = row_has_unread.unwrap_or(summary.unread_posts > 0 || summary.new_posts > 0); + let (unread_posts, new_posts, _) = + apply_home_unread_counts(has_unread, patch.unread, summary.unread_posts, summary.new_posts); + summary.unread_posts = unread_posts; + summary.new_posts = new_posts; +} + +pub(crate) fn apply_patch_to_row(row: &mut fire_models::TopicRow, patch: &TopicHomeRowCountPatch) { + let (unread_posts, new_posts, has_unread) = apply_home_unread_counts( + row.has_unread_posts, + patch.unread, + row.topic.unread_posts, + row.topic.new_posts, + ); + row.topic.posts_count = patch.posts_count; + row.topic.reply_count = patch.reply_count; + row.topic.views = patch.views; + row.topic.last_read_post_number = patch.last_read_post_number; + row.topic.highest_post_number = patch.highest_post_number; + row.topic.unread_posts = unread_posts; + row.topic.new_posts = new_posts; + row.has_unread_posts = has_unread; +} + +pub(crate) fn structure_changed( + previous: Option<&TopicDetailUiSnapshot>, + next: &TopicDetailUiSnapshot, +) -> bool { + let Some(previous) = previous else { + return true; + }; + previous.phase != next.phase + || previous.load_error != next.load_error + || previous.has_more != next.has_more + || previous.is_loading_more != next.is_loading_more + || previous.load_more_error != next.load_more_error + || previous.rows.iter().map(|row| row.post_id).collect::>() + != next.rows.iter().map(|row| row.post_id).collect::>() +} + +pub(crate) fn layout_checksums_changed( + previous: Option<&TopicDetailUiSnapshot>, + next: &TopicDetailUiSnapshot, +) -> bool { + let Some(previous) = previous else { + return !next.rows.is_empty(); + }; + let previous_rows = previous + .rows + .iter() + .map(|row| (row.post_id, row.layout_checksum)) + .collect::>(); + next.rows.iter().any(|row| { + previous_rows + .get(&row.post_id) + .is_none_or(|checksum| *checksum != row.layout_checksum) + }) +} + +pub(crate) fn interaction_checksums_changed( + previous: Option<&TopicDetailUiSnapshot>, + next: &TopicDetailUiSnapshot, +) -> bool { + let Some(previous) = previous else { + return false; + }; + let previous_rows = previous + .rows + .iter() + .map(|row| (row.post_id, row.interaction_checksum)) + .collect::>(); + next.rows.iter().any(|row| { + previous_rows + .get(&row.post_id) + .is_some_and(|checksum| *checksum != row.interaction_checksum) + }) || previous.composer != next.composer +} + +pub(crate) fn chrome_fields_changed(previous: &TopicDetailChrome, next: &TopicDetailChrome) -> bool { + previous.title != next.title + || previous.slug != next.slug + || previous.bookmarked != next.bookmarked + || previous.bookmark_id != next.bookmark_id + || previous.bookmark_name != next.bookmark_name + || previous.bookmark_reminder_at != next.bookmark_reminder_at + || previous.notification_level != next.notification_level + || previous.can_edit != next.can_edit + || previous.category_id != next.category_id + || previous.tags != next.tags + || previous.vote_count != next.vote_count + || previous.user_voted != next.user_voted + || previous.can_vote != next.can_vote + || previous.has_accepted_answer != next.has_accepted_answer + || previous.participants != next.participants +} + +pub(crate) fn sidecar_changed( + previous: &TopicDetailSidecarModel, + next: &TopicDetailSidecarModel, + previous_notice: &Option, + next_notice: &Option, +) -> bool { + previous != next || previous_notice != next_notice +} + +fn layout_checksum(row: &TopicDetailUiRow) -> u64 { + let mut hasher = Hasher::new(); + hasher.u64(row.post_id); + hash_author(&mut hasher, &row.author); + hasher.sep(); + match row.presentation.get() { + Some(document) => hasher.u64(document.presentation().checksum), + None => hasher.str("pending"), + } + hasher.sep(); + hash_polls(&mut hasher, &row.polls); + hasher.sep(); + hash_boosts(&mut hasher, &row.boosts); + hasher.sep(); + hasher.bool(row.reactions.is_empty()); + hasher.finish() +} + +fn interaction_checksum(row: &TopicDetailUiRow) -> u64 { + let mut hasher = Hasher::new(); + hasher.u64(u64::from(row.post_number)); + hasher.sep(); + hasher.str(&row.author.username); + hasher.sep(); + hasher.str(row.author.avatar_template.as_deref().unwrap_or("")); + hasher.sep(); + hasher.str(row.created_at.as_deref().unwrap_or("")); + hasher.sep(); + hasher.str(row.updated_at.as_deref().unwrap_or("")); + hasher.sep(); + hasher.u64(u64::from(row.like_count)); + hasher.sep(); + hasher.u64(u64::from(row.reply_count)); + hasher.sep(); + for reaction in &row.reactions { + hasher.str(&reaction.id); + hasher.sep(); + hasher.str(reaction.kind.as_deref().unwrap_or("")); + hasher.sep(); + hasher.u64(u64::from(reaction.count)); + hasher.sep(); + match reaction.can_undo { + Some(value) => hasher.bool(value), + None => hasher.str(""), + } + hasher.sep(); + } + hasher.str(row.current_reaction_id.as_deref().unwrap_or("")); + hasher.sep(); + hasher.bool(row.accepted_answer); + hasher.bool(row.can_edit); + hasher.bool(row.can_delete); + hasher.bool(row.can_recover); + hasher.bool(row.hidden); + hasher.bool(row.bookmarked); + hasher.u64(row.bookmark_id.unwrap_or(0)); + hasher.str(row.bookmark_name.as_deref().unwrap_or("")); + hasher.str(row.bookmark_reminder_at.as_deref().unwrap_or("")); + hasher.bool(row.is_mutating); + hasher.bool(row.is_loading_reply_context); + hasher.finish() +} + +fn hash_author(hasher: &mut Hasher, author: &TopicDetailAuthorDisplay) { + hasher.str(&author.username); + hasher.sep(); + hasher.str(author.name.as_deref().unwrap_or("")); + hasher.sep(); + hasher.str(author.user_title.as_deref().unwrap_or("")); + hasher.sep(); + hasher.str(author.primary_group_name.as_deref().unwrap_or("")); + hasher.sep(); + hasher.str(author.flair_name.as_deref().unwrap_or("")); + hasher.sep(); + hasher.u64(author.user_id.unwrap_or(0)); + hasher.sep(); + hasher.str(author.flair_url.as_deref().unwrap_or("")); + hasher.sep(); + hasher.str(author.flair_bg_color.as_deref().unwrap_or("")); + hasher.sep(); + hasher.str(author.flair_color.as_deref().unwrap_or("")); + hasher.sep(); + hasher.u64(author.flair_group_id.unwrap_or(0)); + hasher.sep(); + hasher.bool(author.admin); + hasher.bool(author.moderator); + hasher.bool(author.group_moderator); + hasher.str(author.user_status_emoji.as_deref().unwrap_or("")); + hasher.str(author.user_status_description.as_deref().unwrap_or("")); +} + +fn hash_polls(hasher: &mut Hasher, polls: &[TopicDetailPollDisplay]) { + for poll in polls { + hasher.u64(poll.id); + hasher.str(&poll.name); + hasher.str(&poll.kind); + hasher.str(&poll.status); + hasher.str(&poll.results); + hasher.u64(u64::from(poll.voters)); + for vote in &poll.user_votes { + hasher.str(vote); + } + for option in &poll.options { + hasher.str(&option.id); + hasher.str(&option.html); + hasher.u64(u64::from(option.votes)); + } + hasher.sep(); + } +} + +fn hash_boosts(hasher: &mut Hasher, boosts: &[TopicDetailBoostDisplay]) { + for boost in boosts { + hasher.u64(boost.id); + hasher.str(&boost.user.username); + hasher.str(boost.user.name.as_deref().unwrap_or("")); + hasher.str(&boost.display_text); + let plain = boost + .presentation + .get() + .map(|document| document.presentation().plain_text.clone()) + .unwrap_or_default(); + hasher.str(&plain); + hasher.bool(boost.can_delete); + hasher.bool(boost.can_flag); + hasher.sep(); + } +} + +struct Hasher(u64); + +impl Hasher { + fn new() -> Self { + Self(0xcbf29ce484222325) + } + + fn byte(&mut self, byte: u8) { + self.0 ^= u64::from(byte); + self.0 = self.0.wrapping_mul(0x100000001b3); + } + + fn str(&mut self, value: &str) { + for byte in value.as_bytes() { + self.byte(*byte); + } + self.byte(0); + } + + fn u64(&mut self, value: u64) { + for byte in value.to_le_bytes() { + self.byte(byte); + } + } + + fn bool(&mut self, value: bool) { + self.byte(u8::from(value)); + } + + fn sep(&mut self) { + self.byte(0x1f); + } + + fn finish(self) -> u64 { + self.0 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn when_last_read_missing_zeros_counts_when_has_unread_is_false() { + let (unread, new_posts, flag) = apply_home_unread_counts( + false, + TopicHomeUnreadDecision::WhenLastReadMissing, + 4, + 2, + ); + assert_eq!((unread, new_posts, flag), (0, 0, false)); + } + + #[test] + fn when_last_read_missing_keeps_counts_when_has_unread_is_true() { + let (unread, new_posts, flag) = apply_home_unread_counts( + true, + TopicHomeUnreadDecision::WhenLastReadMissing, + 4, + 2, + ); + assert_eq!((unread, new_posts, flag), (4, 2, true)); + } + + #[test] + fn caught_up_zeros_and_clears_flag() { + let (unread, new_posts, flag) = + apply_home_unread_counts(true, TopicHomeUnreadDecision::CaughtUp, 3, 1); + assert_eq!((unread, new_posts, flag), (0, 0, false)); + } +} diff --git a/rust/crates/fire-core/src/core/topics.rs b/rust/crates/fire-core/src/core/topics.rs deleted file mode 100644 index 6e966f54..00000000 --- a/rust/crates/fire-core/src/core/topics.rs +++ /dev/null @@ -1,2233 +0,0 @@ -use std::collections::{BTreeMap, HashMap, HashSet}; -use std::time::Instant; - -use fire_models::{ - LoadMoreTopicPostsQuery, TopicAiSummary, TopicBody, TopicDetail, TopicDetailPage, - TopicDetailQuery, TopicDetailSourceAppend, TopicDetailSourceQuery, TopicDetailSourceSnapshot, - TopicHeader, TopicListKind, TopicListQuery, TopicListResponse, TopicLoadMoreOutcome, - TopicLoadMoreStopReason, TopicLoadedRange, TopicPost, TopicPostStream, TopicSourceCursor, - TopicThread, TopicTreePresentation, TopicTreePresentationQuery, TopicTreeRow, -}; -use http::StatusCode; -use serde_json::Value; -use tracing::{debug, info, warn}; - -use super::{network::expect_success, FireCore}; -use crate::{ - error::FireCoreError, - json_helpers::invalid_json, - topic_payloads::{ - parse_topic_ai_summary_value, parse_topic_post_stream_value, RawTopicDetail, - RawTopicListResponse, - }, -}; - -const TOPIC_POST_BATCH_SIZE: usize = 50; -const FETCH_TOPIC_AI_SUMMARY_OPERATION: &str = "fetch topic ai summary"; -const DEFAULT_TOPIC_INITIAL_BATCH_SIZE: u16 = 40; -const DEFAULT_TOPIC_LOAD_MORE_BATCH_SIZE: u16 = 40; -const DEFAULT_TOPIC_MAX_AUTO_BATCHES_PER_GESTURE: u8 = 3; -const DEFAULT_TOPIC_MAX_AUTO_POSTS_PER_GESTURE: u16 = 120; -const TOPIC_PARENT_HOP_LIMIT: usize = 32; -const TOPIC_LOAD_MORE_FAILURE_MESSAGE: &str = "topic source batch append failed"; - -#[derive(Default)] -pub(crate) struct FireTopicDetailSourceRuntime { - next_session_id: u64, - sessions_by_topic_id: HashMap, -} - -#[derive(Clone)] -struct TopicDetailSourceSession { - session_id: u64, - session_epoch: u64, - header: TopicHeader, - body_post_id: u64, - body_post_number: u32, - focused_post_number: Option, - raw_stream_ids: Vec, - posts_by_id: HashMap, - post_id_by_number: HashMap, - unavailable_post_ids: HashSet, - loaded_ranges: Vec, - next_stream_offset: usize, - last_loaded_post_id: Option, - source_exhausted: bool, - load_more_policy: TopicLoadMorePolicy, -} - -#[derive(Clone, Copy)] -struct TopicLoadMorePolicy { - batch_size: u16, - max_auto_batches_per_gesture: u8, - max_auto_posts_per_gesture: u16, - require_new_root_progress: bool, -} - -#[derive(Default)] -struct TopicUnreadRootAutoSeekStats { - chained_batches: u8, - chained_posts: u16, -} - -struct TopicDetailSourceSessionInit { - session_epoch: u64, - header: TopicHeader, - body_post: TopicPost, - focused_post_number: Option, - raw_stream_ids: Vec, - cached_posts: Vec, - unavailable_post_ids: HashSet, - load_more_policy: TopicLoadMorePolicy, -} - -impl FireCore { - pub async fn fetch_topic_detail_initial( - &self, - query: TopicDetailQuery, - ) -> Result { - let mut result = self.fetch_topic_detail_base(query, true).await?; - result.rebuild_timeline_entries(); - info!( - topic_id = result.id, - posts_count = result.posts_count, - post_stream_total = result.post_stream.stream.len(), - post_stream_len = result.post_stream.posts.len(), - timeline_entries = result.timeline_entries.len(), - "topic detail initial payload fetched successfully" - ); - Ok(result) - } - - pub async fn fetch_topic_list( - &self, - query: TopicListQuery, - ) -> Result { - info!( - kind = ?query.kind, - page = ?query.page, - category_slug = ?query.category_slug, - tag = ?query.tag, - topic_ids_count = query.topic_ids.len(), - "fetching topic list" - ); - - if matches!( - query.kind, - TopicListKind::Unread - | TopicListKind::Unseen - | TopicListKind::PrivateMessagesInbox - | TopicListKind::PrivateMessagesSent - ) && !self.snapshot().cookies.can_authenticate_requests() - { - warn!(kind = ?query.kind, "topic list fetch rejected: missing login session"); - return Err(FireCoreError::MissingLoginSession); - } - - let path = match query.kind { - TopicListKind::PrivateMessagesInbox | TopicListKind::PrivateMessagesSent => { - let snapshot = self.snapshot(); - let username = snapshot - .bootstrap - .current_username - .filter(|value| !value.trim().is_empty()) - .ok_or(FireCoreError::MissingLoginSession)?; - match query.kind { - TopicListKind::PrivateMessagesInbox => { - format!("/topics/private-messages/{username}.json") - } - TopicListKind::PrivateMessagesSent => { - format!("/topics/private-messages-sent/{username}.json") - } - _ => unreachable!(), - } - } - _ => query.api_path(), - }; - - let mut params = Vec::new(); - if let Some(page) = query.page { - if page > 0 { - params.push(("no_definitions", "true".to_string())); - params.push(("page", page.to_string())); - } - } - if !query.topic_ids.is_empty() { - params.push(( - "topic_ids", - query - .topic_ids - .iter() - .map(u64::to_string) - .collect::>() - .join(","), - )); - } - if let Some(order) = &query.order { - params.push(("order", order.clone())); - } - if let Some(ascending) = query.ascending { - params.push(("ascending", ascending.to_string())); - } - let primary_tag_as_query_param = query.category_slug.is_some().then(|| { - query - .tag - .as_ref() - .map(|tag| tag.trim()) - .filter(|tag| !tag.is_empty()) - .map(ToOwned::to_owned) - }); - for tag in primary_tag_as_query_param.into_iter().flatten() { - params.push(("tags[]", tag)); - } - for tag in &query.additional_tags { - params.push(("tags[]", tag.clone())); - } - if query.match_all_tags { - params.push(("match_all_tags", "true".to_string())); - } - - let cache_scope_key = topic_list_cache_scope_key(&query); - let cache_page = query.page.unwrap_or(0); - let traced = self.build_json_get_request("fetch topic list", &path, params, &[])?; - let (trace_id, response) = match self.execute_request(traced).await { - Ok(response) => response, - Err(error @ FireCoreError::Network { .. }) => { - if let Some(cached) = self.read_cached_topic_list(&cache_scope_key, cache_page)? { - warn!( - kind = ?query.kind, - page = ?query.page, - "topic list network fetch failed; returning cached page" - ); - return Ok(cached); - } - return Err(error); - } - Err(error) => return Err(error), - }; - let response = expect_success(self, "fetch topic list", trace_id, response).await?; - let raw: RawTopicListResponse = self - .read_response_json("fetch topic list", trace_id, response) - .await?; - let result: TopicListResponse = raw.into(); - self.write_cached_topic_list(&cache_scope_key, cache_page, &result); - info!( - kind = ?query.kind, - topic_count = result.topics.len(), - user_count = result.users.len(), - has_more = result.more_topics_url.is_some(), - "topic list fetched successfully" - ); - Ok(result) - } - - fn read_cached_topic_list( - &self, - scope_key: &str, - page: u32, - ) -> Result, FireCoreError> { - let auth_scope_hash = self.current_auth_scope_hash(); - let payload = { - let store = self - .shared_store - .lock() - .expect("shared store mutex poisoned"); - store.topic_list_cache_read(&auth_scope_hash, scope_key, page)? - }; - - let Some(payload) = payload else { - return Ok(None); - }; - - let mut cached: TopicListResponse = serde_json::from_str(&payload).map_err(|source| { - FireCoreError::ResponseDeserialize { - operation: "cached topic list", - source, - } - })?; - cached.is_cached = true; - Ok(Some(cached)) - } - - fn write_cached_topic_list(&self, scope_key: &str, page: u32, response: &TopicListResponse) { - let auth_scope_hash = self.current_auth_scope_hash(); - let mut cached = response.clone(); - cached.is_cached = false; - let payload = match serde_json::to_string(&cached) { - Ok(payload) => payload, - Err(error) => { - warn!(error = %error, "failed to serialize topic list cache payload"); - return; - } - }; - let result = self - .shared_store - .lock() - .expect("shared store mutex poisoned") - .topic_list_cache_write(&auth_scope_hash, scope_key, page, &payload); - if let Err(error) = result { - warn!(error = %error, "failed to write topic list cache"); - } - } - - pub async fn fetch_topic_detail( - &self, - query: TopicDetailQuery, - ) -> Result { - let mut result = self.fetch_topic_detail_base(query, true).await?; - if let Err(error) = self - .hydrate_topic_detail_posts(result.id, &mut result) - .await - { - warn!( - topic_id = result.id, - error = %error, - "topic detail hydration fell back to partially loaded posts" - ); - // Hydration builds timeline entries on success; build from partial data on failure. - result.rebuild_timeline_entries(); - } - info!( - topic_id = result.id, - posts_count = result.posts_count, - post_stream_total = result.post_stream.stream.len(), - post_stream_len = result.post_stream.posts.len(), - timeline_entries = result.timeline_entries.len(), - "topic detail fetched successfully" - ); - Ok(result) - } - - pub async fn fetch_topic_detail_source_snapshot( - &self, - query: TopicDetailSourceQuery, - ) -> Result { - let focused_post_number = query - .target_post_number - .filter(|post_number| *post_number > 1); - let initial_batch_size = normalized_topic_initial_batch_size(query.initial_batch_size); - let load_more_policy = TopicLoadMorePolicy { - batch_size: normalized_topic_load_more_batch_size(query.load_more_batch_size), - max_auto_batches_per_gesture: normalized_topic_auto_batch_limit( - query.max_auto_batches_per_gesture, - ), - max_auto_posts_per_gesture: normalized_topic_auto_post_limit( - query.max_auto_posts_per_gesture, - ), - require_new_root_progress: true, - }; - - let mut detail = self - .fetch_topic_detail_base( - TopicDetailQuery { - topic_id: query.topic_id, - post_number: focused_post_number, - track_visit: query.track_visit, - force_load: query.force_load, - filter: None, - username_filters: None, - filter_top_level_replies: false, - }, - false, - ) - .await?; - - // Mid-topic opens (`/t/{id}/{N}.json` from notifications) only embed a - // nearby posts chunk. OP/body is often absent from that chunk on large - // topics. Resolve body via stream head + post_ids[] first — never hard - // fail solely on posts.json?post_number=1 missing the OP payload. - let body_post = self - .resolve_topic_body_post(query.topic_id, &detail) - .await?; - if detail.post_stream.stream.is_empty() && body_post.id > 0 { - detail.post_stream.stream.push(body_post.id); - } - - if let Some(target_post_number) = focused_post_number.filter(|post_number| { - !detail - .post_stream - .posts - .iter() - .any(|post| post.post_number == *post_number) - }) { - detail.post_stream.posts.push( - self.resolve_topic_post_by_number( - query.topic_id, - target_post_number, - &detail.post_stream.stream, - ) - .await?, - ); - } - if !detail - .post_stream - .posts - .iter() - .any(|post| post.id == body_post.id) - { - detail.post_stream.posts.push(body_post.clone()); - } - - let initial_source_post_ids = detail - .post_stream - .stream - .iter() - .copied() - .take(usize::from(initial_batch_size)) - .collect::>(); - let missing_initial_post_ids = - missing_post_ids_from_ids(&initial_source_post_ids, &detail.post_stream.posts); - let fetched_initial_posts = if missing_initial_post_ids.is_empty() { - Vec::new() - } else { - self.fetch_topic_posts(query.topic_id, missing_initial_post_ids.clone()) - .await? - }; - let fetched_initial_post_ids = fetched_initial_posts - .iter() - .map(|post| post.id) - .collect::>(); - let initial_unavailable_post_ids = missing_initial_post_ids - .into_iter() - .filter(|post_id| !fetched_initial_post_ids.contains(post_id)) - .collect::>(); - detail.post_stream.posts = merge_topic_posts( - &detail.post_stream.stream, - std::mem::take(&mut detail.post_stream.posts), - fetched_initial_posts, - ); - - let header = detail.header(); - let session = TopicDetailSourceSession::new(TopicDetailSourceSessionInit { - session_epoch: self.current_session_epoch(), - header, - body_post, - focused_post_number, - raw_stream_ids: detail.post_stream.stream, - cached_posts: detail.post_stream.posts, - unavailable_post_ids: initial_unavailable_post_ids, - load_more_policy, - }); - - let snapshot = { - let mut runtime = self - .topic_detail_source - .lock() - .expect("topic detail source runtime lock poisoned"); - let next_session_id = runtime.next_session_id.saturating_add(1).max(1); - runtime.next_session_id = next_session_id; - let session = session.with_session_id(next_session_id); - let snapshot = session.source_snapshot(); - runtime.sessions_by_topic_id.insert(query.topic_id, session); - snapshot - }; - - Ok(snapshot) - } - - pub async fn fetch_topic_detail_page( - &self, - query: TopicDetailSourceQuery, - ) -> Result { - let topic_id = query.topic_id; - let should_seek_unread_root = - query.allow_suggested_unread_root && query.target_post_number.is_none(); - let source_started_at = Instant::now(); - let mut source_snapshot = self.fetch_topic_detail_source_snapshot(query).await?; - let source_fetch_ms = source_started_at.elapsed().as_millis(); - let tree_started_at = Instant::now(); - let mut tree_presentation = - build_topic_tree_presentation_from_source_snapshot(&source_snapshot); - let tree_presentation_ms = tree_started_at.elapsed().as_millis(); - let auto_seek_started_at = Instant::now(); - let auto_seek = if should_seek_unread_root { - self.extend_topic_source_to_unread_root_if_needed( - &mut source_snapshot, - &mut tree_presentation, - ) - .await? - } else { - TopicUnreadRootAutoSeekStats::default() - }; - let auto_seek_ms = auto_seek_started_at.elapsed().as_millis(); - info!( - topic_id, - source_fetch_ms, - tree_presentation_ms, - auto_unread_root_ms = auto_seek_ms, - auto_unread_root_batches = auto_seek.chained_batches, - auto_unread_root_posts = auto_seek.chained_posts, - source_loaded_posts = source_snapshot.loaded_posts.len(), - body_post_included = true, - cooked_byte_count = topic_detail_source_cooked_byte_count(&source_snapshot), - reply_rows = tree_presentation.reply_rows.len(), - visible_root_count = tree_presentation.visible_root_post_numbers.len(), - first_unread_root_post_number = ?tree_presentation.first_unread_root_post_number, - total_loaded_post_count = tree_presentation.total_loaded_post_count, - "topic detail page built" - ); - Ok(TopicDetailPage { - source_snapshot, - tree_presentation, - }) - } - - pub fn build_topic_tree_presentation( - &self, - query: TopicTreePresentationQuery, - ) -> TopicTreePresentation { - build_topic_tree_presentation_from_query(query) - } - - async fn extend_topic_source_to_unread_root_if_needed( - &self, - source_snapshot: &mut TopicDetailSourceSnapshot, - tree_presentation: &mut TopicTreePresentation, - ) -> Result { - let mut stats = TopicUnreadRootAutoSeekStats::default(); - if !topic_tree_needs_unread_root_extension(source_snapshot, tree_presentation) { - return Ok(stats); - } - - let Some(initial_cursor) = source_snapshot.source_cursor.clone() else { - return Ok(stats); - }; - let policy = self - .clone_active_source_session( - initial_cursor.topic_id, - initial_cursor.session_id, - None, - None, - )? - .load_more_policy; - let mut current_cursor = initial_cursor; - - while topic_tree_needs_unread_root_extension(source_snapshot, tree_presentation) { - let append_result = self.append_topic_source_batch(current_cursor.clone()).await; - let append = match append_result { - Ok(append) => append, - Err(error) => { - warn!( - topic_id = current_cursor.topic_id, - session_id = current_cursor.session_id, - batches = stats.chained_batches, - posts = stats.chained_posts, - error = %error, - "topic unread root auto seek stopped after source append failure" - ); - return Ok(stats); - } - }; - - stats.chained_batches = stats.chained_batches.saturating_add(1); - stats.chained_posts = stats - .chained_posts - .saturating_add(u16::try_from(append.appended_posts.len()).unwrap_or(u16::MAX)); - let session = self.clone_active_source_session( - current_cursor.topic_id, - current_cursor.session_id, - None, - None, - )?; - *source_snapshot = session.source_snapshot(); - *tree_presentation = - build_topic_tree_presentation_from_source_snapshot(source_snapshot); - - if !topic_tree_needs_unread_root_extension(source_snapshot, tree_presentation) - || source_snapshot.source_exhausted - || stats.chained_batches >= policy.max_auto_batches_per_gesture - || stats.chained_posts >= policy.max_auto_posts_per_gesture - { - return Ok(stats); - } - - let Some(next_cursor) = source_snapshot.source_cursor.clone() else { - return Ok(stats); - }; - current_cursor = next_cursor; - } - - Ok(stats) - } - - pub async fn append_topic_detail_source( - &self, - query: LoadMoreTopicPostsQuery, - ) -> Result { - self.append_topic_source_batch(query.cursor).await - } - - pub async fn load_more_topic_posts( - &self, - query: LoadMoreTopicPostsQuery, - ) -> Result { - let initial_session = self.clone_active_source_session( - query.cursor.topic_id, - query.cursor.session_id, - None, - None, - )?; - let initial_snapshot = initial_session.source_snapshot(); - let baseline_tree = build_topic_tree_presentation_from_source_snapshot(&initial_snapshot); - let baseline_visible_roots = baseline_tree.visible_root_post_numbers.clone(); - let policy = initial_session.load_more_policy; - - let mut current_cursor = query.cursor; - let mut latest_snapshot = initial_snapshot; - let mut latest_tree = baseline_tree; - let mut appended_posts = Vec::new(); - let mut chained_batches: u8 = 0; - let mut chained_posts: u16 = 0; - - loop { - let append_result = self.append_topic_source_batch(current_cursor.clone()).await; - let append = match append_result { - Ok(append) => append, - Err(error) if chained_batches == 0 => return Err(error), - Err(error) => { - warn!( - topic_id = current_cursor.topic_id, - session_id = current_cursor.session_id, - batches = chained_batches, - posts = chained_posts, - error = %error, - "{TOPIC_LOAD_MORE_FAILURE_MESSAGE}" - ); - latest_tree.gained_new_root_progress = gained_visible_root_progress( - &baseline_visible_roots, - &latest_tree.visible_root_post_numbers, - ); - return Ok(topic_load_more_outcome( - latest_snapshot, - appended_posts, - latest_tree, - chained_batches, - chained_posts, - TopicLoadMoreStopReason::RequestFailed, - )); - } - }; - - chained_batches = chained_batches.saturating_add(1); - chained_posts = chained_posts - .saturating_add(u16::try_from(append.appended_posts.len()).unwrap_or(u16::MAX)); - appended_posts.extend(append.appended_posts); - let session = self.clone_active_source_session( - current_cursor.topic_id, - current_cursor.session_id, - None, - None, - )?; - latest_snapshot = session.source_snapshot(); - latest_tree = build_topic_tree_presentation_from_source_snapshot(&latest_snapshot); - latest_tree.gained_new_root_progress = gained_visible_root_progress( - &baseline_visible_roots, - &latest_tree.visible_root_post_numbers, - ); - - if policy.require_new_root_progress && latest_tree.gained_new_root_progress { - return Ok(topic_load_more_outcome( - latest_snapshot, - appended_posts, - latest_tree, - chained_batches, - chained_posts, - TopicLoadMoreStopReason::GainedVisibleRootProgress, - )); - } - if latest_snapshot.source_exhausted { - return Ok(topic_load_more_outcome( - latest_snapshot, - appended_posts, - latest_tree, - chained_batches, - chained_posts, - TopicLoadMoreStopReason::SourceExhausted, - )); - } - if chained_batches >= policy.max_auto_batches_per_gesture { - return Ok(topic_load_more_outcome( - latest_snapshot, - appended_posts, - latest_tree, - chained_batches, - chained_posts, - TopicLoadMoreStopReason::MaxAutoBatchesReached, - )); - } - if chained_posts >= policy.max_auto_posts_per_gesture { - return Ok(topic_load_more_outcome( - latest_snapshot, - appended_posts, - latest_tree, - chained_batches, - chained_posts, - TopicLoadMoreStopReason::MaxAutoPostsReached, - )); - } - - let Some(next_cursor) = latest_snapshot.source_cursor.clone() else { - return Ok(topic_load_more_outcome( - latest_snapshot, - appended_posts, - latest_tree, - chained_batches, - chained_posts, - TopicLoadMoreStopReason::SourceExhausted, - )); - }; - current_cursor = next_cursor; - } - } - - pub async fn fetch_topic_posts( - &self, - topic_id: u64, - post_ids: Vec, - ) -> Result, FireCoreError> { - let requested_post_ids = ordered_unique_post_ids(post_ids); - if requested_post_ids.is_empty() { - return Ok(Vec::new()); - } - - let cached_posts = - self.cached_topic_posts_for_active_source_session(topic_id, &requested_post_ids); - let cached_post_ids = cached_posts - .iter() - .map(|post| post.id) - .collect::>(); - let missing_post_ids = requested_post_ids - .iter() - .copied() - .filter(|post_id| !cached_post_ids.contains(post_id)) - .collect::>(); - if missing_post_ids.is_empty() { - return Ok(topic_posts_for_requested_ids( - &requested_post_ids, - cached_posts, - Vec::new(), - )); - } - - let path = format!("/t/{topic_id}/posts.json"); - let params = missing_post_ids - .iter() - .copied() - .map(|post_id| ("post_ids[]", post_id.to_string())) - .chain(std::iter::once(("include_suggested", "false".to_string()))) - .collect::>(); - let traced = self.build_json_get_request("fetch topic posts", &path, params, &[])?; - let (trace_id, response) = self.execute_request(traced).await?; - let response = expect_success(self, "fetch topic posts", trace_id, response).await?; - let value: Value = self - .read_response_json("fetch topic posts", trace_id, response) - .await?; - let post_stream = - parse_topic_post_stream_value(value, self.base_url()).map_err(|source| { - FireCoreError::ResponseDeserialize { - operation: "fetch topic posts", - source, - } - })?; - let fetched_posts = post_stream.posts; - self.cache_topic_posts_for_active_source_session(topic_id, &fetched_posts); - if cached_posts.is_empty() { - return Ok(fetched_posts); - } - Ok(topic_posts_for_requested_ids( - &requested_post_ids, - cached_posts, - fetched_posts, - )) - } - - fn cached_topic_posts_for_active_source_session( - &self, - topic_id: u64, - post_ids: &[u64], - ) -> Vec { - let current_epoch = self.current_session_epoch(); - let runtime = self - .topic_detail_source - .lock() - .expect("topic detail source runtime lock poisoned"); - let Some(session) = runtime.sessions_by_topic_id.get(&topic_id) else { - return Vec::new(); - }; - if session.session_epoch != current_epoch { - return Vec::new(); - } - session.posts_for_ids(post_ids) - } - - fn cache_topic_posts_for_active_source_session(&self, topic_id: u64, posts: &[TopicPost]) { - if posts.is_empty() { - return; - } - let current_epoch = self.current_session_epoch(); - let mut runtime = self - .topic_detail_source - .lock() - .expect("topic detail source runtime lock poisoned"); - let Some(session) = runtime.sessions_by_topic_id.get_mut(&topic_id) else { - return; - }; - if session.session_epoch != current_epoch { - return; - } - session.merge_posts(posts.iter().cloned()); - } - - /// Resolve the topic body/OP used as tree root. - /// - /// Prefer payloads already in the detail chunk, then stream-head via - /// `post_ids[]`, then number-based / root-detail fallbacks. - async fn resolve_topic_body_post( - &self, - topic_id: u64, - detail: &TopicDetail, - ) -> Result { - if let Some(post) = detail - .post_stream - .posts - .iter() - .find(|post| post.post_number == 1) - .cloned() - { - return Ok(post); - } - - if let Some(first_id) = detail - .post_stream - .stream - .first() - .copied() - .filter(|post_id| *post_id > 0) - { - let posts = self.fetch_topic_posts(topic_id, vec![first_id]).await?; - if let Some(post) = posts.into_iter().find(|post| post.id == first_id) { - return Ok(post); - } - } - - if let Ok(post) = self - .resolve_topic_post_by_number(topic_id, 1, &detail.post_stream.stream) - .await - { - return Ok(post); - } - - // Last resort: unanchored topic detail always starts near the beginning. - let root = self - .fetch_topic_detail_base( - TopicDetailQuery { - topic_id, - post_number: None, - track_visit: false, - force_load: true, - filter: None, - username_filters: None, - filter_top_level_replies: false, - }, - false, - ) - .await?; - if let Some(post) = root - .post_stream - .posts - .iter() - .find(|post| post.post_number == 1) - .cloned() - { - return Ok(post); - } - root.post_stream - .posts - .into_iter() - .min_by_key(|post| post.post_number) - .ok_or_else(|| FireCoreError::ResponseDeserialize { - operation: "resolve topic body post", - source: invalid_json( - "topic detail did not include a body/original post payload".to_string(), - ), - }) - } - - async fn resolve_topic_post_by_number( - &self, - topic_id: u64, - post_number: u32, - stream_ids: &[u64], - ) -> Result { - // 1) Number-window posts.json (fast path when Discourse returns the floor). - if let Ok(post) = self.fetch_post_by_number(topic_id, post_number).await { - return Ok(post); - } - - // 2) Anchored topic detail around the floor — more reliable than posts.json - // for some large/complex topics where the number window omits the exact post. - let anchored = self - .fetch_topic_detail_base( - TopicDetailQuery { - topic_id, - post_number: Some(post_number), - track_visit: false, - force_load: true, - filter: None, - username_filters: None, - filter_top_level_replies: false, - }, - false, - ) - .await?; - if let Some(post) = anchored - .post_stream - .posts - .into_iter() - .find(|post| post.post_number == post_number) - { - return Ok(post); - } - - // 3) If stream is known and dense enough that index ~= post_number-1, try id. - // This is best-effort only (deleted posts create gaps). - if post_number > 0 { - let index = usize::try_from(post_number.saturating_sub(1)).unwrap_or(usize::MAX); - if let Some(post_id) = stream_ids.get(index).copied().filter(|id| *id > 0) { - let posts = self.fetch_topic_posts(topic_id, vec![post_id]).await?; - if let Some(post) = posts - .into_iter() - .find(|post| post.id == post_id || post.post_number == post_number) - { - return Ok(post); - } - } - } - - Err(FireCoreError::ResponseDeserialize { - operation: "resolve topic post by number", - source: invalid_json(format!( - "topic post stream did not contain post number {post_number}" - )), - }) - } - - async fn fetch_post_by_number( - &self, - topic_id: u64, - post_number: u32, - ) -> Result { - let path = format!("/t/{topic_id}/posts.json"); - let params = vec![ - ("post_number", post_number.to_string()), - ("asc", "true".to_string()), - ("include_suggested", "false".to_string()), - ]; - let traced = self.build_json_get_request("fetch post by number", &path, params, &[])?; - let (trace_id, response) = self.execute_request(traced).await?; - let response = expect_success(self, "fetch post by number", trace_id, response).await?; - let value: Value = self - .read_response_json("fetch post by number", trace_id, response) - .await?; - let post_stream = - parse_topic_post_stream_value(value, self.base_url()).map_err(|source| { - FireCoreError::ResponseDeserialize { - operation: "fetch post by number", - source, - } - })?; - post_stream - .posts - .into_iter() - .find(|post| post.post_number == post_number) - .ok_or_else(|| FireCoreError::ResponseDeserialize { - operation: "fetch post by number", - source: invalid_json(format!( - "topic post stream did not contain post number {post_number}" - )), - }) - } - - pub async fn fetch_topic_ai_summary( - &self, - topic_id: u64, - skip_age_check: bool, - ) -> Result, FireCoreError> { - info!(topic_id, skip_age_check, "fetching topic AI summary"); - - let path = format!("/discourse-ai/summarization/t/{topic_id}"); - let mut params = Vec::new(); - if skip_age_check { - params.push(("skip_age_check", "true".to_string())); - } - - let traced = - self.build_json_get_request(FETCH_TOPIC_AI_SUMMARY_OPERATION, &path, params, &[])?; - let (trace_id, response) = self.execute_request(traced).await?; - let response = match expect_success( - self, - FETCH_TOPIC_AI_SUMMARY_OPERATION, - trace_id, - response, - ) - .await - { - Ok(response) => response, - Err(FireCoreError::HttpStatus { - status, - body: _, - operation: FETCH_TOPIC_AI_SUMMARY_OPERATION, - }) if status == StatusCode::NOT_FOUND.as_u16() - || status == StatusCode::FORBIDDEN.as_u16() => - { - info!(topic_id, status, "topic AI summary is unavailable"); - return Ok(None); - } - Err(error) => return Err(error), - }; - let value: Value = self - .read_response_json(FETCH_TOPIC_AI_SUMMARY_OPERATION, trace_id, response) - .await?; - let summary = parse_topic_ai_summary_value(value).map_err(|source| { - FireCoreError::ResponseDeserialize { - operation: FETCH_TOPIC_AI_SUMMARY_OPERATION, - source, - } - })?; - info!( - topic_id, - has_summary = summary.is_some(), - "topic AI summary fetched successfully" - ); - Ok(summary) - } - - fn clone_active_source_session( - &self, - topic_id: u64, - session_id: u64, - expected_next_stream_offset: Option, - expected_last_loaded_post_id: Option, - ) -> Result { - let current_epoch = self.current_session_epoch(); - let runtime = self - .topic_detail_source - .lock() - .expect("topic detail source runtime lock poisoned"); - let Some(session) = runtime.sessions_by_topic_id.get(&topic_id) else { - return Err(FireCoreError::InvalidTopicSourceCursor { - topic_id, - session_id, - }); - }; - if session.session_id != session_id || session.session_epoch != current_epoch { - return Err(FireCoreError::InvalidTopicSourceCursor { - topic_id, - session_id, - }); - } - if let Some(expected_next_stream_offset) = expected_next_stream_offset { - if session.next_stream_offset != expected_next_stream_offset as usize - || session.last_loaded_post_id != expected_last_loaded_post_id - { - return Err(FireCoreError::InvalidTopicSourceCursor { - topic_id, - session_id, - }); - } - } - Ok(session.clone()) - } - - async fn append_topic_source_batch( - &self, - cursor: TopicSourceCursor, - ) -> Result { - let batch_size = normalized_topic_load_more_batch_size(cursor.batch_size); - let session = self.clone_active_source_session( - cursor.topic_id, - cursor.session_id, - Some(cursor.next_stream_offset), - cursor.last_loaded_post_id, - )?; - if session.source_exhausted { - return Ok(TopicDetailSourceAppend { - appended_posts: Vec::new(), - loaded_ranges: session.loaded_ranges, - source_cursor: None, - source_exhausted: true, - }); - } - - let batch_start_offset = session.next_stream_offset; - let batch_end_offset = session - .next_stream_offset - .saturating_add(usize::from(batch_size)) - .min(session.raw_stream_ids.len()); - let batch_post_ids = session.raw_stream_ids[batch_start_offset..batch_end_offset].to_vec(); - let previously_loaded_post_ids = batch_post_ids - .iter() - .copied() - .filter(|post_id| session.posts_by_id.contains_key(post_id)) - .collect::>(); - let missing_post_ids = batch_post_ids - .iter() - .copied() - .filter(|post_id| !previously_loaded_post_ids.contains(post_id)) - .collect::>(); - let mut fetched_posts = Vec::new(); - for post_ids in missing_post_ids.chunks(TOPIC_POST_BATCH_SIZE) { - fetched_posts.extend( - self.fetch_topic_posts(cursor.topic_id, post_ids.to_vec()) - .await?, - ); - } - let fetched_post_ids = fetched_posts - .iter() - .map(|post| post.id) - .collect::>(); - let unavailable_post_ids = missing_post_ids - .into_iter() - .filter(|post_id| !fetched_post_ids.contains(post_id)) - .collect::>(); - - let mut runtime = self - .topic_detail_source - .lock() - .expect("topic detail source runtime lock poisoned"); - let Some(session) = runtime.sessions_by_topic_id.get_mut(&cursor.topic_id) else { - return Err(FireCoreError::InvalidTopicSourceCursor { - topic_id: cursor.topic_id, - session_id: cursor.session_id, - }); - }; - if session.session_id != cursor.session_id - || session.session_epoch != self.current_session_epoch() - || session.next_stream_offset != cursor.next_stream_offset as usize - || session.last_loaded_post_id != cursor.last_loaded_post_id - { - return Err(FireCoreError::InvalidTopicSourceCursor { - topic_id: cursor.topic_id, - session_id: cursor.session_id, - }); - } - - session.merge_posts(fetched_posts); - session.mark_unavailable(unavailable_post_ids); - session.recompute_loaded_state(); - let appended_posts = batch_post_ids - .iter() - .filter(|post_id| !previously_loaded_post_ids.contains(post_id)) - .filter_map(|post_id| session.posts_by_id.get(post_id).cloned()) - .collect::>(); - Ok(TopicDetailSourceAppend { - appended_posts, - loaded_ranges: session.loaded_ranges.clone(), - source_cursor: session.source_cursor(), - source_exhausted: session.source_exhausted, - }) - } - - async fn fetch_topic_detail_base( - &self, - query: TopicDetailQuery, - include_thread_state: bool, - ) -> Result { - info!( - topic_id = query.topic_id, - post_number = ?query.post_number, - track_visit = query.track_visit, - "fetching topic detail" - ); - - let path = if let Some(post_number) = query.post_number { - format!("/t/{}/{}.json", query.topic_id, post_number) - } else { - format!("/t/{}.json", query.topic_id) - }; - - let mut params = Vec::new(); - if query.track_visit { - params.push(("track_visit", "true".to_string())); - } - if query.force_load { - params.push(("forceLoad", "true".to_string())); - } - if let Some(filter) = query.filter { - params.push(("filter", filter)); - } - if let Some(username_filters) = query.username_filters { - params.push(("username_filters", username_filters)); - } - if query.filter_top_level_replies { - params.push(("filter_top_level_replies", "true".to_string())); - } - - let mut extra_headers = Vec::new(); - if query.track_visit { - extra_headers.push(("Discourse-Track-View", "1".to_string())); - extra_headers.push(("Discourse-Track-View-Topic-Id", query.topic_id.to_string())); - } - - let traced = - self.build_json_get_request("fetch topic detail", &path, params, &extra_headers)?; - let (trace_id, response) = self.execute_request(traced).await?; - let response = expect_success(self, "fetch topic detail", trace_id, response).await?; - let raw: RawTopicDetail = self - .read_response_json("fetch topic detail", trace_id, response) - .await?; - let detail = raw.into_topic_detail(include_thread_state, self.base_url()); - ensure_requested_topic_detail(query.topic_id, detail.id)?; - Ok(detail) - } - - async fn hydrate_topic_detail_posts( - &self, - topic_id: u64, - detail: &mut TopicDetail, - ) -> Result<(), FireCoreError> { - let missing_post_ids = missing_topic_post_ids(&detail.post_stream); - if missing_post_ids.is_empty() { - return Ok(()); - } - - info!( - topic_id, - loaded_posts = detail.post_stream.posts.len(), - total_posts = detail.post_stream.stream.len(), - missing_posts = missing_post_ids.len(), - "hydrating missing topic posts" - ); - - let mut fetched_posts = Vec::with_capacity(missing_post_ids.len()); - for post_ids in missing_post_ids.chunks(TOPIC_POST_BATCH_SIZE) { - fetched_posts.extend(self.fetch_topic_posts(topic_id, post_ids.to_vec()).await?); - } - - if fetched_posts.is_empty() { - return Ok(()); - } - - detail.post_stream.posts = merge_topic_posts( - &detail.post_stream.stream, - std::mem::take(&mut detail.post_stream.posts), - fetched_posts, - ); - detail.thread = TopicThread::from_posts(&detail.post_stream.posts); - detail.flat_posts = detail.thread.flatten(&detail.post_stream.posts); - detail.rebuild_timeline_entries(); - - let remaining_missing = missing_topic_post_ids(&detail.post_stream); - if !remaining_missing.is_empty() { - warn!( - topic_id, - missing_posts = remaining_missing.len(), - loaded_posts = detail.post_stream.posts.len(), - total_posts = detail.post_stream.stream.len(), - "topic detail hydration completed with unresolved missing posts" - ); - } - - Ok(()) - } -} - -fn missing_topic_post_ids(post_stream: &TopicPostStream) -> Vec { - if post_stream.stream.len() <= post_stream.posts.len() { - return Vec::new(); - } - - let loaded_post_ids: HashSet = post_stream.posts.iter().map(|post| post.id).collect(); - post_stream - .stream - .iter() - .copied() - .filter(|post_id| !loaded_post_ids.contains(post_id)) - .collect() -} - -fn merge_topic_posts( - ordered_post_ids: &[u64], - existing_posts: Vec, - fetched_posts: Vec, -) -> Vec { - let mut posts_by_id: HashMap = HashMap::new(); - for post in existing_posts { - posts_by_id.insert(post.id, post); - } - for mut post in fetched_posts { - if let Some(existing) = posts_by_id.get(&post.id) { - post.reuse_presentation_from(existing); - } - posts_by_id.insert(post.id, post); - } - - let mut merged_posts = Vec::with_capacity(posts_by_id.len()); - for post_id in ordered_post_ids { - if let Some(post) = posts_by_id.remove(post_id) { - merged_posts.push(post); - } - } - - let mut trailing_posts: Vec = posts_by_id.into_values().collect(); - trailing_posts.sort_by_key(|post| (post.post_number, post.id)); - merged_posts.extend(trailing_posts); - merged_posts -} - -fn topic_posts_for_requested_ids( - requested_post_ids: &[u64], - cached_posts: Vec, - fetched_posts: Vec, -) -> Vec { - let mut posts_by_id: HashMap = cached_posts - .into_iter() - .chain(fetched_posts) - .map(|post| (post.id, post)) - .collect(); - - let mut ordered_posts = Vec::with_capacity(posts_by_id.len()); - for post_id in requested_post_ids { - if let Some(post) = posts_by_id.remove(post_id) { - ordered_posts.push(post); - } - } - - let mut trailing_posts: Vec = posts_by_id.into_values().collect(); - trailing_posts.sort_by_key(|post| (post.post_number, post.id)); - ordered_posts.extend(trailing_posts); - ordered_posts -} - -impl TopicDetailSourceSession { - fn new(init: TopicDetailSourceSessionInit) -> Self { - let TopicDetailSourceSessionInit { - session_epoch, - header, - body_post, - focused_post_number, - raw_stream_ids, - cached_posts, - unavailable_post_ids, - load_more_policy, - } = init; - let mut posts_by_id = HashMap::new(); - let mut post_id_by_number = HashMap::new(); - - post_id_by_number.insert(body_post.post_number, body_post.id); - posts_by_id.insert(body_post.id, body_post.clone()); - - for post in cached_posts { - post_id_by_number.insert(post.post_number, post.id); - posts_by_id.insert(post.id, post); - } - - let mut session = Self { - session_id: 0, - session_epoch, - header, - body_post_id: body_post.id, - body_post_number: body_post.post_number, - focused_post_number, - raw_stream_ids, - posts_by_id, - post_id_by_number, - unavailable_post_ids, - loaded_ranges: Vec::new(), - next_stream_offset: 0, - last_loaded_post_id: None, - source_exhausted: false, - load_more_policy, - }; - session.recompute_loaded_state(); - session - } - - fn with_session_id(mut self, session_id: u64) -> Self { - self.session_id = session_id; - self - } - - fn posts_for_ids(&self, post_ids: &[u64]) -> Vec { - post_ids - .iter() - .filter_map(|post_id| self.posts_by_id.get(post_id).cloned()) - .collect() - } - - fn merge_posts(&mut self, posts: impl IntoIterator) { - for mut post in posts { - self.unavailable_post_ids.remove(&post.id); - self.post_id_by_number.insert(post.post_number, post.id); - if let Some(existing) = self.posts_by_id.get(&post.id) { - post.reuse_presentation_from(existing); - } - self.posts_by_id.insert(post.id, post); - } - } - fn mark_unavailable(&mut self, post_ids: HashSet) { - for post_id in post_ids { - if !self.posts_by_id.contains_key(&post_id) { - self.unavailable_post_ids.insert(post_id); - } - } - } - - fn recompute_loaded_state(&mut self) { - self.loaded_ranges.clear(); - let mut active_range_start: Option = None; - let mut active_range_first_post_id: Option = None; - - for (offset, post_id) in self.raw_stream_ids.iter().copied().enumerate() { - if self.is_satisfied_post_id(post_id) { - if active_range_start.is_none() { - active_range_start = Some(offset); - active_range_first_post_id = Some(post_id); - } - continue; - } - - if let Some(start_offset) = active_range_start.take() { - self.loaded_ranges.push(TopicLoadedRange { - start_offset: start_offset as u32, - end_offset_exclusive: offset as u32, - first_post_id: active_range_first_post_id - .take() - .unwrap_or(self.raw_stream_ids[start_offset]), - last_post_id: self.raw_stream_ids[offset.saturating_sub(1)], - }); - } - } - - if let Some(start_offset) = active_range_start { - self.loaded_ranges.push(TopicLoadedRange { - start_offset: start_offset as u32, - end_offset_exclusive: self.raw_stream_ids.len() as u32, - first_post_id: active_range_first_post_id - .unwrap_or(self.raw_stream_ids[start_offset]), - last_post_id: self - .raw_stream_ids - .last() - .copied() - .unwrap_or(self.body_post_id), - }); - } - - self.next_stream_offset = self - .raw_stream_ids - .iter() - .take_while(|post_id| self.is_satisfied_post_id(**post_id)) - .count(); - self.last_loaded_post_id = self - .next_stream_offset - .checked_sub(1) - .and_then(|offset| self.raw_stream_ids.get(offset).copied()); - self.source_exhausted = self.next_stream_offset >= self.raw_stream_ids.len(); - } - - fn source_cursor(&self) -> Option { - (!self.source_exhausted).then_some(TopicSourceCursor { - topic_id: self.header.topic_id, - session_id: self.session_id, - next_stream_offset: self.next_stream_offset as u32, - last_loaded_post_id: self.last_loaded_post_id, - batch_size: self.load_more_policy.batch_size, - }) - } - - fn source_snapshot(&self) -> TopicDetailSourceSnapshot { - TopicDetailSourceSnapshot { - header: self.header.clone(), - body: TopicBody { - post: self.body_post(), - }, - raw_stream_ids: self.raw_stream_ids.clone(), - loaded_posts: self.ordered_loaded_posts(), - loaded_ranges: self.loaded_ranges.clone(), - source_cursor: self.source_cursor(), - source_exhausted: self.source_exhausted, - focused_post_number: self.focused_post_number, - } - } - - fn body_post(&self) -> TopicPost { - self.posts_by_id - .get(&self.body_post_id) - .cloned() - .or_else(|| { - self.post_id_by_number - .get(&self.body_post_number) - .and_then(|post_id| self.posts_by_id.get(post_id)) - .cloned() - }) - .expect("topic detail source session missing body post") - } - - fn ordered_loaded_posts(&self) -> Vec { - merge_topic_posts( - &self.raw_stream_ids, - self.posts_by_id.values().cloned().collect(), - Vec::new(), - ) - } - - fn is_satisfied_post_id(&self, post_id: u64) -> bool { - self.posts_by_id.contains_key(&post_id) || self.unavailable_post_ids.contains(&post_id) - } -} - -fn build_topic_tree_presentation_from_query( - query: TopicTreePresentationQuery, -) -> TopicTreePresentation { - let mut ordered_posts = deduplicate_topic_posts_by_id(merge_topic_posts( - &query.raw_stream_ids, - query.loaded_posts, - Vec::new(), - )); - if !ordered_posts - .iter() - .any(|post| post.id == query.body_post.id) - { - ordered_posts.push(query.body_post.clone()); - ordered_posts = deduplicate_topic_posts_by_id(merge_topic_posts( - &query.raw_stream_ids, - ordered_posts, - Vec::new(), - )); - } - - let original_post = ordered_posts - .iter() - .find(|post| { - post.id == query.body_post.id || post.post_number == query.body_post.post_number - }) - .cloned() - .unwrap_or(query.body_post); - - let mut posts_by_id = HashMap::new(); - let mut posts_by_number = HashMap::new(); - for post in ordered_posts { - posts_by_number.insert(post.post_number, post.clone()); - posts_by_id.insert(post.id, post); - } - - let stream_index_by_post_id = query - .raw_stream_ids - .iter() - .enumerate() - .map(|(index, post_id)| (*post_id, index)) - .collect::>(); - - let mut children_by_parent = BTreeMap::>::new(); - for post in posts_by_id.values() { - if post.id == original_post.id { - continue; - } - let parent_post_number = resolve_tree_attachment_parent_post_number( - post, - &posts_by_number, - original_post.post_number, - ); - children_by_parent - .entry(parent_post_number) - .or_default() - .push(post.id); - } - - for child_post_ids in children_by_parent.values_mut() { - child_post_ids.sort_by_key(|post_id| { - let stream_index = stream_index_by_post_id - .get(post_id) - .copied() - .unwrap_or(usize::MAX); - let post_key = posts_by_id - .get(post_id) - .map(|post| (post.post_number, post.id)) - .unwrap_or((u32::MAX, u64::MAX)); - (stream_index, post_key.0, post_key.1) - }); - } - - let mut reply_rows = Vec::new(); - let mut visible_root_post_numbers = Vec::new(); - let mut visited = HashSet::new(); - let root_children = children_by_parent - .get(&original_post.post_number) - .cloned() - .unwrap_or_default(); - append_tree_rows_preorder( - &root_children, - original_post.post_number, - 0, - None, - &posts_by_id, - &children_by_parent, - &mut visited, - &mut reply_rows, - &mut visible_root_post_numbers, - ); - - let mut orphan_post_ids = query - .raw_stream_ids - .iter() - .copied() - .filter(|post_id| { - posts_by_id.contains_key(post_id) - && *post_id != original_post.id - && !visited.contains(post_id) - }) - .collect::>(); - orphan_post_ids.extend( - posts_by_id - .keys() - .copied() - .filter(|post_id| *post_id != original_post.id && !visited.contains(post_id)), - ); - orphan_post_ids = ordered_unique_post_ids(orphan_post_ids); - if !orphan_post_ids.is_empty() { - append_tree_rows_preorder( - &orphan_post_ids, - original_post.post_number, - 0, - None, - &posts_by_id, - &children_by_parent, - &mut visited, - &mut reply_rows, - &mut visible_root_post_numbers, - ); - } - - TopicTreePresentation { - original_post_id: original_post.id, - original_post_number: original_post.post_number, - first_unread_root_post_number: first_unread_root_post_number( - &reply_rows, - original_post.post_number, - query.last_read_post_number, - ), - reply_rows, - total_loaded_post_count: posts_by_id.len() as u32, - visible_root_post_numbers, - gained_new_root_progress: false, - } -} - -fn build_topic_tree_presentation_from_source_snapshot( - snapshot: &TopicDetailSourceSnapshot, -) -> TopicTreePresentation { - build_topic_tree_presentation_from_query(TopicTreePresentationQuery { - body_post: snapshot.body.post.clone(), - raw_stream_ids: snapshot.raw_stream_ids.clone(), - loaded_posts: snapshot.loaded_posts.clone(), - focused_post_number: snapshot.focused_post_number, - last_read_post_number: snapshot.header.last_read_post_number, - }) -} - -fn topic_tree_needs_unread_root_extension( - snapshot: &TopicDetailSourceSnapshot, - presentation: &TopicTreePresentation, -) -> bool { - let Some(last_read_post_number) = snapshot.header.last_read_post_number else { - return false; - }; - last_read_post_number > 0 - && last_read_post_number < snapshot.header.highest_post_number - && presentation.first_unread_root_post_number.is_none() - && !snapshot.source_exhausted -} - -fn first_unread_root_post_number( - reply_rows: &[TopicTreeRow], - original_post_number: u32, - last_read_post_number: Option, -) -> Option { - let last_read_post_number = last_read_post_number?; - reply_rows - .iter() - .find(|row| { - row.parent_post_number == Some(original_post_number) - && row.post_number > last_read_post_number - }) - .map(|row| row.post_number) -} - -fn topic_detail_source_cooked_byte_count(snapshot: &TopicDetailSourceSnapshot) -> usize { - let mut seen_post_ids = HashSet::new(); - let mut total = 0usize; - for post in std::iter::once(&snapshot.body.post).chain(snapshot.loaded_posts.iter()) { - if seen_post_ids.insert(post.id) { - total += post.cooked.len(); - } - } - total -} - -#[allow(clippy::too_many_arguments)] -fn append_tree_rows_preorder( - child_post_ids: &[u64], - parent_post_number: u32, - parent_depth: u16, - current_root_post_number: Option, - posts_by_id: &HashMap, - children_by_parent: &BTreeMap>, - visited: &mut HashSet, - reply_rows: &mut Vec, - visible_root_post_numbers: &mut Vec, -) -> u32 { - let mut descendant_total = 0_u32; - - for (sibling_index, child_post_id) in child_post_ids.iter().copied().enumerate() { - if !visited.insert(child_post_id) { - continue; - } - let Some(post) = posts_by_id.get(&child_post_id).cloned() else { - continue; - }; - let root_post_number = current_root_post_number.unwrap_or(post.post_number); - if current_root_post_number.is_none() - && visible_root_post_numbers.last().copied() != Some(root_post_number) - { - visible_root_post_numbers.push(root_post_number); - } - - let row_index = reply_rows.len(); - let grand_children = children_by_parent - .get(&post.post_number) - .cloned() - .unwrap_or_default(); - reply_rows.push(TopicTreeRow { - post_id: post.id, - post_number: post.post_number, - root_post_number, - parent_post_number: Some(parent_post_number), - depth: parent_depth.saturating_add(1), - preorder_index: row_index as u32, - has_children: !grand_children.is_empty(), - sibling_index: sibling_index as u16, - is_last_sibling: sibling_index + 1 == child_post_ids.len(), - descendant_count: 0, - }); - let nested_descendant_count = append_tree_rows_preorder( - &grand_children, - post.post_number, - parent_depth.saturating_add(1), - Some(root_post_number), - posts_by_id, - children_by_parent, - visited, - reply_rows, - visible_root_post_numbers, - ); - reply_rows[row_index].descendant_count = nested_descendant_count; - descendant_total = descendant_total.saturating_add(1 + nested_descendant_count); - } - - descendant_total -} - -fn resolve_tree_attachment_parent_post_number( - post: &TopicPost, - posts_by_number: &HashMap, - body_post_number: u32, -) -> u32 { - let Some(declared_parent) = normalized_reply_target(post.reply_to_post_number) else { - return body_post_number; - }; - if declared_parent == body_post_number || declared_parent == post.post_number { - if declared_parent == post.post_number { - debug!( - post_number = post.post_number, - declared_parent, - body_post_number, - "topic tree attachment parent fell back to body: post replies to itself" - ); - } - return body_post_number; - } - if !posts_by_number.contains_key(&declared_parent) { - debug!( - post_number = post.post_number, - declared_parent, - body_post_number, - "topic tree attachment parent fell back to body: declared parent missing from loaded posts" - ); - return body_post_number; - } - - let mut current_parent = declared_parent; - let mut visited = [0_u32; TOPIC_PARENT_HOP_LIMIT + 1]; - visited[0] = post.post_number; - for visited_len in (1..).take(TOPIC_PARENT_HOP_LIMIT) { - if visited[..visited_len].contains(¤t_parent) { - debug!( - post_number = post.post_number, - declared_parent, - current_parent, - body_post_number, - "topic tree attachment parent fell back to body: detected reply cycle" - ); - return body_post_number; - } - visited[visited_len] = current_parent; - let Some(parent_post) = posts_by_number.get(¤t_parent) else { - debug!( - post_number = post.post_number, - declared_parent, - current_parent, - body_post_number, - "topic tree attachment parent fell back to body: ancestor disappeared from loaded posts" - ); - return body_post_number; - }; - match normalized_reply_target(parent_post.reply_to_post_number) { - Some(next_parent) if next_parent == body_post_number => return declared_parent, - Some(next_parent) if next_parent == parent_post.post_number => { - debug!( - post_number = post.post_number, - declared_parent, - current_parent, - body_post_number, - "topic tree attachment parent fell back to body: ancestor replies to itself" - ); - return body_post_number; - } - Some(next_parent) => { - current_parent = next_parent; - } - None => return declared_parent, - } - } - - debug!( - post_number = post.post_number, - declared_parent, - body_post_number, - hop_limit = TOPIC_PARENT_HOP_LIMIT, - "topic tree attachment parent fell back to body: exceeded parent hop limit" - ); - body_post_number -} - -fn normalized_reply_target(reply_to_post_number: Option) -> Option { - reply_to_post_number.filter(|post_number| *post_number > 0) -} - -fn missing_post_ids_from_ids(ordered_post_ids: &[u64], loaded_posts: &[TopicPost]) -> Vec { - let loaded_post_ids: HashSet = loaded_posts.iter().map(|post| post.id).collect(); - ordered_post_ids - .iter() - .copied() - .filter(|post_id| !loaded_post_ids.contains(post_id)) - .collect() -} - -fn ordered_unique_post_ids(ids: Vec) -> Vec { - let mut seen = HashSet::new(); - let mut result = Vec::with_capacity(ids.len()); - for post_id in ids { - if post_id > 0 && seen.insert(post_id) { - result.push(post_id); - } - } - result -} - -fn ensure_requested_topic_detail( - requested_topic_id: u64, - actual_topic_id: u64, -) -> Result<(), FireCoreError> { - if requested_topic_id == actual_topic_id { - return Ok(()); - } - Err(FireCoreError::UnexpectedTopicDetail { - requested_topic_id, - actual_topic_id, - }) -} - -fn normalized_topic_initial_batch_size(batch_size: u16) -> u16 { - if batch_size == 0 { - DEFAULT_TOPIC_INITIAL_BATCH_SIZE - } else { - batch_size - } -} - -fn topic_load_more_outcome( - source_snapshot: TopicDetailSourceSnapshot, - appended_posts: Vec, - tree_presentation: TopicTreePresentation, - chained_batches: u8, - chained_posts: u16, - stop_reason: TopicLoadMoreStopReason, -) -> TopicLoadMoreOutcome { - TopicLoadMoreOutcome { - source_snapshot, - appended_posts, - tree_presentation, - chained_batches, - chained_posts, - stop_reason, - } -} - -fn normalized_topic_load_more_batch_size(batch_size: u16) -> u16 { - if batch_size == 0 { - DEFAULT_TOPIC_LOAD_MORE_BATCH_SIZE - } else { - batch_size - } -} - -fn normalized_topic_auto_batch_limit(limit: u8) -> u8 { - if limit == 0 { - DEFAULT_TOPIC_MAX_AUTO_BATCHES_PER_GESTURE - } else { - limit - } -} - -fn normalized_topic_auto_post_limit(limit: u16) -> u16 { - if limit == 0 { - DEFAULT_TOPIC_MAX_AUTO_POSTS_PER_GESTURE - } else { - limit - } -} - -fn gained_visible_root_progress(previous: &[u32], current: &[u32]) -> bool { - let previous_roots = previous.iter().copied().collect::>(); - current - .iter() - .copied() - .any(|post_number| !previous_roots.contains(&post_number)) -} - -fn deduplicate_topic_posts_by_id(posts: Vec) -> Vec { - let mut seen_post_ids = HashSet::new(); - let mut deduplicated = Vec::with_capacity(posts.len()); - for post in posts { - if seen_post_ids.insert(post.id) { - deduplicated.push(post); - } - } - deduplicated -} - -fn topic_list_cache_scope_key(query: &TopicListQuery) -> String { - let mut parts = vec![ - format!("kind={}", query.kind.filter_name()), - format!( - "category_slug={}", - query.category_slug.as_deref().unwrap_or("") - ), - format!( - "category_id={}", - query.category_id.map_or(String::new(), |id| id.to_string()) - ), - format!( - "parent_category_slug={}", - query.parent_category_slug.as_deref().unwrap_or("") - ), - format!("tag={}", normalized_cache_value(query.tag.as_deref())), - format!("order={}", query.order.as_deref().unwrap_or("")), - format!( - "ascending={}", - query - .ascending - .map_or(String::new(), |value| value.to_string()) - ), - format!("match_all_tags={}", query.match_all_tags), - ]; - - let mut topic_ids = query.topic_ids.clone(); - topic_ids.sort_unstable(); - parts.push(format!( - "topic_ids={}", - topic_ids - .iter() - .map(u64::to_string) - .collect::>() - .join(",") - )); - - parts.push(format!( - "additional_tags={}", - query - .additional_tags - .iter() - .map(|tag| normalized_cache_value(Some(tag))) - .collect::>() - .join(",") - )); - - parts.join("|") -} - -fn normalized_cache_value(value: Option<&str>) -> String { - value.unwrap_or("").trim().to_ascii_lowercase() -} - -#[cfg(test)] -mod tests { - use super::*; - - fn make_topic_post(post_number: u32, reply_to_post_number: Option) -> TopicPost { - TopicPost { - id: u64::from(post_number), - username: format!("user-{post_number}"), - cooked: format!("

{post_number}

"), - post_number, - reply_to_post_number, - ..TopicPost::default() - } - } - - #[test] - fn resolve_tree_attachment_parent_falls_back_to_body_when_intermediate_is_missing() { - let body_post = make_topic_post(1, None); - let post = make_topic_post(5, Some(3)); - let posts_by_number = HashMap::from([ - (body_post.post_number, body_post.clone()), - (post.post_number, post.clone()), - ]); - - let attachment_parent = resolve_tree_attachment_parent_post_number( - &post, - &posts_by_number, - body_post.post_number, - ); - - assert_eq!(attachment_parent, body_post.post_number); - } - - #[test] - fn resolve_tree_attachment_parent_falls_back_to_body_when_cycle_is_detected() { - let body_post = make_topic_post(1, None); - let post = make_topic_post(3, Some(4)); - let parent = make_topic_post(4, Some(3)); - let posts_by_number = HashMap::from([ - (body_post.post_number, body_post.clone()), - (post.post_number, post.clone()), - (parent.post_number, parent), - ]); - - let attachment_parent = resolve_tree_attachment_parent_post_number( - &post, - &posts_by_number, - body_post.post_number, - ); - - assert_eq!(attachment_parent, body_post.post_number); - } - - #[test] - fn resolve_tree_attachment_parent_falls_back_to_body_after_hop_limit() { - let body_post = make_topic_post(1, None); - let mut posts_by_number = HashMap::from([(body_post.post_number, body_post.clone())]); - - for post_number in 2..=36 { - let reply_to_post_number = if post_number == 3 { - Some(body_post.post_number) - } else { - Some(post_number - 1) - }; - let post = make_topic_post(post_number, reply_to_post_number); - posts_by_number.insert(post.post_number, post); - } - - let post = posts_by_number - .get(&36) - .expect("missing deep descendant post"); - let attachment_parent = resolve_tree_attachment_parent_post_number( - post, - &posts_by_number, - body_post.post_number, - ); - - assert_eq!(attachment_parent, body_post.post_number); - } - - #[test] - fn tree_presentation_preserves_parent_numbers_depths_and_root_grouping() { - let body_post = make_topic_post(1, None); - let root_post = make_topic_post(2, Some(1)); - let child_post = make_topic_post(3, Some(2)); - let grandchild_post = make_topic_post(4, Some(3)); - let second_root = make_topic_post(5, Some(1)); - - let presentation = build_topic_tree_presentation_from_query(TopicTreePresentationQuery { - body_post: body_post.clone(), - raw_stream_ids: vec![ - body_post.id, - root_post.id, - child_post.id, - grandchild_post.id, - second_root.id, - ], - loaded_posts: vec![ - body_post.clone(), - root_post.clone(), - child_post.clone(), - grandchild_post.clone(), - second_root.clone(), - ], - focused_post_number: None, - last_read_post_number: Some(4), - }); - - assert_eq!( - presentation - .reply_rows - .iter() - .map(|row| row.post_id) - .collect::>(), - vec![ - root_post.id, - child_post.id, - grandchild_post.id, - second_root.id - ] - ); - assert_eq!(presentation.reply_rows[0].parent_post_number, Some(1)); - assert_eq!(presentation.reply_rows[0].depth, 1); - assert_eq!(presentation.reply_rows[1].parent_post_number, Some(2)); - assert_eq!(presentation.reply_rows[1].depth, 2); - assert_eq!(presentation.reply_rows[2].parent_post_number, Some(3)); - assert_eq!(presentation.reply_rows[2].depth, 3); - assert_eq!( - presentation - .reply_rows - .iter() - .map(|row| row.root_post_number) - .collect::>(), - vec![2, 2, 2, 5] - ); - assert_eq!(presentation.visible_root_post_numbers, vec![2, 5]); - assert_eq!(presentation.first_unread_root_post_number, Some(5)); - } - - #[test] - fn tree_presentation_reparents_missing_branch_to_body() { - let body_post = make_topic_post(1, None); - let orphan_root = make_topic_post(5, Some(99)); - let orphan_child = make_topic_post(6, Some(5)); - - let presentation = build_topic_tree_presentation_from_query(TopicTreePresentationQuery { - body_post: body_post.clone(), - raw_stream_ids: vec![body_post.id, orphan_root.id, orphan_child.id], - loaded_posts: vec![body_post.clone(), orphan_root.clone(), orphan_child.clone()], - focused_post_number: None, - last_read_post_number: Some(5), - }); - - assert_eq!( - presentation - .reply_rows - .iter() - .map(|row| row.post_id) - .collect::>(), - vec![orphan_root.id, orphan_child.id] - ); - assert_eq!(presentation.reply_rows[0].parent_post_number, Some(1)); - assert_eq!(presentation.reply_rows[1].parent_post_number, Some(1)); - assert_eq!(presentation.reply_rows[0].depth, 1); - assert_eq!(presentation.reply_rows[1].depth, 1); - assert_eq!( - presentation - .reply_rows - .iter() - .map(|row| row.root_post_number) - .collect::>(), - vec![5, 6] - ); - assert_eq!(presentation.visible_root_post_numbers, vec![5, 6]); - assert_eq!(presentation.first_unread_root_post_number, Some(6)); - } - - #[test] - fn tree_presentation_ignores_nested_unread_posts_for_root_target() { - let body_post = make_topic_post(1, None); - let root_post = make_topic_post(2, Some(1)); - let child_post = make_topic_post(9, Some(2)); - - let presentation = build_topic_tree_presentation_from_query(TopicTreePresentationQuery { - body_post: body_post.clone(), - raw_stream_ids: vec![body_post.id, root_post.id, child_post.id], - loaded_posts: vec![body_post.clone(), root_post.clone(), child_post.clone()], - focused_post_number: None, - last_read_post_number: Some(8), - }); - - assert_eq!(presentation.visible_root_post_numbers, vec![2]); - assert_eq!(presentation.first_unread_root_post_number, None); - } - - #[test] - fn ordered_unique_post_ids_drops_zeroes_and_duplicates() { - assert_eq!( - ordered_unique_post_ids(vec![0, 2, 2, 3, 0, 4, 3]), - vec![2, 3, 4] - ); - } - - #[test] - fn source_session_tracks_contiguous_loaded_ranges_and_unavailable_post_ids() { - let body_post = make_topic_post(1, None); - let second_post = make_topic_post(2, Some(1)); - let fourth_post = make_topic_post(4, Some(1)); - let mut session = TopicDetailSourceSession::new(TopicDetailSourceSessionInit { - session_epoch: 3, - header: TopicHeader { - topic_id: 42, - ..TopicHeader::default() - }, - body_post: body_post.clone(), - focused_post_number: None, - raw_stream_ids: vec![body_post.id, second_post.id, 3, fourth_post.id], - cached_posts: vec![body_post.clone(), second_post.clone(), fourth_post.clone()], - unavailable_post_ids: HashSet::new(), - load_more_policy: TopicLoadMorePolicy { - batch_size: 40, - max_auto_batches_per_gesture: 3, - max_auto_posts_per_gesture: 120, - require_new_root_progress: true, - }, - }); - - assert_eq!(session.next_stream_offset, 2); - assert_eq!(session.last_loaded_post_id, Some(2)); - assert_eq!( - session - .loaded_ranges - .iter() - .map(|range| (range.start_offset, range.end_offset_exclusive)) - .collect::>(), - vec![(0, 2), (3, 4)] - ); - assert!(!session.source_exhausted); - - session.mark_unavailable(HashSet::from([3])); - session.recompute_loaded_state(); - - assert_eq!(session.next_stream_offset, 4); - assert_eq!(session.last_loaded_post_id, Some(4)); - assert!(session.source_exhausted); - assert_eq!( - session - .loaded_ranges - .iter() - .map(|range| (range.start_offset, range.end_offset_exclusive)) - .collect::>(), - vec![(0, 4)] - ); - } - - #[test] - fn gained_visible_root_progress_detects_new_root_post_numbers() { - assert!(!gained_visible_root_progress(&[2, 5], &[2, 5])); - assert!(gained_visible_root_progress(&[2, 5], &[2, 5, 8])); - } -} diff --git a/rust/crates/fire-core/src/core/topics/list.rs b/rust/crates/fire-core/src/core/topics/list.rs new file mode 100644 index 00000000..f368c00a --- /dev/null +++ b/rust/crates/fire-core/src/core/topics/list.rs @@ -0,0 +1,235 @@ +use fire_models::{TopicListKind, TopicListQuery, TopicListResponse}; +use tracing::{info, warn}; + +use super::super::{network::expect_success, FireCore}; +use crate::{ + error::FireCoreError, + topic_payloads::RawTopicListResponse, +}; + +pub(crate) fn topic_list_cache_scope_key(query: &TopicListQuery) -> String { + let mut parts = vec![ + format!("kind={}", query.kind.filter_name()), + format!( + "category_slug={}", + query.category_slug.as_deref().unwrap_or("") + ), + format!( + "category_id={}", + query.category_id.map_or(String::new(), |id| id.to_string()) + ), + format!( + "parent_category_slug={}", + query.parent_category_slug.as_deref().unwrap_or("") + ), + format!("tag={}", normalized_cache_value(query.tag.as_deref())), + format!("order={}", query.order.as_deref().unwrap_or("")), + format!( + "ascending={}", + query + .ascending + .map_or(String::new(), |value| value.to_string()) + ), + format!("match_all_tags={}", query.match_all_tags), + ]; + + let mut topic_ids = query.topic_ids.clone(); + topic_ids.sort_unstable(); + parts.push(format!( + "topic_ids={}", + topic_ids + .iter() + .map(u64::to_string) + .collect::>() + .join(",") + )); + + parts.push(format!( + "additional_tags={}", + query + .additional_tags + .iter() + .map(|tag| normalized_cache_value(Some(tag))) + .collect::>() + .join(",") + )); + + parts.join("|") +} + +fn normalized_cache_value(value: Option<&str>) -> String { + value.unwrap_or("").trim().to_ascii_lowercase() +} + +impl FireCore { + pub async fn fetch_topic_list( + &self, + query: TopicListQuery, + ) -> Result { + info!( + kind = ?query.kind, + page = ?query.page, + category_slug = ?query.category_slug, + tag = ?query.tag, + topic_ids_count = query.topic_ids.len(), + "fetching topic list" + ); + + if matches!( + query.kind, + TopicListKind::Unread + | TopicListKind::Unseen + | TopicListKind::PrivateMessagesInbox + | TopicListKind::PrivateMessagesSent + ) && !self.snapshot().cookies.can_authenticate_requests() + { + warn!(kind = ?query.kind, "topic list fetch rejected: missing login session"); + return Err(FireCoreError::MissingLoginSession); + } + + let path = match query.kind { + TopicListKind::PrivateMessagesInbox | TopicListKind::PrivateMessagesSent => { + let snapshot = self.snapshot(); + let username = snapshot + .bootstrap + .current_username + .filter(|value| !value.trim().is_empty()) + .ok_or(FireCoreError::MissingLoginSession)?; + match query.kind { + TopicListKind::PrivateMessagesInbox => { + format!("/topics/private-messages/{username}.json") + } + TopicListKind::PrivateMessagesSent => { + format!("/topics/private-messages-sent/{username}.json") + } + _ => unreachable!(), + } + } + _ => query.api_path(), + }; + + let mut params = Vec::new(); + if let Some(page) = query.page { + if page > 0 { + params.push(("no_definitions", "true".to_string())); + params.push(("page", page.to_string())); + } + } + if !query.topic_ids.is_empty() { + params.push(( + "topic_ids", + query + .topic_ids + .iter() + .map(u64::to_string) + .collect::>() + .join(","), + )); + } + if let Some(order) = &query.order { + params.push(("order", order.clone())); + } + if let Some(ascending) = query.ascending { + params.push(("ascending", ascending.to_string())); + } + let primary_tag_as_query_param = query.category_slug.is_some().then(|| { + query + .tag + .as_ref() + .map(|tag| tag.trim()) + .filter(|tag| !tag.is_empty()) + .map(ToOwned::to_owned) + }); + for tag in primary_tag_as_query_param.into_iter().flatten() { + params.push(("tags[]", tag)); + } + for tag in &query.additional_tags { + params.push(("tags[]", tag.clone())); + } + if query.match_all_tags { + params.push(("match_all_tags", "true".to_string())); + } + + let cache_scope_key = topic_list_cache_scope_key(&query); + let cache_page = query.page.unwrap_or(0); + let traced = self.build_json_get_request("fetch topic list", &path, params, &[])?; + let (trace_id, response) = match self.execute_request(traced).await { + Ok(response) => response, + Err(error @ FireCoreError::Network { .. }) => { + if let Some(cached) = self.read_cached_topic_list(&cache_scope_key, cache_page)? { + warn!( + kind = ?query.kind, + page = ?query.page, + "topic list network fetch failed; returning cached page" + ); + return Ok(cached); + } + return Err(error); + } + Err(error) => return Err(error), + }; + let response = expect_success(self, "fetch topic list", trace_id, response).await?; + let raw: RawTopicListResponse = self + .read_response_json("fetch topic list", trace_id, response) + .await?; + let result: TopicListResponse = raw.into(); + self.write_cached_topic_list(&cache_scope_key, cache_page, &result); + info!( + kind = ?query.kind, + topic_count = result.topics.len(), + user_count = result.users.len(), + has_more = result.more_topics_url.is_some(), + "topic list fetched successfully" + ); + Ok(result) + } + + fn read_cached_topic_list( + &self, + scope_key: &str, + page: u32, + ) -> Result, FireCoreError> { + let auth_scope_hash = self.current_auth_scope_hash(); + let payload = { + let store = self + .shared_store + .lock() + .expect("shared store mutex poisoned"); + store.topic_list_cache_read(&auth_scope_hash, scope_key, page)? + }; + + let Some(payload) = payload else { + return Ok(None); + }; + + let mut cached: TopicListResponse = serde_json::from_str(&payload).map_err(|source| { + FireCoreError::ResponseDeserialize { + operation: "cached topic list", + source, + } + })?; + cached.is_cached = true; + Ok(Some(cached)) + } + + fn write_cached_topic_list(&self, scope_key: &str, page: u32, response: &TopicListResponse) { + let auth_scope_hash = self.current_auth_scope_hash(); + let mut cached = response.clone(); + cached.is_cached = false; + let payload = match serde_json::to_string(&cached) { + Ok(payload) => payload, + Err(error) => { + warn!(error = %error, "failed to serialize topic list cache payload"); + return; + } + }; + let result = self + .shared_store + .lock() + .expect("shared store mutex poisoned") + .topic_list_cache_write(&auth_scope_hash, scope_key, page, &payload); + if let Err(error) = result { + warn!(error = %error, "failed to write topic list cache"); + } + } +} diff --git a/rust/crates/fire-core/src/core/topics/mod.rs b/rust/crates/fire-core/src/core/topics/mod.rs new file mode 100644 index 00000000..41edd496 --- /dev/null +++ b/rust/crates/fire-core/src/core/topics/mod.rs @@ -0,0 +1,11 @@ +mod list; +mod posts; +mod source; +mod tree; + +pub(crate) use list::topic_list_cache_scope_key; +pub(crate) use source::{ + load_more_topic_detail_posts, load_topic_detail_page, + FireTopicDetailSourceRuntime, +}; +pub(crate) use tree::build_topic_tree_presentation_from_source_snapshot; diff --git a/rust/crates/fire-core/src/core/topics/posts.rs b/rust/crates/fire-core/src/core/topics/posts.rs new file mode 100644 index 00000000..fda10631 --- /dev/null +++ b/rust/crates/fire-core/src/core/topics/posts.rs @@ -0,0 +1,99 @@ +use std::collections::{HashMap, HashSet}; + +use fire_models::{TopicPost, TopicPostStream}; + +pub(super) fn missing_topic_post_ids(post_stream: &TopicPostStream) -> Vec { + if post_stream.stream.len() <= post_stream.posts.len() { + return Vec::new(); + } + + let loaded_post_ids: HashSet = post_stream.posts.iter().map(|post| post.id).collect(); + post_stream + .stream + .iter() + .copied() + .filter(|post_id| !loaded_post_ids.contains(post_id)) + .collect() +} + +pub(super) fn merge_topic_posts( + ordered_post_ids: &[u64], + existing_posts: Vec, + fetched_posts: Vec, +) -> Vec { + let mut posts_by_id: HashMap = HashMap::new(); + for post in existing_posts { + posts_by_id.insert(post.id, post); + } + for mut post in fetched_posts { + if let Some(existing) = posts_by_id.get(&post.id) { + post.reuse_presentation_from(existing); + } + posts_by_id.insert(post.id, post); + } + + let mut merged_posts = Vec::with_capacity(posts_by_id.len()); + for post_id in ordered_post_ids { + if let Some(post) = posts_by_id.remove(post_id) { + merged_posts.push(post); + } + } + + let mut trailing_posts: Vec = posts_by_id.into_values().collect(); + trailing_posts.sort_by_key(|post| (post.post_number, post.id)); + merged_posts.extend(trailing_posts); + merged_posts +} + +pub(super) fn topic_posts_for_requested_ids( + requested_post_ids: &[u64], + cached_posts: Vec, + fetched_posts: Vec, +) -> Vec { + let mut posts_by_id: HashMap = cached_posts + .into_iter() + .chain(fetched_posts) + .map(|post| (post.id, post)) + .collect(); + + let mut ordered_posts = Vec::with_capacity(posts_by_id.len()); + for post_id in requested_post_ids { + if let Some(post) = posts_by_id.remove(post_id) { + ordered_posts.push(post); + } + } + + let mut trailing_posts: Vec = posts_by_id.into_values().collect(); + trailing_posts.sort_by_key(|post| (post.post_number, post.id)); + ordered_posts.extend(trailing_posts); + ordered_posts +} +pub(super) fn missing_post_ids_from_ids(ordered_post_ids: &[u64], loaded_posts: &[TopicPost]) -> Vec { + let loaded_post_ids: HashSet = loaded_posts.iter().map(|post| post.id).collect(); + ordered_post_ids + .iter() + .copied() + .filter(|post_id| !loaded_post_ids.contains(post_id)) + .collect() +} + +pub(super) fn ordered_unique_post_ids(ids: Vec) -> Vec { + let mut seen = HashSet::new(); + let mut result = Vec::with_capacity(ids.len()); + for post_id in ids { + if post_id > 0 && seen.insert(post_id) { + result.push(post_id); + } + } + result +} +pub(super) fn deduplicate_topic_posts_by_id(posts: Vec) -> Vec { + let mut seen_post_ids = HashSet::new(); + let mut deduplicated = Vec::with_capacity(posts.len()); + for post in posts { + if seen_post_ids.insert(post.id) { + deduplicated.push(post); + } + } + deduplicated +} diff --git a/rust/crates/fire-core/src/core/topics/source/hydrate.rs b/rust/crates/fire-core/src/core/topics/source/hydrate.rs new file mode 100644 index 00000000..6850f199 --- /dev/null +++ b/rust/crates/fire-core/src/core/topics/source/hydrate.rs @@ -0,0 +1,495 @@ +use std::collections::{HashMap, HashSet}; +use std::time::Instant; + +use fire_models::{ + LoadMoreTopicPostsQuery, TopicAiSummary, TopicBody, TopicDetail, TopicDetailPage, + TopicDetailQuery, TopicDetailSourceAppend, TopicDetailSourceQuery, TopicDetailSourceSnapshot, + TopicHeader, TopicLoadMoreOutcome, TopicLoadMoreStopReason, TopicLoadedRange, TopicPost, + TopicSourceCursor, TopicThread, TopicTreePresentation, +}; +use http::StatusCode; +use serde_json::Value; +use tracing::{info, warn}; + +use super::super::super::{network::expect_success, FireCore}; +use super::super::posts::{ + merge_topic_posts, missing_post_ids_from_ids, missing_topic_post_ids, + ordered_unique_post_ids, topic_posts_for_requested_ids, +}; +use super::super::tree::{ + build_topic_tree_presentation_from_source_snapshot, topic_detail_source_cooked_byte_count, + topic_tree_needs_unread_root_extension, +}; +use super::*; +use crate::{ + error::FireCoreError, + json_helpers::invalid_json, + topic_payloads::{parse_topic_ai_summary_value, parse_topic_post_stream_value, RawTopicDetail}, +}; +impl FireCore { + pub async fn fetch_topic_posts( + &self, + topic_id: u64, + post_ids: Vec, + ) -> Result, FireCoreError> { + let requested_post_ids = ordered_unique_post_ids(post_ids); + if requested_post_ids.is_empty() { + return Ok(Vec::new()); + } + + let cached_posts = + self.cached_topic_posts_for_active_source_session(topic_id, &requested_post_ids); + let cached_post_ids = cached_posts + .iter() + .map(|post| post.id) + .collect::>(); + let missing_post_ids = requested_post_ids + .iter() + .copied() + .filter(|post_id| !cached_post_ids.contains(post_id)) + .collect::>(); + if missing_post_ids.is_empty() { + return Ok(topic_posts_for_requested_ids( + &requested_post_ids, + cached_posts, + Vec::new(), + )); + } + + let path = format!("/t/{topic_id}/posts.json"); + let params = missing_post_ids + .iter() + .copied() + .map(|post_id| ("post_ids[]", post_id.to_string())) + .chain(std::iter::once(("include_suggested", "false".to_string()))) + .collect::>(); + let traced = self.build_json_get_request("fetch topic posts", &path, params, &[])?; + let (trace_id, response) = self.execute_request(traced).await?; + let response = expect_success(self, "fetch topic posts", trace_id, response).await?; + let value: Value = self + .read_response_json("fetch topic posts", trace_id, response) + .await?; + let post_stream = + parse_topic_post_stream_value(value, self.base_url()).map_err(|source| { + FireCoreError::ResponseDeserialize { + operation: "fetch topic posts", + source, + } + })?; + let fetched_posts = post_stream.posts; + self.cache_topic_posts_for_active_source_session(topic_id, &fetched_posts); + if cached_posts.is_empty() { + return Ok(fetched_posts); + } + Ok(topic_posts_for_requested_ids( + &requested_post_ids, + cached_posts, + fetched_posts, + )) + } + + pub(super) fn cached_topic_posts_for_active_source_session( + &self, + topic_id: u64, + post_ids: &[u64], + ) -> Vec { + let current_epoch = self.current_session_epoch(); + let runtime = self + .topic_detail_source + .lock() + .expect("topic detail source runtime lock poisoned"); + let Some(session) = runtime.sessions_by_topic_id.get(&topic_id) else { + return Vec::new(); + }; + if session.session_epoch != current_epoch { + return Vec::new(); + } + session.posts_for_ids(post_ids) + } + + pub(super) fn cache_topic_posts_for_active_source_session(&self, topic_id: u64, posts: &[TopicPost]) { + if posts.is_empty() { + return; + } + let current_epoch = self.current_session_epoch(); + let mut runtime = self + .topic_detail_source + .lock() + .expect("topic detail source runtime lock poisoned"); + let Some(session) = runtime.sessions_by_topic_id.get_mut(&topic_id) else { + return; + }; + if session.session_epoch != current_epoch { + return; + } + session.merge_posts(posts.iter().cloned()); + } + + pub(crate) fn topic_source_contains_target( + &self, + topic_id: u64, + target_post_number: Option, + ) -> bool { + let current_epoch = self.current_session_epoch(); + let runtime = self + .topic_detail_source + .lock() + .expect("topic detail source runtime lock poisoned"); + let Some(session) = runtime.sessions_by_topic_id.get(&topic_id) else { + return false; + }; + if session.session_epoch != current_epoch { + return false; + } + match target_post_number { + Some(post_number) => session.contains_post_number(post_number), + None => true, + } + } + + pub(crate) fn clone_topic_source_snapshot( + &self, + topic_id: u64, + ) -> Option { + let current_epoch = self.current_session_epoch(); + let runtime = self + .topic_detail_source + .lock() + .expect("topic detail source runtime lock poisoned"); + let session = runtime.sessions_by_topic_id.get(&topic_id)?; + (session.session_epoch == current_epoch).then(|| session.source_snapshot()) + } + + pub(crate) fn with_topic_source_session_mut( + &self, + topic_id: u64, + session_id: Option, + mutate: impl FnOnce(&mut TopicDetailSourceSession) -> R, + ) -> Option { + let current_epoch = self.current_session_epoch(); + let mut runtime = self + .topic_detail_source + .lock() + .expect("topic detail source runtime lock poisoned"); + let session = runtime.sessions_by_topic_id.get_mut(&topic_id)?; + if session.session_epoch != current_epoch { + return None; + } + if let Some(session_id) = session_id { + if session.session_id != session_id { + return None; + } + } + Some(mutate(session)) + } + + #[cfg(test)] + pub(crate) fn seed_topic_detail_source_for_test( + &self, + header: TopicHeader, + body_post: TopicPost, + posts: Vec, + raw_stream_ids: Vec, + ) -> u64 { + let session = TopicDetailSourceSession::new(TopicDetailSourceSessionInit { + session_epoch: self.current_session_epoch(), + header, + body_post, + focused_post_number: None, + raw_stream_ids, + cached_posts: posts, + unavailable_post_ids: HashSet::new(), + load_more_policy: TopicLoadMorePolicy { + batch_size: DEFAULT_TOPIC_LOAD_MORE_BATCH_SIZE, + max_auto_batches_per_gesture: DEFAULT_TOPIC_MAX_AUTO_BATCHES_PER_GESTURE, + max_auto_posts_per_gesture: DEFAULT_TOPIC_MAX_AUTO_POSTS_PER_GESTURE, + require_new_root_progress: true, + }, + }); + let mut runtime = self + .topic_detail_source + .lock() + .expect("topic detail source runtime lock poisoned"); + let next_session_id = runtime.next_session_id.saturating_add(1).max(1); + runtime.next_session_id = next_session_id; + let topic_id = session.header.topic_id; + runtime + .sessions_by_topic_id + .insert(topic_id, session.with_session_id(next_session_id)); + next_session_id + } + + /// Resolve the topic body/OP used as tree root. + /// + /// Prefer payloads already in the detail chunk, then stream-head via + /// `post_ids[]`, then number-based / root-detail fallbacks. + pub(super) async fn resolve_topic_body_post( + &self, + topic_id: u64, + detail: &TopicDetail, + ) -> Result { + if let Some(post) = detail + .post_stream + .posts + .iter() + .find(|post| post.post_number == 1) + .cloned() + { + return Ok(post); + } + + if let Some(first_id) = detail + .post_stream + .stream + .first() + .copied() + .filter(|post_id| *post_id > 0) + { + let posts = self.fetch_topic_posts(topic_id, vec![first_id]).await?; + if let Some(post) = posts.into_iter().find(|post| post.id == first_id) { + return Ok(post); + } + } + + if let Ok(post) = self + .resolve_topic_post_by_number(topic_id, 1, &detail.post_stream.stream) + .await + { + return Ok(post); + } + + // Last resort: unanchored topic detail always starts near the beginning. + let root = self + .fetch_topic_detail_base( + TopicDetailQuery { + topic_id, + post_number: None, + track_visit: false, + force_load: true, + filter: None, + username_filters: None, + filter_top_level_replies: false, + }, + false, + ) + .await?; + if let Some(post) = root + .post_stream + .posts + .iter() + .find(|post| post.post_number == 1) + .cloned() + { + return Ok(post); + } + root.post_stream + .posts + .into_iter() + .min_by_key(|post| post.post_number) + .ok_or_else(|| FireCoreError::ResponseDeserialize { + operation: "resolve topic body post", + source: invalid_json( + "topic detail did not include a body/original post payload".to_string(), + ), + }) + } + + pub(super) async fn resolve_topic_post_by_number( + &self, + topic_id: u64, + post_number: u32, + stream_ids: &[u64], + ) -> Result { + // 1) Number-window posts.json (fast path when Discourse returns the floor). + if let Ok(post) = self.fetch_post_by_number(topic_id, post_number).await { + return Ok(post); + } + + // 2) Anchored topic detail around the floor — more reliable than posts.json + // for some large/complex topics where the number window omits the exact post. + let anchored = self + .fetch_topic_detail_base( + TopicDetailQuery { + topic_id, + post_number: Some(post_number), + track_visit: false, + force_load: true, + filter: None, + username_filters: None, + filter_top_level_replies: false, + }, + false, + ) + .await?; + if let Some(post) = anchored + .post_stream + .posts + .into_iter() + .find(|post| post.post_number == post_number) + { + return Ok(post); + } + + // 3) If stream is known and dense enough that index ~= post_number-1, try id. + // This is best-effort only (deleted posts create gaps). + if post_number > 0 { + let index = usize::try_from(post_number.saturating_sub(1)).unwrap_or(usize::MAX); + if let Some(post_id) = stream_ids.get(index).copied().filter(|id| *id > 0) { + let posts = self.fetch_topic_posts(topic_id, vec![post_id]).await?; + if let Some(post) = posts + .into_iter() + .find(|post| post.id == post_id || post.post_number == post_number) + { + return Ok(post); + } + } + } + + Err(FireCoreError::ResponseDeserialize { + operation: "resolve topic post by number", + source: invalid_json(format!( + "topic post stream did not contain post number {post_number}" + )), + }) + } + + pub(super) async fn fetch_post_by_number( + &self, + topic_id: u64, + post_number: u32, + ) -> Result { + let path = format!("/t/{topic_id}/posts.json"); + let params = vec![ + ("post_number", post_number.to_string()), + ("asc", "true".to_string()), + ("include_suggested", "false".to_string()), + ]; + let traced = self.build_json_get_request("fetch post by number", &path, params, &[])?; + let (trace_id, response) = self.execute_request(traced).await?; + let response = expect_success(self, "fetch post by number", trace_id, response).await?; + let value: Value = self + .read_response_json("fetch post by number", trace_id, response) + .await?; + let post_stream = + parse_topic_post_stream_value(value, self.base_url()).map_err(|source| { + FireCoreError::ResponseDeserialize { + operation: "fetch post by number", + source, + } + })?; + post_stream + .posts + .into_iter() + .find(|post| post.post_number == post_number) + .ok_or_else(|| FireCoreError::ResponseDeserialize { + operation: "fetch post by number", + source: invalid_json(format!( + "topic post stream did not contain post number {post_number}" + )), + }) + } + + pub async fn fetch_topic_ai_summary( + &self, + topic_id: u64, + skip_age_check: bool, + ) -> Result, FireCoreError> { + info!(topic_id, skip_age_check, "fetching topic AI summary"); + + let path = format!("/discourse-ai/summarization/t/{topic_id}"); + let mut params = Vec::new(); + if skip_age_check { + params.push(("skip_age_check", "true".to_string())); + } + + let traced = + self.build_json_get_request(FETCH_TOPIC_AI_SUMMARY_OPERATION, &path, params, &[])?; + let (trace_id, response) = self.execute_request(traced).await?; + let response = match expect_success( + self, + FETCH_TOPIC_AI_SUMMARY_OPERATION, + trace_id, + response, + ) + .await + { + Ok(response) => response, + Err(FireCoreError::HttpStatus { + status, + body: _, + operation: FETCH_TOPIC_AI_SUMMARY_OPERATION, + }) if status == StatusCode::NOT_FOUND.as_u16() + || status == StatusCode::FORBIDDEN.as_u16() => + { + info!(topic_id, status, "topic AI summary is unavailable"); + return Ok(None); + } + Err(error) => return Err(error), + }; + let value: Value = self + .read_response_json(FETCH_TOPIC_AI_SUMMARY_OPERATION, trace_id, response) + .await?; + let summary = parse_topic_ai_summary_value(value).map_err(|source| { + FireCoreError::ResponseDeserialize { + operation: FETCH_TOPIC_AI_SUMMARY_OPERATION, + source, + } + })?; + info!( + topic_id, + has_summary = summary.is_some(), + "topic AI summary fetched successfully" + ); + Ok(summary) + } + + pub(super) async fn hydrate_topic_detail_posts( + &self, + topic_id: u64, + detail: &mut TopicDetail, + ) -> Result<(), FireCoreError> { + let missing_post_ids = missing_topic_post_ids(&detail.post_stream); + if missing_post_ids.is_empty() { + return Ok(()); + } + + info!( + topic_id, + loaded_posts = detail.post_stream.posts.len(), + total_posts = detail.post_stream.stream.len(), + missing_posts = missing_post_ids.len(), + "hydrating missing topic posts" + ); + + let mut fetched_posts = Vec::with_capacity(missing_post_ids.len()); + for post_ids in missing_post_ids.chunks(TOPIC_POST_BATCH_SIZE) { + fetched_posts.extend(self.fetch_topic_posts(topic_id, post_ids.to_vec()).await?); + } + + if fetched_posts.is_empty() { + return Ok(()); + } + + detail.post_stream.posts = merge_topic_posts( + &detail.post_stream.stream, + std::mem::take(&mut detail.post_stream.posts), + fetched_posts, + ); + detail.thread = TopicThread::from_posts(&detail.post_stream.posts); + detail.flat_posts = detail.thread.flatten(&detail.post_stream.posts); + detail.rebuild_timeline_entries(); + + let remaining_missing = missing_topic_post_ids(&detail.post_stream); + if !remaining_missing.is_empty() { + warn!( + topic_id, + missing_posts = remaining_missing.len(), + loaded_posts = detail.post_stream.posts.len(), + total_posts = detail.post_stream.stream.len(), + "topic detail hydration completed with unresolved missing posts" + ); + } + + Ok(()) + } +} diff --git a/rust/crates/fire-core/src/core/topics/source/load.rs b/rust/crates/fire-core/src/core/topics/source/load.rs new file mode 100644 index 00000000..187220b3 --- /dev/null +++ b/rust/crates/fire-core/src/core/topics/source/load.rs @@ -0,0 +1,671 @@ +use std::collections::{HashMap, HashSet}; +use std::time::Instant; + +use fire_models::{ + LoadMoreTopicPostsQuery, TopicAiSummary, TopicBody, TopicDetail, TopicDetailPage, + TopicDetailQuery, TopicDetailSourceAppend, TopicDetailSourceQuery, TopicDetailSourceSnapshot, + TopicHeader, TopicLoadMoreOutcome, TopicLoadMoreStopReason, TopicLoadedRange, TopicPost, + TopicSourceCursor, TopicThread, TopicTreePresentation, +}; +use http::StatusCode; +use serde_json::Value; +use tracing::{info, warn}; + +use super::super::super::{network::expect_success, FireCore}; +use super::super::posts::{ + merge_topic_posts, missing_post_ids_from_ids, missing_topic_post_ids, + ordered_unique_post_ids, topic_posts_for_requested_ids, +}; +use super::super::tree::{ + build_topic_tree_presentation_from_source_snapshot, topic_detail_source_cooked_byte_count, + topic_tree_needs_unread_root_extension, +}; +use super::*; +use crate::{ + error::FireCoreError, + json_helpers::invalid_json, + topic_payloads::{parse_topic_ai_summary_value, parse_topic_post_stream_value, RawTopicDetail}, +}; +pub(crate) async fn load_topic_detail_source_snapshot( + core: &FireCore, + query: TopicDetailSourceQuery, +) -> Result { + core.load_topic_detail_source_snapshot_impl(query).await +} + +pub(crate) async fn load_topic_detail_page( + core: &FireCore, + query: TopicDetailSourceQuery, +) -> Result { + core.load_topic_detail_page_impl(query).await +} + +pub(crate) async fn load_more_topic_detail_posts( + core: &FireCore, + query: LoadMoreTopicPostsQuery, +) -> Result { + core.load_more_topic_posts_impl(query).await +} + +impl FireCore { + pub async fn fetch_topic_detail_initial( + &self, + query: TopicDetailQuery, + ) -> Result { + let mut result = self.fetch_topic_detail_base(query, true).await?; + result.rebuild_timeline_entries(); + info!( + topic_id = result.id, + posts_count = result.posts_count, + post_stream_total = result.post_stream.stream.len(), + post_stream_len = result.post_stream.posts.len(), + timeline_entries = result.timeline_entries.len(), + "topic detail initial payload fetched successfully" + ); + Ok(result) + } + + pub async fn fetch_topic_detail( + &self, + query: TopicDetailQuery, + ) -> Result { + let mut result = self.fetch_topic_detail_base(query, true).await?; + if let Err(error) = self + .hydrate_topic_detail_posts(result.id, &mut result) + .await + { + warn!( + topic_id = result.id, + error = %error, + "topic detail hydration fell back to partially loaded posts" + ); + // Hydration builds timeline entries on success; build from partial data on failure. + result.rebuild_timeline_entries(); + } + info!( + topic_id = result.id, + posts_count = result.posts_count, + post_stream_total = result.post_stream.stream.len(), + post_stream_len = result.post_stream.posts.len(), + timeline_entries = result.timeline_entries.len(), + "topic detail fetched successfully" + ); + Ok(result) + } + + pub async fn fetch_topic_detail_source_snapshot( + &self, + query: TopicDetailSourceQuery, + ) -> Result { + load_topic_detail_source_snapshot(self, query).await + } + + pub(crate) async fn load_topic_detail_source_snapshot_impl( + &self, + query: TopicDetailSourceQuery, + ) -> Result { + let focused_post_number = query + .target_post_number + .filter(|post_number| *post_number > 1); + let initial_batch_size = normalized_topic_initial_batch_size(query.initial_batch_size); + let load_more_policy = TopicLoadMorePolicy { + batch_size: normalized_topic_load_more_batch_size(query.load_more_batch_size), + max_auto_batches_per_gesture: normalized_topic_auto_batch_limit( + query.max_auto_batches_per_gesture, + ), + max_auto_posts_per_gesture: normalized_topic_auto_post_limit( + query.max_auto_posts_per_gesture, + ), + require_new_root_progress: true, + }; + + let mut detail = self + .fetch_topic_detail_base( + TopicDetailQuery { + topic_id: query.topic_id, + post_number: focused_post_number, + track_visit: query.track_visit, + force_load: query.force_load, + filter: None, + username_filters: None, + filter_top_level_replies: false, + }, + false, + ) + .await?; + + // Mid-topic opens (`/t/{id}/{N}.json` from notifications) only embed a + // nearby posts chunk. OP/body is often absent from that chunk on large + // topics. Resolve body via stream head + post_ids[] first — never hard + // fail solely on posts.json?post_number=1 missing the OP payload. + let body_post = self + .resolve_topic_body_post(query.topic_id, &detail) + .await?; + if detail.post_stream.stream.is_empty() && body_post.id > 0 { + detail.post_stream.stream.push(body_post.id); + } + + if let Some(target_post_number) = focused_post_number.filter(|post_number| { + !detail + .post_stream + .posts + .iter() + .any(|post| post.post_number == *post_number) + }) { + detail.post_stream.posts.push( + self.resolve_topic_post_by_number( + query.topic_id, + target_post_number, + &detail.post_stream.stream, + ) + .await?, + ); + } + if !detail + .post_stream + .posts + .iter() + .any(|post| post.id == body_post.id) + { + detail.post_stream.posts.push(body_post.clone()); + } + + let initial_source_post_ids = detail + .post_stream + .stream + .iter() + .copied() + .take(usize::from(initial_batch_size)) + .collect::>(); + let missing_initial_post_ids = + missing_post_ids_from_ids(&initial_source_post_ids, &detail.post_stream.posts); + let fetched_initial_posts = if missing_initial_post_ids.is_empty() { + Vec::new() + } else { + self.fetch_topic_posts(query.topic_id, missing_initial_post_ids.clone()) + .await? + }; + let fetched_initial_post_ids = fetched_initial_posts + .iter() + .map(|post| post.id) + .collect::>(); + let initial_unavailable_post_ids = missing_initial_post_ids + .into_iter() + .filter(|post_id| !fetched_initial_post_ids.contains(post_id)) + .collect::>(); + detail.post_stream.posts = merge_topic_posts( + &detail.post_stream.stream, + std::mem::take(&mut detail.post_stream.posts), + fetched_initial_posts, + ); + + let header = detail.header(); + let session = TopicDetailSourceSession::new(TopicDetailSourceSessionInit { + session_epoch: self.current_session_epoch(), + header, + body_post, + focused_post_number, + raw_stream_ids: detail.post_stream.stream, + cached_posts: detail.post_stream.posts, + unavailable_post_ids: initial_unavailable_post_ids, + load_more_policy, + }); + + let snapshot = { + let mut runtime = self + .topic_detail_source + .lock() + .expect("topic detail source runtime lock poisoned"); + let next_session_id = runtime.next_session_id.saturating_add(1).max(1); + runtime.next_session_id = next_session_id; + let session = session.with_session_id(next_session_id); + let snapshot = session.source_snapshot(); + runtime.sessions_by_topic_id.insert(query.topic_id, session); + snapshot + }; + + Ok(snapshot) + } + + pub async fn fetch_topic_detail_page( + &self, + query: TopicDetailSourceQuery, + ) -> Result { + load_topic_detail_page(self, query).await + } + + pub(crate) async fn load_topic_detail_page_impl( + &self, + query: TopicDetailSourceQuery, + ) -> Result { + let topic_id = query.topic_id; + let should_seek_unread_root = + query.allow_suggested_unread_root && query.target_post_number.is_none(); + let source_started_at = Instant::now(); + let mut source_snapshot = load_topic_detail_source_snapshot(self, query).await?; + let source_fetch_ms = source_started_at.elapsed().as_millis(); + let tree_started_at = Instant::now(); + let mut tree_presentation = + build_topic_tree_presentation_from_source_snapshot(&source_snapshot); + let tree_presentation_ms = tree_started_at.elapsed().as_millis(); + let auto_seek_started_at = Instant::now(); + let auto_seek = if should_seek_unread_root { + self.extend_topic_source_to_unread_root_if_needed( + &mut source_snapshot, + &mut tree_presentation, + ) + .await? + } else { + TopicUnreadRootAutoSeekStats::default() + }; + let auto_seek_ms = auto_seek_started_at.elapsed().as_millis(); + info!( + topic_id, + source_fetch_ms, + tree_presentation_ms, + auto_unread_root_ms = auto_seek_ms, + auto_unread_root_batches = auto_seek.chained_batches, + auto_unread_root_posts = auto_seek.chained_posts, + source_loaded_posts = source_snapshot.loaded_posts.len(), + body_post_included = true, + cooked_byte_count = topic_detail_source_cooked_byte_count(&source_snapshot), + reply_rows = tree_presentation.reply_rows.len(), + visible_root_count = tree_presentation.visible_root_post_numbers.len(), + first_unread_root_post_number = ?tree_presentation.first_unread_root_post_number, + total_loaded_post_count = tree_presentation.total_loaded_post_count, + "topic detail page built" + ); + Ok(TopicDetailPage { + source_snapshot, + tree_presentation, + }) + } + + pub(super) async fn extend_topic_source_to_unread_root_if_needed( + &self, + source_snapshot: &mut TopicDetailSourceSnapshot, + tree_presentation: &mut TopicTreePresentation, + ) -> Result { + let mut stats = TopicUnreadRootAutoSeekStats::default(); + if !topic_tree_needs_unread_root_extension(source_snapshot, tree_presentation) { + return Ok(stats); + } + + let Some(initial_cursor) = source_snapshot.source_cursor.clone() else { + return Ok(stats); + }; + let policy = self + .clone_active_source_session( + initial_cursor.topic_id, + initial_cursor.session_id, + None, + None, + )? + .load_more_policy; + let mut current_cursor = initial_cursor; + + while topic_tree_needs_unread_root_extension(source_snapshot, tree_presentation) { + let append_result = self.append_topic_source_batch(current_cursor.clone()).await; + let append = match append_result { + Ok(append) => append, + Err(error) => { + warn!( + topic_id = current_cursor.topic_id, + session_id = current_cursor.session_id, + batches = stats.chained_batches, + posts = stats.chained_posts, + error = %error, + "topic unread root auto seek stopped after source append failure" + ); + return Ok(stats); + } + }; + + stats.chained_batches = stats.chained_batches.saturating_add(1); + stats.chained_posts = stats + .chained_posts + .saturating_add(u16::try_from(append.appended_posts.len()).unwrap_or(u16::MAX)); + let session = self.clone_active_source_session( + current_cursor.topic_id, + current_cursor.session_id, + None, + None, + )?; + *source_snapshot = session.source_snapshot(); + *tree_presentation = + build_topic_tree_presentation_from_source_snapshot(source_snapshot); + + if !topic_tree_needs_unread_root_extension(source_snapshot, tree_presentation) + || source_snapshot.source_exhausted + || stats.chained_batches >= policy.max_auto_batches_per_gesture + || stats.chained_posts >= policy.max_auto_posts_per_gesture + { + return Ok(stats); + } + + let Some(next_cursor) = source_snapshot.source_cursor.clone() else { + return Ok(stats); + }; + current_cursor = next_cursor; + } + + Ok(stats) + } + + pub async fn append_topic_detail_source( + &self, + query: LoadMoreTopicPostsQuery, + ) -> Result { + self.append_topic_source_batch(query.cursor).await + } + + pub async fn load_more_topic_posts( + &self, + query: LoadMoreTopicPostsQuery, + ) -> Result { + load_more_topic_detail_posts(self, query).await + } + + pub(crate) async fn load_more_topic_posts_impl( + &self, + query: LoadMoreTopicPostsQuery, + ) -> Result { + let initial_session = self.clone_active_source_session( + query.cursor.topic_id, + query.cursor.session_id, + None, + None, + )?; + let initial_snapshot = initial_session.source_snapshot(); + let baseline_tree = build_topic_tree_presentation_from_source_snapshot(&initial_snapshot); + let baseline_visible_roots = baseline_tree.visible_root_post_numbers.clone(); + let policy = initial_session.load_more_policy; + + let mut current_cursor = query.cursor; + let mut latest_snapshot = initial_snapshot; + let mut latest_tree = baseline_tree; + let mut appended_posts = Vec::new(); + let mut chained_batches: u8 = 0; + let mut chained_posts: u16 = 0; + + loop { + let append_result = self.append_topic_source_batch(current_cursor.clone()).await; + let append = match append_result { + Ok(append) => append, + Err(error) if chained_batches == 0 => return Err(error), + Err(error) => { + warn!( + topic_id = current_cursor.topic_id, + session_id = current_cursor.session_id, + batches = chained_batches, + posts = chained_posts, + error = %error, + "{TOPIC_LOAD_MORE_FAILURE_MESSAGE}" + ); + latest_tree.gained_new_root_progress = gained_visible_root_progress( + &baseline_visible_roots, + &latest_tree.visible_root_post_numbers, + ); + return Ok(topic_load_more_outcome( + latest_snapshot, + appended_posts, + latest_tree, + chained_batches, + chained_posts, + TopicLoadMoreStopReason::RequestFailed, + )); + } + }; + + chained_batches = chained_batches.saturating_add(1); + chained_posts = chained_posts + .saturating_add(u16::try_from(append.appended_posts.len()).unwrap_or(u16::MAX)); + appended_posts.extend(append.appended_posts); + let session = self.clone_active_source_session( + current_cursor.topic_id, + current_cursor.session_id, + None, + None, + )?; + latest_snapshot = session.source_snapshot(); + latest_tree = build_topic_tree_presentation_from_source_snapshot(&latest_snapshot); + latest_tree.gained_new_root_progress = gained_visible_root_progress( + &baseline_visible_roots, + &latest_tree.visible_root_post_numbers, + ); + + if policy.require_new_root_progress && latest_tree.gained_new_root_progress { + return Ok(topic_load_more_outcome( + latest_snapshot, + appended_posts, + latest_tree, + chained_batches, + chained_posts, + TopicLoadMoreStopReason::GainedVisibleRootProgress, + )); + } + if latest_snapshot.source_exhausted { + return Ok(topic_load_more_outcome( + latest_snapshot, + appended_posts, + latest_tree, + chained_batches, + chained_posts, + TopicLoadMoreStopReason::SourceExhausted, + )); + } + if chained_batches >= policy.max_auto_batches_per_gesture { + return Ok(topic_load_more_outcome( + latest_snapshot, + appended_posts, + latest_tree, + chained_batches, + chained_posts, + TopicLoadMoreStopReason::MaxAutoBatchesReached, + )); + } + if chained_posts >= policy.max_auto_posts_per_gesture { + return Ok(topic_load_more_outcome( + latest_snapshot, + appended_posts, + latest_tree, + chained_batches, + chained_posts, + TopicLoadMoreStopReason::MaxAutoPostsReached, + )); + } + + let Some(next_cursor) = latest_snapshot.source_cursor.clone() else { + return Ok(topic_load_more_outcome( + latest_snapshot, + appended_posts, + latest_tree, + chained_batches, + chained_posts, + TopicLoadMoreStopReason::SourceExhausted, + )); + }; + current_cursor = next_cursor; + } + } + + pub(super) fn clone_active_source_session( + &self, + topic_id: u64, + session_id: u64, + expected_next_stream_offset: Option, + expected_last_loaded_post_id: Option, + ) -> Result { + let current_epoch = self.current_session_epoch(); + let runtime = self + .topic_detail_source + .lock() + .expect("topic detail source runtime lock poisoned"); + let Some(session) = runtime.sessions_by_topic_id.get(&topic_id) else { + return Err(FireCoreError::InvalidTopicSourceCursor { + topic_id, + session_id, + }); + }; + if session.session_id != session_id || session.session_epoch != current_epoch { + return Err(FireCoreError::InvalidTopicSourceCursor { + topic_id, + session_id, + }); + } + if let Some(expected_next_stream_offset) = expected_next_stream_offset { + if session.next_stream_offset != expected_next_stream_offset as usize + || session.last_loaded_post_id != expected_last_loaded_post_id + { + return Err(FireCoreError::InvalidTopicSourceCursor { + topic_id, + session_id, + }); + } + } + Ok(session.clone()) + } + + pub(super) async fn append_topic_source_batch( + &self, + cursor: TopicSourceCursor, + ) -> Result { + let batch_size = normalized_topic_load_more_batch_size(cursor.batch_size); + let session = self.clone_active_source_session( + cursor.topic_id, + cursor.session_id, + Some(cursor.next_stream_offset), + cursor.last_loaded_post_id, + )?; + if session.source_exhausted { + return Ok(TopicDetailSourceAppend { + appended_posts: Vec::new(), + loaded_ranges: session.loaded_ranges, + source_cursor: None, + source_exhausted: true, + }); + } + + let batch_start_offset = session.next_stream_offset; + let batch_end_offset = session + .next_stream_offset + .saturating_add(usize::from(batch_size)) + .min(session.raw_stream_ids.len()); + let batch_post_ids = session.raw_stream_ids[batch_start_offset..batch_end_offset].to_vec(); + let previously_loaded_post_ids = batch_post_ids + .iter() + .copied() + .filter(|post_id| session.posts_by_id.contains_key(post_id)) + .collect::>(); + let missing_post_ids = batch_post_ids + .iter() + .copied() + .filter(|post_id| !previously_loaded_post_ids.contains(post_id)) + .collect::>(); + let mut fetched_posts = Vec::new(); + for post_ids in missing_post_ids.chunks(TOPIC_POST_BATCH_SIZE) { + fetched_posts.extend( + self.fetch_topic_posts(cursor.topic_id, post_ids.to_vec()) + .await?, + ); + } + let fetched_post_ids = fetched_posts + .iter() + .map(|post| post.id) + .collect::>(); + let unavailable_post_ids = missing_post_ids + .into_iter() + .filter(|post_id| !fetched_post_ids.contains(post_id)) + .collect::>(); + + let mut runtime = self + .topic_detail_source + .lock() + .expect("topic detail source runtime lock poisoned"); + let Some(session) = runtime.sessions_by_topic_id.get_mut(&cursor.topic_id) else { + return Err(FireCoreError::InvalidTopicSourceCursor { + topic_id: cursor.topic_id, + session_id: cursor.session_id, + }); + }; + if session.session_id != cursor.session_id + || session.session_epoch != self.current_session_epoch() + || session.next_stream_offset != cursor.next_stream_offset as usize + || session.last_loaded_post_id != cursor.last_loaded_post_id + { + return Err(FireCoreError::InvalidTopicSourceCursor { + topic_id: cursor.topic_id, + session_id: cursor.session_id, + }); + } + + session.merge_posts(fetched_posts); + session.mark_unavailable(unavailable_post_ids); + session.recompute_loaded_state(); + let appended_posts = batch_post_ids + .iter() + .filter(|post_id| !previously_loaded_post_ids.contains(post_id)) + .filter_map(|post_id| session.posts_by_id.get(post_id).cloned()) + .collect::>(); + Ok(TopicDetailSourceAppend { + appended_posts, + loaded_ranges: session.loaded_ranges.clone(), + source_cursor: session.source_cursor(), + source_exhausted: session.source_exhausted, + }) + } + + pub(super) async fn fetch_topic_detail_base( + &self, + query: TopicDetailQuery, + include_thread_state: bool, + ) -> Result { + info!( + topic_id = query.topic_id, + post_number = ?query.post_number, + track_visit = query.track_visit, + "fetching topic detail" + ); + + let path = if let Some(post_number) = query.post_number { + format!("/t/{}/{}.json", query.topic_id, post_number) + } else { + format!("/t/{}.json", query.topic_id) + }; + + let mut params = Vec::new(); + if query.track_visit { + params.push(("track_visit", "true".to_string())); + } + if query.force_load { + params.push(("forceLoad", "true".to_string())); + } + if let Some(filter) = query.filter { + params.push(("filter", filter)); + } + if let Some(username_filters) = query.username_filters { + params.push(("username_filters", username_filters)); + } + if query.filter_top_level_replies { + params.push(("filter_top_level_replies", "true".to_string())); + } + + let mut extra_headers = Vec::new(); + if query.track_visit { + extra_headers.push(("Discourse-Track-View", "1".to_string())); + extra_headers.push(("Discourse-Track-View-Topic-Id", query.topic_id.to_string())); + } + + let traced = + self.build_json_get_request("fetch topic detail", &path, params, &extra_headers)?; + let (trace_id, response) = self.execute_request(traced).await?; + let response = expect_success(self, "fetch topic detail", trace_id, response).await?; + let raw: RawTopicDetail = self + .read_response_json("fetch topic detail", trace_id, response) + .await?; + let detail = raw.into_topic_detail(include_thread_state, self.base_url()); + ensure_requested_topic_detail(query.topic_id, detail.id)?; + Ok(detail) + } + +} diff --git a/rust/crates/fire-core/src/core/topics/source/mod.rs b/rust/crates/fire-core/src/core/topics/source/mod.rs new file mode 100644 index 00000000..4660f80e --- /dev/null +++ b/rust/crates/fire-core/src/core/topics/source/mod.rs @@ -0,0 +1,146 @@ +use std::collections::{HashMap, HashSet}; + +use fire_models::{ + TopicDetailSourceSnapshot, TopicHeader, TopicLoadMoreOutcome, TopicLoadMoreStopReason, + TopicLoadedRange, TopicPost, TopicSourceCursor, TopicTreePresentation, +}; + +use crate::error::FireCoreError; + +mod hydrate; +mod load; +mod session; + +pub(crate) use load::{ + load_more_topic_detail_posts, load_topic_detail_page, load_topic_detail_source_snapshot, +}; + +const TOPIC_POST_BATCH_SIZE: usize = 50; +const FETCH_TOPIC_AI_SUMMARY_OPERATION: &str = "fetch topic ai summary"; +const DEFAULT_TOPIC_INITIAL_BATCH_SIZE: u16 = 40; +const DEFAULT_TOPIC_LOAD_MORE_BATCH_SIZE: u16 = 40; +const DEFAULT_TOPIC_MAX_AUTO_BATCHES_PER_GESTURE: u8 = 3; +const DEFAULT_TOPIC_MAX_AUTO_POSTS_PER_GESTURE: u16 = 120; +const TOPIC_LOAD_MORE_FAILURE_MESSAGE: &str = "topic source batch append failed"; + +#[derive(Default)] +pub(crate) struct FireTopicDetailSourceRuntime { + next_session_id: u64, + sessions_by_topic_id: HashMap, +} + +#[derive(Clone)] +pub(crate) struct TopicDetailSourceSession { + session_id: u64, + session_epoch: u64, + header: TopicHeader, + body_post_id: u64, + body_post_number: u32, + focused_post_number: Option, + raw_stream_ids: Vec, + posts_by_id: HashMap, + post_id_by_number: HashMap, + unavailable_post_ids: HashSet, + loaded_ranges: Vec, + next_stream_offset: usize, + last_loaded_post_id: Option, + source_exhausted: bool, + load_more_policy: TopicLoadMorePolicy, +} + +#[derive(Clone, Copy)] +struct TopicLoadMorePolicy { + batch_size: u16, + max_auto_batches_per_gesture: u8, + max_auto_posts_per_gesture: u16, + require_new_root_progress: bool, +} + +#[derive(Default)] +struct TopicUnreadRootAutoSeekStats { + chained_batches: u8, + chained_posts: u16, +} + +struct TopicDetailSourceSessionInit { + session_epoch: u64, + header: TopicHeader, + body_post: TopicPost, + focused_post_number: Option, + raw_stream_ids: Vec, + cached_posts: Vec, + unavailable_post_ids: HashSet, + load_more_policy: TopicLoadMorePolicy, +} + +fn ensure_requested_topic_detail( + requested_topic_id: u64, + actual_topic_id: u64, +) -> Result<(), FireCoreError> { + if requested_topic_id == actual_topic_id { + return Ok(()); + } + Err(FireCoreError::UnexpectedTopicDetail { + requested_topic_id, + actual_topic_id, + }) +} + +fn normalized_topic_initial_batch_size(batch_size: u16) -> u16 { + if batch_size == 0 { + DEFAULT_TOPIC_INITIAL_BATCH_SIZE + } else { + batch_size + } +} + +fn topic_load_more_outcome( + source_snapshot: TopicDetailSourceSnapshot, + appended_posts: Vec, + tree_presentation: TopicTreePresentation, + chained_batches: u8, + chained_posts: u16, + stop_reason: TopicLoadMoreStopReason, +) -> TopicLoadMoreOutcome { + TopicLoadMoreOutcome { + source_snapshot, + appended_posts, + tree_presentation, + chained_batches, + chained_posts, + stop_reason, + } +} + +fn normalized_topic_load_more_batch_size(batch_size: u16) -> u16 { + if batch_size == 0 { + DEFAULT_TOPIC_LOAD_MORE_BATCH_SIZE + } else { + batch_size + } +} + +fn normalized_topic_auto_batch_limit(limit: u8) -> u8 { + if limit == 0 { + DEFAULT_TOPIC_MAX_AUTO_BATCHES_PER_GESTURE + } else { + limit + } +} + +fn normalized_topic_auto_post_limit(limit: u16) -> u16 { + if limit == 0 { + DEFAULT_TOPIC_MAX_AUTO_POSTS_PER_GESTURE + } else { + limit + } +} + +fn gained_visible_root_progress(previous: &[u32], current: &[u32]) -> bool { + let previous_roots = previous.iter().copied().collect::>(); + current + .iter() + .copied() + .any(|post_number| !previous_roots.contains(&post_number)) +} + diff --git a/rust/crates/fire-core/src/core/topics/source/session.rs b/rust/crates/fire-core/src/core/topics/source/session.rs new file mode 100644 index 00000000..f7c4d0eb --- /dev/null +++ b/rust/crates/fire-core/src/core/topics/source/session.rs @@ -0,0 +1,353 @@ +use std::collections::{HashMap, HashSet}; +use std::time::Instant; + +use fire_models::{ + LoadMoreTopicPostsQuery, TopicAiSummary, TopicBody, TopicDetail, TopicDetailPage, + TopicDetailQuery, TopicDetailSourceAppend, TopicDetailSourceQuery, TopicDetailSourceSnapshot, + TopicHeader, TopicLoadMoreOutcome, TopicLoadMoreStopReason, TopicLoadedRange, TopicPost, + TopicSourceCursor, TopicThread, TopicTreePresentation, +}; +use http::StatusCode; +use serde_json::Value; +use tracing::{info, warn}; + +use super::super::super::{network::expect_success, FireCore}; +use super::super::posts::{ + merge_topic_posts, missing_post_ids_from_ids, missing_topic_post_ids, + ordered_unique_post_ids, topic_posts_for_requested_ids, +}; +use super::super::tree::{ + build_topic_tree_presentation_from_source_snapshot, topic_detail_source_cooked_byte_count, + topic_tree_needs_unread_root_extension, +}; +use super::*; +use crate::{ + error::FireCoreError, + json_helpers::invalid_json, + topic_payloads::{parse_topic_ai_summary_value, parse_topic_post_stream_value, RawTopicDetail}, +}; +impl TopicDetailSourceSession { + pub(crate) fn raw_stream_len(&self) -> usize { + self.raw_stream_ids.len() + } + + pub(crate) fn raw_stream_ids(&self) -> &[u64] { + &self.raw_stream_ids + } + + pub(crate) fn contains_post_number(&self, post_number: u32) -> bool { + self.post_id_by_number.contains_key(&post_number) + } + + pub(crate) fn header(&self) -> &TopicHeader { + &self.header + } + + pub(crate) fn header_mut(&mut self) -> &mut TopicHeader { + &mut self.header + } + + pub(crate) fn post(&self, post_id: u64) -> Option<&TopicPost> { + self.posts_by_id.get(&post_id) + } + + pub(crate) fn post_mut(&mut self, post_id: u64) -> Option<&mut TopicPost> { + self.posts_by_id.get_mut(&post_id) + } + + pub(crate) fn stream_index_for_post_number(&self, post_number: u32) -> Option { + let post_id = self.post_id_by_number.get(&post_number).copied()?; + self.raw_stream_ids.iter().position(|id| *id == post_id) + } + + pub(crate) fn append_stream_post(&mut self, post: TopicPost) -> bool { + let is_new = !self.raw_stream_ids.contains(&post.id); + if is_new { + self.raw_stream_ids.push(post.id); + } + self.merge_posts(std::iter::once(post)); + self.recompute_loaded_state(); + is_new + } + + pub(crate) fn missing_ids_in_range(&self, range: std::ops::Range) -> Vec { + let end = range.end.min(self.raw_stream_ids.len()); + let start = range.start.min(end); + self.raw_stream_ids[start..end] + .iter() + .copied() + .filter(|post_id| !self.is_satisfied_post_id(*post_id)) + .collect() + } + + pub(crate) fn loaded_post_numbers_in_range(&self, range: std::ops::Range) -> Vec { + let end = range.end.min(self.raw_stream_ids.len()); + let start = range.start.min(end); + self.raw_stream_ids[start..end] + .iter() + .filter_map(|post_id| self.posts_by_id.get(post_id).map(|post| post.post_number)) + .collect() + } + + pub(super) fn new(init: TopicDetailSourceSessionInit) -> Self { + let TopicDetailSourceSessionInit { + session_epoch, + header, + body_post, + focused_post_number, + raw_stream_ids, + cached_posts, + unavailable_post_ids, + load_more_policy, + } = init; + let mut posts_by_id = HashMap::new(); + let mut post_id_by_number = HashMap::new(); + + post_id_by_number.insert(body_post.post_number, body_post.id); + posts_by_id.insert(body_post.id, body_post.clone()); + + for post in cached_posts { + post_id_by_number.insert(post.post_number, post.id); + posts_by_id.insert(post.id, post); + } + + let mut session = Self { + session_id: 0, + session_epoch, + header, + body_post_id: body_post.id, + body_post_number: body_post.post_number, + focused_post_number, + raw_stream_ids, + posts_by_id, + post_id_by_number, + unavailable_post_ids, + loaded_ranges: Vec::new(), + next_stream_offset: 0, + last_loaded_post_id: None, + source_exhausted: false, + load_more_policy, + }; + session.recompute_loaded_state(); + session + } + + pub(super) fn with_session_id(mut self, session_id: u64) -> Self { + self.session_id = session_id; + self + } + + pub(super) fn posts_for_ids(&self, post_ids: &[u64]) -> Vec { + post_ids + .iter() + .filter_map(|post_id| self.posts_by_id.get(post_id).cloned()) + .collect() + } + + pub(crate) fn merge_posts(&mut self, posts: impl IntoIterator) { + for mut post in posts { + self.unavailable_post_ids.remove(&post.id); + self.post_id_by_number.insert(post.post_number, post.id); + if let Some(existing) = self.posts_by_id.get(&post.id) { + post.reuse_presentation_from(existing); + } + self.posts_by_id.insert(post.id, post); + } + } + pub(crate) fn mark_unavailable(&mut self, post_ids: HashSet) { + for post_id in post_ids { + if !self.posts_by_id.contains_key(&post_id) { + self.unavailable_post_ids.insert(post_id); + } + } + } + + pub(crate) fn recompute_loaded_state(&mut self) { + self.loaded_ranges.clear(); + let mut active_range_start: Option = None; + let mut active_range_first_post_id: Option = None; + + for (offset, post_id) in self.raw_stream_ids.iter().copied().enumerate() { + if self.is_satisfied_post_id(post_id) { + if active_range_start.is_none() { + active_range_start = Some(offset); + active_range_first_post_id = Some(post_id); + } + continue; + } + + if let Some(start_offset) = active_range_start.take() { + self.loaded_ranges.push(TopicLoadedRange { + start_offset: start_offset as u32, + end_offset_exclusive: offset as u32, + first_post_id: active_range_first_post_id + .take() + .unwrap_or(self.raw_stream_ids[start_offset]), + last_post_id: self.raw_stream_ids[offset.saturating_sub(1)], + }); + } + } + + if let Some(start_offset) = active_range_start { + self.loaded_ranges.push(TopicLoadedRange { + start_offset: start_offset as u32, + end_offset_exclusive: self.raw_stream_ids.len() as u32, + first_post_id: active_range_first_post_id + .unwrap_or(self.raw_stream_ids[start_offset]), + last_post_id: self + .raw_stream_ids + .last() + .copied() + .unwrap_or(self.body_post_id), + }); + } + + self.next_stream_offset = self + .raw_stream_ids + .iter() + .take_while(|post_id| self.is_satisfied_post_id(**post_id)) + .count(); + self.last_loaded_post_id = self + .next_stream_offset + .checked_sub(1) + .and_then(|offset| self.raw_stream_ids.get(offset).copied()); + self.source_exhausted = self.next_stream_offset >= self.raw_stream_ids.len(); + } + + pub(super) fn source_cursor(&self) -> Option { + (!self.source_exhausted).then_some(TopicSourceCursor { + topic_id: self.header.topic_id, + session_id: self.session_id, + next_stream_offset: self.next_stream_offset as u32, + last_loaded_post_id: self.last_loaded_post_id, + batch_size: self.load_more_policy.batch_size, + }) + } + + pub(crate) fn source_snapshot(&self) -> TopicDetailSourceSnapshot { + TopicDetailSourceSnapshot { + header: self.header.clone(), + body: TopicBody { + post: self.body_post(), + }, + raw_stream_ids: self.raw_stream_ids.clone(), + loaded_posts: self.ordered_loaded_posts(), + loaded_ranges: self.loaded_ranges.clone(), + source_cursor: self.source_cursor(), + source_exhausted: self.source_exhausted, + focused_post_number: self.focused_post_number, + } + } + + fn body_post(&self) -> TopicPost { + self.posts_by_id + .get(&self.body_post_id) + .cloned() + .or_else(|| { + self.post_id_by_number + .get(&self.body_post_number) + .and_then(|post_id| self.posts_by_id.get(post_id)) + .cloned() + }) + .expect("topic detail source session missing body post") + } + + fn ordered_loaded_posts(&self) -> Vec { + merge_topic_posts( + &self.raw_stream_ids, + self.posts_by_id.values().cloned().collect(), + Vec::new(), + ) + } + + fn is_satisfied_post_id(&self, post_id: u64) -> bool { + self.posts_by_id.contains_key(&post_id) || self.unavailable_post_ids.contains(&post_id) + } +} + + +#[cfg(test)] +mod tests { + use super::*; + use super::super::gained_visible_root_progress; + use super::super::super::posts::ordered_unique_post_ids; + use fire_models::{TopicHeader, TopicPost}; + use std::collections::HashSet; + + fn make_topic_post(post_number: u32, reply_to_post_number: Option) -> TopicPost { + TopicPost { + id: u64::from(post_number), + username: format!("user-{post_number}"), + cooked: format!("

{post_number}

"), + post_number, + reply_to_post_number, + ..TopicPost::default() + } + } + + #[test] + fn ordered_unique_post_ids_drops_zeroes_and_duplicates() { + assert_eq!( + ordered_unique_post_ids(vec![0, 2, 2, 3, 0, 4, 3]), + vec![2, 3, 4] + ); + } + + #[test] + fn source_session_tracks_contiguous_loaded_ranges_and_unavailable_post_ids() { + let body_post = make_topic_post(1, None); + let second_post = make_topic_post(2, Some(1)); + let fourth_post = make_topic_post(4, Some(1)); + let mut session = TopicDetailSourceSession::new(TopicDetailSourceSessionInit { + session_epoch: 3, + header: TopicHeader { + topic_id: 42, + ..TopicHeader::default() + }, + body_post: body_post.clone(), + focused_post_number: None, + raw_stream_ids: vec![body_post.id, second_post.id, 3, fourth_post.id], + cached_posts: vec![body_post.clone(), second_post.clone(), fourth_post.clone()], + unavailable_post_ids: HashSet::new(), + load_more_policy: TopicLoadMorePolicy { + batch_size: 40, + max_auto_batches_per_gesture: 3, + max_auto_posts_per_gesture: 120, + require_new_root_progress: true, + }, + }); + + assert_eq!(session.next_stream_offset, 2); + assert_eq!(session.last_loaded_post_id, Some(2)); + assert_eq!( + session + .loaded_ranges + .iter() + .map(|range| (range.start_offset, range.end_offset_exclusive)) + .collect::>(), + vec![(0, 2), (3, 4)] + ); + assert!(!session.source_exhausted); + + session.mark_unavailable(HashSet::from([3])); + session.recompute_loaded_state(); + + assert_eq!(session.next_stream_offset, 4); + assert_eq!(session.last_loaded_post_id, Some(4)); + assert!(session.source_exhausted); + assert_eq!( + session + .loaded_ranges + .iter() + .map(|range| (range.start_offset, range.end_offset_exclusive)) + .collect::>(), + vec![(0, 4)] + ); + } + + #[test] + fn gained_visible_root_progress_detects_new_root_post_numbers() { + assert!(!gained_visible_root_progress(&[2, 5], &[2, 5])); + assert!(gained_visible_root_progress(&[2, 5], &[2, 5, 8])); + } +} diff --git a/rust/crates/fire-core/src/core/topics/tree.rs b/rust/crates/fire-core/src/core/topics/tree.rs new file mode 100644 index 00000000..b5717502 --- /dev/null +++ b/rust/crates/fire-core/src/core/topics/tree.rs @@ -0,0 +1,563 @@ +use std::collections::{BTreeMap, HashMap, HashSet}; + +use tracing::debug; + +use fire_models::{ + TopicDetailSourceSnapshot, TopicPost, TopicTreePresentation, TopicTreePresentationQuery, + TopicTreeRow, +}; + +use super::posts::{ + deduplicate_topic_posts_by_id, merge_topic_posts, ordered_unique_post_ids, +}; + +use super::super::FireCore; + +const TOPIC_PARENT_HOP_LIMIT: usize = 32; + +fn build_topic_tree_presentation_from_query( + query: TopicTreePresentationQuery, +) -> TopicTreePresentation { + let mut ordered_posts = deduplicate_topic_posts_by_id(merge_topic_posts( + &query.raw_stream_ids, + query.loaded_posts, + Vec::new(), + )); + if !ordered_posts + .iter() + .any(|post| post.id == query.body_post.id) + { + ordered_posts.push(query.body_post.clone()); + ordered_posts = deduplicate_topic_posts_by_id(merge_topic_posts( + &query.raw_stream_ids, + ordered_posts, + Vec::new(), + )); + } + + let original_post = ordered_posts + .iter() + .find(|post| { + post.id == query.body_post.id || post.post_number == query.body_post.post_number + }) + .cloned() + .unwrap_or(query.body_post); + + let mut posts_by_id = HashMap::new(); + let mut posts_by_number = HashMap::new(); + for post in ordered_posts { + posts_by_number.insert(post.post_number, post.clone()); + posts_by_id.insert(post.id, post); + } + + let stream_index_by_post_id = query + .raw_stream_ids + .iter() + .enumerate() + .map(|(index, post_id)| (*post_id, index)) + .collect::>(); + + let mut children_by_parent = BTreeMap::>::new(); + for post in posts_by_id.values() { + if post.id == original_post.id { + continue; + } + let parent_post_number = resolve_tree_attachment_parent_post_number( + post, + &posts_by_number, + original_post.post_number, + ); + children_by_parent + .entry(parent_post_number) + .or_default() + .push(post.id); + } + + for child_post_ids in children_by_parent.values_mut() { + child_post_ids.sort_by_key(|post_id| { + let stream_index = stream_index_by_post_id + .get(post_id) + .copied() + .unwrap_or(usize::MAX); + let post_key = posts_by_id + .get(post_id) + .map(|post| (post.post_number, post.id)) + .unwrap_or((u32::MAX, u64::MAX)); + (stream_index, post_key.0, post_key.1) + }); + } + + let mut reply_rows = Vec::new(); + let mut visible_root_post_numbers = Vec::new(); + let mut visited = HashSet::new(); + let root_children = children_by_parent + .get(&original_post.post_number) + .cloned() + .unwrap_or_default(); + append_tree_rows_preorder( + &root_children, + original_post.post_number, + 0, + None, + &posts_by_id, + &children_by_parent, + &mut visited, + &mut reply_rows, + &mut visible_root_post_numbers, + ); + + let mut orphan_post_ids = query + .raw_stream_ids + .iter() + .copied() + .filter(|post_id| { + posts_by_id.contains_key(post_id) + && *post_id != original_post.id + && !visited.contains(post_id) + }) + .collect::>(); + orphan_post_ids.extend( + posts_by_id + .keys() + .copied() + .filter(|post_id| *post_id != original_post.id && !visited.contains(post_id)), + ); + orphan_post_ids = ordered_unique_post_ids(orphan_post_ids); + if !orphan_post_ids.is_empty() { + append_tree_rows_preorder( + &orphan_post_ids, + original_post.post_number, + 0, + None, + &posts_by_id, + &children_by_parent, + &mut visited, + &mut reply_rows, + &mut visible_root_post_numbers, + ); + } + + TopicTreePresentation { + original_post_id: original_post.id, + original_post_number: original_post.post_number, + first_unread_root_post_number: first_unread_root_post_number( + &reply_rows, + original_post.post_number, + query.last_read_post_number, + ), + reply_rows, + total_loaded_post_count: posts_by_id.len() as u32, + visible_root_post_numbers, + gained_new_root_progress: false, + } +} + +pub(crate) fn build_topic_tree_presentation_from_source_snapshot( + snapshot: &TopicDetailSourceSnapshot, +) -> TopicTreePresentation { + build_topic_tree_presentation_from_query(TopicTreePresentationQuery { + body_post: snapshot.body.post.clone(), + raw_stream_ids: snapshot.raw_stream_ids.clone(), + loaded_posts: snapshot.loaded_posts.clone(), + focused_post_number: snapshot.focused_post_number, + last_read_post_number: snapshot.header.last_read_post_number, + }) +} + +pub(super) fn topic_tree_needs_unread_root_extension( + snapshot: &TopicDetailSourceSnapshot, + presentation: &TopicTreePresentation, +) -> bool { + let Some(last_read_post_number) = snapshot.header.last_read_post_number else { + return false; + }; + last_read_post_number > 0 + && last_read_post_number < snapshot.header.highest_post_number + && presentation.first_unread_root_post_number.is_none() + && !snapshot.source_exhausted +} + +pub(super) fn first_unread_root_post_number( + reply_rows: &[TopicTreeRow], + original_post_number: u32, + last_read_post_number: Option, +) -> Option { + let last_read_post_number = last_read_post_number?; + reply_rows + .iter() + .find(|row| { + row.parent_post_number == Some(original_post_number) + && row.post_number > last_read_post_number + }) + .map(|row| row.post_number) +} + +pub(super) fn topic_detail_source_cooked_byte_count(snapshot: &TopicDetailSourceSnapshot) -> usize { + let mut seen_post_ids = HashSet::new(); + let mut total = 0usize; + for post in std::iter::once(&snapshot.body.post).chain(snapshot.loaded_posts.iter()) { + if seen_post_ids.insert(post.id) { + total += post.cooked.len(); + } + } + total +} + +#[allow(clippy::too_many_arguments)] +fn append_tree_rows_preorder( + child_post_ids: &[u64], + parent_post_number: u32, + parent_depth: u16, + current_root_post_number: Option, + posts_by_id: &HashMap, + children_by_parent: &BTreeMap>, + visited: &mut HashSet, + reply_rows: &mut Vec, + visible_root_post_numbers: &mut Vec, +) -> u32 { + let mut descendant_total = 0_u32; + + for (sibling_index, child_post_id) in child_post_ids.iter().copied().enumerate() { + if !visited.insert(child_post_id) { + continue; + } + let Some(post) = posts_by_id.get(&child_post_id).cloned() else { + continue; + }; + let root_post_number = current_root_post_number.unwrap_or(post.post_number); + if current_root_post_number.is_none() + && visible_root_post_numbers.last().copied() != Some(root_post_number) + { + visible_root_post_numbers.push(root_post_number); + } + + let row_index = reply_rows.len(); + let grand_children = children_by_parent + .get(&post.post_number) + .cloned() + .unwrap_or_default(); + reply_rows.push(TopicTreeRow { + post_id: post.id, + post_number: post.post_number, + root_post_number, + parent_post_number: Some(parent_post_number), + depth: parent_depth.saturating_add(1), + preorder_index: row_index as u32, + has_children: !grand_children.is_empty(), + sibling_index: sibling_index as u16, + is_last_sibling: sibling_index + 1 == child_post_ids.len(), + descendant_count: 0, + }); + let nested_descendant_count = append_tree_rows_preorder( + &grand_children, + post.post_number, + parent_depth.saturating_add(1), + Some(root_post_number), + posts_by_id, + children_by_parent, + visited, + reply_rows, + visible_root_post_numbers, + ); + reply_rows[row_index].descendant_count = nested_descendant_count; + descendant_total = descendant_total.saturating_add(1 + nested_descendant_count); + } + + descendant_total +} + +fn resolve_tree_attachment_parent_post_number( + post: &TopicPost, + posts_by_number: &HashMap, + body_post_number: u32, +) -> u32 { + let Some(declared_parent) = normalized_reply_target(post.reply_to_post_number) else { + return body_post_number; + }; + if declared_parent == body_post_number || declared_parent == post.post_number { + if declared_parent == post.post_number { + debug!( + post_number = post.post_number, + declared_parent, + body_post_number, + "topic tree attachment parent fell back to body: post replies to itself" + ); + } + return body_post_number; + } + if !posts_by_number.contains_key(&declared_parent) { + debug!( + post_number = post.post_number, + declared_parent, + body_post_number, + "topic tree attachment parent fell back to body: declared parent missing from loaded posts" + ); + return body_post_number; + } + + let mut current_parent = declared_parent; + let mut visited = [0_u32; TOPIC_PARENT_HOP_LIMIT + 1]; + visited[0] = post.post_number; + for visited_len in (1..).take(TOPIC_PARENT_HOP_LIMIT) { + if visited[..visited_len].contains(¤t_parent) { + debug!( + post_number = post.post_number, + declared_parent, + current_parent, + body_post_number, + "topic tree attachment parent fell back to body: detected reply cycle" + ); + return body_post_number; + } + visited[visited_len] = current_parent; + let Some(parent_post) = posts_by_number.get(¤t_parent) else { + debug!( + post_number = post.post_number, + declared_parent, + current_parent, + body_post_number, + "topic tree attachment parent fell back to body: ancestor disappeared from loaded posts" + ); + return body_post_number; + }; + match normalized_reply_target(parent_post.reply_to_post_number) { + Some(next_parent) if next_parent == body_post_number => return declared_parent, + Some(next_parent) if next_parent == parent_post.post_number => { + debug!( + post_number = post.post_number, + declared_parent, + current_parent, + body_post_number, + "topic tree attachment parent fell back to body: ancestor replies to itself" + ); + return body_post_number; + } + Some(next_parent) => { + current_parent = next_parent; + } + None => return declared_parent, + } + } + + debug!( + post_number = post.post_number, + declared_parent, + body_post_number, + hop_limit = TOPIC_PARENT_HOP_LIMIT, + "topic tree attachment parent fell back to body: exceeded parent hop limit" + ); + body_post_number +} + +fn normalized_reply_target(reply_to_post_number: Option) -> Option { + reply_to_post_number.filter(|post_number| *post_number > 0) +} + +impl FireCore { + pub fn build_topic_tree_presentation( + &self, + query: TopicTreePresentationQuery, + ) -> TopicTreePresentation { + build_topic_tree_presentation_from_query(query) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use fire_models::TopicPost; + use std::collections::HashMap; + + fn make_topic_post(post_number: u32, reply_to_post_number: Option) -> TopicPost { + TopicPost { + id: u64::from(post_number), + username: format!("user-{post_number}"), + cooked: format!("

{post_number}

"), + post_number, + reply_to_post_number, + ..TopicPost::default() + } + } + + #[test] + fn resolve_tree_attachment_parent_falls_back_to_body_when_intermediate_is_missing() { + let body_post = make_topic_post(1, None); + let post = make_topic_post(5, Some(3)); + let posts_by_number = HashMap::from([ + (body_post.post_number, body_post.clone()), + (post.post_number, post.clone()), + ]); + + let attachment_parent = resolve_tree_attachment_parent_post_number( + &post, + &posts_by_number, + body_post.post_number, + ); + + assert_eq!(attachment_parent, body_post.post_number); + } + + #[test] + fn resolve_tree_attachment_parent_falls_back_to_body_when_cycle_is_detected() { + let body_post = make_topic_post(1, None); + let post = make_topic_post(3, Some(4)); + let parent = make_topic_post(4, Some(3)); + let posts_by_number = HashMap::from([ + (body_post.post_number, body_post.clone()), + (post.post_number, post.clone()), + (parent.post_number, parent), + ]); + + let attachment_parent = resolve_tree_attachment_parent_post_number( + &post, + &posts_by_number, + body_post.post_number, + ); + + assert_eq!(attachment_parent, body_post.post_number); + } + + #[test] + fn resolve_tree_attachment_parent_falls_back_to_body_after_hop_limit() { + let body_post = make_topic_post(1, None); + let mut posts_by_number = HashMap::from([(body_post.post_number, body_post.clone())]); + + for post_number in 2..=36 { + let reply_to_post_number = if post_number == 3 { + Some(body_post.post_number) + } else { + Some(post_number - 1) + }; + let post = make_topic_post(post_number, reply_to_post_number); + posts_by_number.insert(post.post_number, post); + } + + let post = posts_by_number + .get(&36) + .expect("missing deep descendant post"); + let attachment_parent = resolve_tree_attachment_parent_post_number( + post, + &posts_by_number, + body_post.post_number, + ); + + assert_eq!(attachment_parent, body_post.post_number); + } + + #[test] + fn tree_presentation_preserves_parent_numbers_depths_and_root_grouping() { + let body_post = make_topic_post(1, None); + let root_post = make_topic_post(2, Some(1)); + let child_post = make_topic_post(3, Some(2)); + let grandchild_post = make_topic_post(4, Some(3)); + let second_root = make_topic_post(5, Some(1)); + + let presentation = build_topic_tree_presentation_from_query(TopicTreePresentationQuery { + body_post: body_post.clone(), + raw_stream_ids: vec![ + body_post.id, + root_post.id, + child_post.id, + grandchild_post.id, + second_root.id, + ], + loaded_posts: vec![ + body_post.clone(), + root_post.clone(), + child_post.clone(), + grandchild_post.clone(), + second_root.clone(), + ], + focused_post_number: None, + last_read_post_number: Some(4), + }); + + assert_eq!( + presentation + .reply_rows + .iter() + .map(|row| row.post_id) + .collect::>(), + vec![ + root_post.id, + child_post.id, + grandchild_post.id, + second_root.id + ] + ); + assert_eq!(presentation.reply_rows[0].parent_post_number, Some(1)); + assert_eq!(presentation.reply_rows[0].depth, 1); + assert_eq!(presentation.reply_rows[1].parent_post_number, Some(2)); + assert_eq!(presentation.reply_rows[1].depth, 2); + assert_eq!(presentation.reply_rows[2].parent_post_number, Some(3)); + assert_eq!(presentation.reply_rows[2].depth, 3); + assert_eq!( + presentation + .reply_rows + .iter() + .map(|row| row.root_post_number) + .collect::>(), + vec![2, 2, 2, 5] + ); + assert_eq!(presentation.visible_root_post_numbers, vec![2, 5]); + assert_eq!(presentation.first_unread_root_post_number, Some(5)); + } + + #[test] + fn tree_presentation_reparents_missing_branch_to_body() { + let body_post = make_topic_post(1, None); + let orphan_root = make_topic_post(5, Some(99)); + let orphan_child = make_topic_post(6, Some(5)); + + let presentation = build_topic_tree_presentation_from_query(TopicTreePresentationQuery { + body_post: body_post.clone(), + raw_stream_ids: vec![body_post.id, orphan_root.id, orphan_child.id], + loaded_posts: vec![body_post.clone(), orphan_root.clone(), orphan_child.clone()], + focused_post_number: None, + last_read_post_number: Some(5), + }); + + assert_eq!( + presentation + .reply_rows + .iter() + .map(|row| row.post_id) + .collect::>(), + vec![orphan_root.id, orphan_child.id] + ); + assert_eq!(presentation.reply_rows[0].parent_post_number, Some(1)); + assert_eq!(presentation.reply_rows[1].parent_post_number, Some(1)); + assert_eq!(presentation.reply_rows[0].depth, 1); + assert_eq!(presentation.reply_rows[1].depth, 1); + assert_eq!( + presentation + .reply_rows + .iter() + .map(|row| row.root_post_number) + .collect::>(), + vec![5, 6] + ); + assert_eq!(presentation.visible_root_post_numbers, vec![5, 6]); + assert_eq!(presentation.first_unread_root_post_number, Some(6)); + } + + #[test] + fn tree_presentation_ignores_nested_unread_posts_for_root_target() { + let body_post = make_topic_post(1, None); + let root_post = make_topic_post(2, Some(1)); + let child_post = make_topic_post(9, Some(2)); + + let presentation = build_topic_tree_presentation_from_query(TopicTreePresentationQuery { + body_post: body_post.clone(), + raw_stream_ids: vec![body_post.id, root_post.id, child_post.id], + loaded_posts: vec![body_post.clone(), root_post.clone(), child_post.clone()], + focused_post_number: None, + last_read_post_number: Some(8), + }); + + assert_eq!(presentation.visible_root_post_numbers, vec![2]); + assert_eq!(presentation.first_unread_root_post_number, None); + } + + +} diff --git a/rust/crates/fire-core/src/lib.rs b/rust/crates/fire-core/src/lib.rs index 825e9722..ba0e3965 100644 --- a/rust/crates/fire-core/src/lib.rs +++ b/rust/crates/fire-core/src/lib.rs @@ -29,6 +29,7 @@ pub use chat_payloads::{ pub use config::FireCoreConfig; pub use core::{ FireAuthRecoveryHint, FireAuthRecoveryHintReason, FireCore, FireSessionPersistenceState, + TopicDetailObserver, TopicDetailOpenRequest, TopicDetailSession, TopicDetailSessionRegistry, }; pub use diagnostics::{ DiagnosticsPageDirection, DiagnosticsTextPage, FireLogFileDetail, FireLogFilePage, diff --git a/rust/crates/fire-core/src/session_store.rs b/rust/crates/fire-core/src/session_store.rs index 74e251b7..c1c9181f 100644 --- a/rust/crates/fire-core/src/session_store.rs +++ b/rust/crates/fire-core/src/session_store.rs @@ -60,6 +60,7 @@ impl From for SessionSnapshot { cookies: value.cookies.into(), bootstrap: value.bootstrap.into(), browser_user_agent: None, + read_path_login_request: None, } } } diff --git a/rust/crates/fire-core/src/state_observer.rs b/rust/crates/fire-core/src/state_observer.rs index b21481c6..cc0c86f5 100644 --- a/rust/crates/fire-core/src/state_observer.rs +++ b/rust/crates/fire-core/src/state_observer.rs @@ -169,6 +169,7 @@ mod tests { ..BootstrapArtifacts::default() }, browser_user_agent: None, + read_path_login_request: None, } } diff --git a/rust/crates/fire-models/src/lib.rs b/rust/crates/fire-models/src/lib.rs index 4e23df30..b6c47f24 100644 --- a/rust/crates/fire-models/src/lib.rs +++ b/rust/crates/fire-models/src/lib.rs @@ -10,6 +10,7 @@ mod search; mod session; mod topic; mod topic_detail; +mod topic_detail_ui; mod user; pub use cf_clearance::*; @@ -24,6 +25,7 @@ pub use search::*; pub use session::*; pub use topic::*; pub use topic_detail::*; +pub use topic_detail_ui::*; pub use user::*; #[cfg(test)] @@ -583,6 +585,7 @@ mod tests { ..BootstrapArtifacts::default() }, browser_user_agent: None, + read_path_login_request: None, }; let readiness = snapshot.readiness(); @@ -608,6 +611,7 @@ mod tests { ..BootstrapArtifacts::default() }, browser_user_agent: None, + read_path_login_request: None, }; let readiness = snapshot.readiness(); @@ -654,6 +658,7 @@ mod tests { default_composer_category: Some(2), }, browser_user_agent: None, + read_path_login_request: None, }; snapshot.clear_login_state(true); diff --git a/rust/crates/fire-models/src/session.rs b/rust/crates/fire-models/src/session.rs index 93bd2bb8..1ed86552 100644 --- a/rust/crates/fire-models/src/session.rs +++ b/rust/crates/fire-models/src/session.rs @@ -313,6 +313,10 @@ pub struct SessionSnapshot { pub bootstrap: BootstrapArtifacts, #[serde(default)] pub browser_user_agent: Option, + /// Wake-up copy for `SessionState::from_snapshot`. Not persisted and not part of + /// `snapshot_revision`. The authoritative value lives on `FireSessionRuntimeState`. + #[serde(skip)] + pub read_path_login_request: Option, } impl SessionSnapshot { diff --git a/rust/crates/fire-models/src/topic_detail_ui.rs b/rust/crates/fire-models/src/topic_detail_ui.rs new file mode 100644 index 00000000..c04e4c19 --- /dev/null +++ b/rust/crates/fire-models/src/topic_detail_ui.rs @@ -0,0 +1,300 @@ +use crate::rich_text::AttachedPresentation; +use crate::topic_detail::{Poll, PostActionType, TopicReaction}; + +/// Read-path login wake-up. Lives on runtime session state, not the persisted envelope. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ReadPathLoginRequest { + pub generation: u64, + pub operation: String, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TopicDetailPhase { + Loading, + Ready, + Failed, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum TopicDetailLoadError { + Network, + LoginRequired, + Unrecoverable { message: String }, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TopicDetailNotice { + pub title: Option, + pub message: String, + pub retryable: bool, + pub emphasizes_error: bool, +} + +/// Unread formula copied from the removed Swift `patchedTopicRow`. +/// Swift assigns fields; it does not compare post numbers. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TopicHomeUnreadDecision { + /// `last_read` is None. If the row's `has_unread_posts` is false, zero both counts. + /// If it is true, keep both counts. Leave the flag as it is. + WhenLastReadMissing, + /// `last_read >= highest`. Zero both counts. `has_unread_posts = false`. + CaughtUp, + /// `last_read < highest`. Keep both counts. `has_unread_posts = true`. + StillUnread, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TopicHomeRowCountPatch { + pub topic_id: u64, + pub posts_count: u32, + pub reply_count: u32, + pub views: u32, + pub last_read_post_number: Option, + pub highest_post_number: u32, + pub unread: TopicHomeUnreadDecision, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TopicDetailAuthorDisplay { + pub username: String, + pub name: Option, + pub avatar_template: Option, + pub user_id: Option, + pub user_title: Option, + pub primary_group_name: Option, + pub flair_url: Option, + pub flair_name: Option, + pub flair_bg_color: Option, + pub flair_color: Option, + pub flair_group_id: Option, + pub moderator: bool, + pub admin: bool, + pub group_moderator: bool, + pub user_status_emoji: Option, + pub user_status_description: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TopicDetailParticipantDisplay { + pub user_id: u64, + pub username: String, + pub name: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TopicDetailReactionChip { + pub id: String, + pub kind: Option, + pub count: u32, + pub can_undo: Option, + pub selected: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TopicDetailPollOptionDisplay { + pub id: String, + pub html: String, + pub plain_text: String, + pub votes: u32, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TopicDetailPollDisplay { + pub id: u64, + pub name: String, + pub kind: String, + pub status: String, + pub results: String, + pub options: Vec, + pub voters: u32, + pub user_votes: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TopicDetailBoostUserDisplay { + pub id: u64, + pub username: String, + pub name: Option, + pub avatar_template: Option, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct TopicDetailBoostDisplay { + pub id: u64, + pub display_text: String, + pub user: TopicDetailBoostUserDisplay, + pub can_delete: bool, + pub can_flag: bool, + pub user_flag_status: Option, + pub available_flags: Vec, + pub presentation: AttachedPresentation, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TopicDetailReplyUserDisplay { + pub username: String, + pub name: Option, + pub avatar_template: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TopicDetailTypingUser { + pub id: u64, + pub username: String, + pub avatar_template: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TopicDetailChrome { + pub title: String, + pub slug: String, + pub archetype: Option, + pub bookmarked: bool, + pub bookmark_id: Option, + pub bookmark_name: Option, + pub bookmark_reminder_at: Option, + pub notification_level: Option, + pub can_edit: bool, + pub category_id: Option, + pub tags: Vec, + pub views: u32, + pub posts_count: u32, + pub reply_count: u32, + pub like_count: u32, + pub vote_count: i32, + pub user_voted: bool, + pub can_vote: bool, + pub has_accepted_answer: bool, + pub created_at: Option, + pub highest_post_number: u32, + pub last_read_post_number: Option, + pub participants: Vec, + pub summarizable: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct TopicDetailComposerModel { + pub typing_users: Vec, + pub is_submitting: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct TopicDetailSidecarModel { + pub summarized_text: Option, + pub algorithm: Option, + pub outdated: bool, + pub can_regenerate: bool, + pub new_posts_since_summary: u32, + pub updated_at: Option, + pub is_loading: bool, + pub error: Option, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct TopicDetailUiRow { + pub post_id: u64, + pub post_number: u32, + pub root_post_number: u32, + pub parent_post_number: Option, + pub depth: u16, + pub has_children: bool, + pub is_last_sibling: bool, + pub descendant_count: u32, + pub author: TopicDetailAuthorDisplay, + pub presentation: AttachedPresentation, + pub layout_checksum: u64, + pub interaction_checksum: u64, + pub created_at: Option, + pub updated_at: Option, + pub post_type: i32, + pub reply_count: u32, + pub reply_to_username: Option, + pub reply_to_user: Option, + pub like_count: u32, + pub reactions: Vec, + pub current_reaction_id: Option, + pub polls: Vec, + pub boosts: Vec, + pub accepted_answer: bool, + pub can_accept_answer: bool, + pub can_unaccept_answer: bool, + pub can_edit: bool, + pub can_delete: bool, + pub can_recover: bool, + pub can_boost: bool, + pub bookmarked: bool, + pub bookmark_id: Option, + pub bookmark_name: Option, + pub bookmark_reminder_at: Option, + pub hidden: bool, + pub is_mutating: bool, + pub is_loading_reply_context: bool, + pub is_original_post: bool, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct TopicDetailReplyContext { + pub root_post_id: u64, + pub appended_post_ids: Vec, + pub history_rows: Vec, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct TopicDetailUiSnapshot { + pub topic_id: u64, + pub generation: u64, + pub phase: TopicDetailPhase, + pub load_error: Option, + pub notice: Option, + pub has_more: bool, + pub is_loading_more: bool, + pub load_more_error: Option, + pub scroll_target_post_number: Option, + pub collection_revision: u64, + pub chrome_revision: u64, + pub sidecar_revision: u64, + pub interaction_revision: u64, + pub chrome: TopicDetailChrome, + pub composer: TopicDetailComposerModel, + pub sidecar: TopicDetailSidecarModel, + pub rows: Vec, + pub focused_reply_context: Option, + pub flag_types: Vec, + pub home_row_patch: Option, +} + +impl TopicDetailReactionChip { + pub fn from_reaction(reaction: &TopicReaction, selected: bool) -> Self { + Self { + id: reaction.id.clone(), + kind: reaction.kind.clone(), + count: reaction.count, + can_undo: reaction.can_undo, + selected, + } + } +} + +impl From<&Poll> for TopicDetailPollDisplay { + fn from(poll: &Poll) -> Self { + Self { + id: poll.id, + name: poll.name.clone(), + kind: poll.kind.clone(), + status: poll.status.clone(), + results: poll.results.clone(), + options: poll + .options + .iter() + .map(|option| TopicDetailPollOptionDisplay { + id: option.id.clone(), + html: option.html.clone(), + plain_text: option.plain_text.clone(), + votes: option.votes, + }) + .collect(), + voters: poll.voters, + user_votes: poll.user_votes.clone(), + } + } +} diff --git a/rust/crates/fire-store/src/lib.rs b/rust/crates/fire-store/src/lib.rs index 4fdf7d56..1093b140 100644 --- a/rust/crates/fire-store/src/lib.rs +++ b/rust/crates/fire-store/src/lib.rs @@ -135,6 +135,32 @@ impl FireStore { Ok(()) } + pub fn topic_list_cache_list_pages( + &self, + auth_scope_hash: &str, + scope_key: &str, + ) -> Result, FireStoreError> { + let mut stmt = self.connection.prepare( + r#" + SELECT page, payload_json + FROM topic_list_cache + WHERE auth_scope_hash = ?1 AND scope_key = ?2 + ORDER BY page ASC, fetched_at_ms DESC + "#, + )?; + let mut rows = stmt.query(rusqlite::params![auth_scope_hash, scope_key])?; + let mut pages = Vec::new(); + while let Some(row) = rows.next()? { + let page = u32::try_from(row.get::<_, i64>(0)?).unwrap_or(0); + let payload = row.get::<_, String>(1)?; + if pages.iter().any(|(existing, _)| *existing == page) { + continue; + } + pages.push((page, payload)); + } + Ok(pages) + } + pub fn topic_list_cache_read( &self, auth_scope_hash: &str, diff --git a/rust/crates/fire-uniffi-session/src/lib.rs b/rust/crates/fire-uniffi-session/src/lib.rs index 0b0d48c7..fa73b228 100644 --- a/rust/crates/fire-uniffi-session/src/lib.rs +++ b/rust/crates/fire-uniffi-session/src/lib.rs @@ -21,7 +21,8 @@ pub use records::{ LoginFinalizationResultState, LoginPhaseState, LoginStateDeterminationState, LoginSyncState, NuclearResetPlanState, PassiveLogoutTriggerState, PlatformCookieState, PreloadedDataStateState, RefreshBatchState, RefreshTriggerState, SecondFactorRequirementState, SessionPersistenceState, - SessionReadinessState, SessionState, TopicCategoryState, WebViewCookieActionState, + SessionReadinessState, SessionState, ReadPathLoginRequestState, TopicCategoryState, + WebViewCookieActionState, WebViewCookieInfoState, WebViewLoginDecisionState, WebViewLoginJsResultState, WebViewLoginPhaseState, }; @@ -83,6 +84,19 @@ impl FireSessionHandle { ) } + pub fn complete_read_path_login( + &self, + generation: u64, + succeeded: bool, + ) -> Result<(), FireUniFfiError> { + run_infallible( + &self.shared.panic_state, + &self.shared.core, + "complete_read_path_login", + move |inner| inner.complete_read_path_login(generation, succeeded), + ) + } + pub fn snapshot(&self) -> Result { run_infallible( &self.shared.panic_state, diff --git a/rust/crates/fire-uniffi-session/src/records.rs b/rust/crates/fire-uniffi-session/src/records.rs index 3837d999..9607fb51 100644 --- a/rust/crates/fire-uniffi-session/src/records.rs +++ b/rust/crates/fire-uniffi-session/src/records.rs @@ -820,6 +820,13 @@ pub struct SessionState { pub browser_user_agent: Option, pub profile_display_name: String, pub login_phase_label: String, + pub read_path_login_request: Option, +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct ReadPathLoginRequestState { + pub generation: u64, + pub operation: String, } impl SessionState { @@ -837,6 +844,12 @@ impl SessionState { readiness: readiness.into(), login_phase: login_phase.into(), browser_user_agent: snapshot.browser_user_agent, + read_path_login_request: snapshot.read_path_login_request.map(|request| { + ReadPathLoginRequestState { + generation: request.generation, + operation: request.operation, + } + }), } } } diff --git a/rust/crates/fire-uniffi-topics/src/lib.rs b/rust/crates/fire-uniffi-topics/src/lib.rs index 130b13fa..fe36c5e7 100644 --- a/rust/crates/fire-uniffi-topics/src/lib.rs +++ b/rust/crates/fire-uniffi-topics/src/lib.rs @@ -5,6 +5,17 @@ use std::sync::Arc; use fire_uniffi_types::{run_on_ffi_runtime, FireUniFfiError, SharedFireCore, TopicListState}; pub mod records; +mod session; +mod ui_records; + +pub use session::{TopicDetailObserver, TopicDetailSessionHandle}; +pub use ui_records::{ + TopicDetailAuthorDisplayState, TopicDetailBoostDisplayState, TopicDetailChromeState, + TopicDetailComposerModelState, TopicDetailLoadErrorState, TopicDetailNoticeState, + TopicDetailOpenRequestState, TopicDetailPhaseState, TopicDetailReplyContextState, + TopicDetailSidecarModelState, TopicDetailUiRowState, TopicDetailUiSnapshotState, + TopicHomeRowCountPatchState, TopicHomeUnreadDecisionState, +}; pub use records::{ LoadMoreTopicPostsQueryState, PollOptionState, PollState, PostActionTypeState, @@ -51,66 +62,6 @@ impl FireTopicsHandle { Ok(response.into()) } - pub async fn fetch_topic_detail_source_snapshot( - &self, - query: TopicDetailSourceQueryState, - ) -> Result { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let response = run_on_ffi_runtime( - "fetch_topic_detail_source_snapshot", - panic_state, - async move { - let base_url = inner.base_url().to_string(); - let snapshot = inner - .fetch_topic_detail_source_snapshot(query.into()) - .await?; - Ok::<_, fire_core::FireCoreError>((base_url, snapshot)) - }, - ) - .await?; - Ok(records::topic_detail_source_snapshot_state_from_model( - response.1, - &response.0, - )) - } - - pub async fn fetch_topic_detail_page( - &self, - query: TopicDetailSourceQueryState, - ) -> Result { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let response = run_on_ffi_runtime("fetch_topic_detail_page", panic_state, async move { - let base_url = inner.base_url().to_string(); - let page = inner.fetch_topic_detail_page(query.into()).await?; - Ok::<_, fire_core::FireCoreError>((base_url, page)) - }) - .await?; - Ok(records::topic_detail_page_state_from_model( - response.1, - &response.0, - )) - } - - pub async fn load_more_topic_posts( - &self, - query: LoadMoreTopicPostsQueryState, - ) -> Result { - let inner = self.shared.core.clone(); - let panic_state = self.shared.panic_state.clone(); - let response = run_on_ffi_runtime("load_more_topic_posts", panic_state, async move { - let base_url = inner.base_url().to_string(); - let outcome = inner.load_more_topic_posts(query.into()).await?; - Ok::<_, fire_core::FireCoreError>((base_url, outcome)) - }) - .await?; - Ok(records::topic_load_more_outcome_state_from_model( - response.1, - &response.0, - )) - } - pub async fn fetch_topic_posts( &self, topic_id: u64, diff --git a/rust/crates/fire-uniffi-topics/src/records.rs b/rust/crates/fire-uniffi-topics/src/records.rs deleted file mode 100644 index 9040eb58..00000000 --- a/rust/crates/fire-uniffi-topics/src/records.rs +++ /dev/null @@ -1,1247 +0,0 @@ -use std::sync::Arc; - -use fire_models::{ - LoadMoreTopicPostsQuery, Poll, PollOption, PostActionType, PostFlagRequest, PostReactionUpdate, - PostUpdateRequest, PrivateMessageCreateRequest, ReactionUser, ReactionUsersGroup, - ResolvedUploadUrl, TopicAiSummary, TopicBody, TopicCreateRequest, TopicDetail, - TopicDetailCreatedBy, TopicDetailMeta, TopicDetailPage, TopicDetailSourceQuery, - TopicDetailSourceSnapshot, TopicHeader, TopicListQuery, TopicLoadMoreOutcome, - TopicLoadMoreStopReason, TopicLoadedRange, TopicPost, TopicPostAuthorMetadata, TopicPostBoost, - TopicPostBoostUser, TopicPostStream, TopicReaction, TopicReplyRequest, TopicReplyToUser, - TopicSourceCursor, TopicTimingEntry, TopicTimingsRequest, TopicTreePresentation, TopicTreeRow, - TopicUpdateRequest, UploadResult, VoteResponse, VotedUser, -}; - -use fire_uniffi_types::{ - intern_presented_handle, RenderDocumentHandle, TopicListKindState, TopicParticipantState, - TopicTagState, -}; - -#[derive(uniffi::Record, Debug, Clone)] -pub struct TopicListQueryState { - pub kind: TopicListKindState, - pub page: Option, - pub topic_ids: Vec, - pub order: Option, - pub ascending: Option, - pub category_slug: Option, - pub category_id: Option, - pub parent_category_slug: Option, - pub tag: Option, - pub additional_tags: Vec, - pub match_all_tags: bool, -} - -impl From for TopicListQueryState { - fn from(value: TopicListQuery) -> Self { - Self { - kind: value.kind.into(), - page: value.page, - topic_ids: value.topic_ids, - order: value.order, - ascending: value.ascending, - category_slug: value.category_slug, - category_id: value.category_id, - parent_category_slug: value.parent_category_slug, - tag: value.tag, - additional_tags: value.additional_tags, - match_all_tags: value.match_all_tags, - } - } -} - -impl From for TopicListQuery { - fn from(value: TopicListQueryState) -> Self { - Self { - kind: value.kind.into(), - page: value.page, - topic_ids: value.topic_ids, - order: value.order, - ascending: value.ascending, - category_slug: value.category_slug, - category_id: value.category_id, - parent_category_slug: value.parent_category_slug, - tag: value.tag, - additional_tags: value.additional_tags, - match_all_tags: value.match_all_tags, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct TopicLoadedRangeState { - pub start_offset: u32, - pub end_offset_exclusive: u32, - pub first_post_id: u64, - pub last_post_id: u64, -} - -impl From for TopicLoadedRangeState { - fn from(value: TopicLoadedRange) -> Self { - Self { - start_offset: value.start_offset, - end_offset_exclusive: value.end_offset_exclusive, - first_post_id: value.first_post_id, - last_post_id: value.last_post_id, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct TopicSourceCursorState { - pub topic_id: u64, - pub session_id: u64, - pub next_stream_offset: u32, - pub last_loaded_post_id: Option, - pub batch_size: u16, -} - -impl From for TopicSourceCursorState { - fn from(value: TopicSourceCursor) -> Self { - Self { - topic_id: value.topic_id, - session_id: value.session_id, - next_stream_offset: value.next_stream_offset, - last_loaded_post_id: value.last_loaded_post_id, - batch_size: value.batch_size, - } - } -} - -impl From for TopicSourceCursor { - fn from(value: TopicSourceCursorState) -> Self { - Self { - topic_id: value.topic_id, - session_id: value.session_id, - next_stream_offset: value.next_stream_offset, - last_loaded_post_id: value.last_loaded_post_id, - batch_size: value.batch_size, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct TopicDetailSourceQueryState { - pub topic_id: u64, - pub target_post_number: Option, - pub allow_suggested_unread_root: bool, - pub track_visit: bool, - pub force_load: bool, - pub initial_batch_size: u16, - pub load_more_batch_size: u16, - pub max_auto_batches_per_gesture: u8, - pub max_auto_posts_per_gesture: u16, -} - -impl From for TopicDetailSourceQuery { - fn from(value: TopicDetailSourceQueryState) -> Self { - Self { - topic_id: value.topic_id, - target_post_number: value.target_post_number, - allow_suggested_unread_root: value.allow_suggested_unread_root, - track_visit: value.track_visit, - force_load: value.force_load, - initial_batch_size: value.initial_batch_size, - load_more_batch_size: value.load_more_batch_size, - max_auto_batches_per_gesture: value.max_auto_batches_per_gesture, - max_auto_posts_per_gesture: value.max_auto_posts_per_gesture, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct TopicDetailSourceSnapshotState { - pub header: TopicHeaderState, - pub body: TopicBodyState, - pub raw_stream_ids: Vec, - pub loaded_posts: Vec, - pub loaded_ranges: Vec, - pub source_cursor: Option, - pub source_exhausted: bool, - pub focused_post_number: Option, -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct LoadMoreTopicPostsQueryState { - pub cursor: TopicSourceCursorState, -} - -impl From for LoadMoreTopicPostsQuery { - fn from(value: LoadMoreTopicPostsQueryState) -> Self { - Self { - cursor: value.cursor.into(), - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct TopicAiSummaryState { - pub summarized_text: String, - pub algorithm: Option, - pub outdated: bool, - pub can_regenerate: bool, - pub new_posts_since_summary: u32, - pub updated_at: Option, -} - -impl From for TopicAiSummaryState { - fn from(value: TopicAiSummary) -> Self { - Self { - summarized_text: value.summarized_text, - algorithm: value.algorithm, - outdated: value.outdated, - can_regenerate: value.can_regenerate, - new_posts_since_summary: value.new_posts_since_summary, - updated_at: value.updated_at, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct TopicReactionState { - pub id: String, - pub kind: Option, - pub count: u32, - pub can_undo: Option, -} - -impl From for TopicReactionState { - fn from(value: TopicReaction) -> Self { - Self { - id: value.id, - kind: value.kind, - count: value.count, - can_undo: value.can_undo, - } - } -} - -impl From for TopicReaction { - fn from(value: TopicReactionState) -> Self { - Self { - id: value.id, - kind: value.kind, - count: value.count, - can_undo: value.can_undo, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct ReactionUserState { - pub id: u64, - pub username: String, - pub name: Option, - pub avatar_template: Option, -} - -impl From for ReactionUserState { - fn from(value: ReactionUser) -> Self { - Self { - id: value.id, - username: value.username, - name: value.name, - avatar_template: value.avatar_template, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct ReactionUsersGroupState { - pub id: String, - pub count: u32, - pub users: Vec, -} - -impl From for ReactionUsersGroupState { - fn from(value: ReactionUsersGroup) -> Self { - Self { - id: value.id, - count: value.count, - users: value.users.into_iter().map(Into::into).collect(), - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct PollOptionState { - pub id: String, - pub html: String, - pub plain_text: String, - pub votes: u32, -} - -impl From for PollOptionState { - fn from(value: PollOption) -> Self { - Self { - id: value.id, - html: value.html, - plain_text: value.plain_text, - votes: value.votes, - } - } -} - -impl From for PollOption { - fn from(value: PollOptionState) -> Self { - Self { - id: value.id, - html: value.html, - plain_text: value.plain_text, - votes: value.votes, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct PollState { - pub id: u64, - pub name: String, - pub kind: String, - pub status: String, - pub results: String, - pub options: Vec, - pub voters: u32, - pub user_votes: Vec, -} - -impl From for PollState { - fn from(value: Poll) -> Self { - Self { - id: value.id, - name: value.name, - kind: value.kind, - status: value.status, - results: value.results, - options: value.options.into_iter().map(Into::into).collect(), - voters: value.voters, - user_votes: value.user_votes, - } - } -} - -impl From for Poll { - fn from(value: PollState) -> Self { - Self { - id: value.id, - name: value.name, - kind: value.kind, - status: value.status, - results: value.results, - options: value.options.into_iter().map(Into::into).collect(), - voters: value.voters, - user_votes: value.user_votes, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct TopicReplyRequestState { - pub topic_id: u64, - pub raw: String, - pub reply_to_post_number: Option, -} - -impl From for TopicReplyRequest { - fn from(value: TopicReplyRequestState) -> Self { - Self { - topic_id: value.topic_id, - raw: value.raw, - reply_to_post_number: value.reply_to_post_number, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct TopicCreateRequestState { - pub title: String, - pub raw: String, - pub category_id: u64, - pub tags: Vec, -} - -impl From for TopicCreateRequest { - fn from(value: TopicCreateRequestState) -> Self { - Self { - title: value.title, - raw: value.raw, - category_id: value.category_id, - tags: value.tags, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct PrivateMessageCreateRequestState { - pub title: String, - pub raw: String, - pub target_recipients: Vec, -} - -impl From for PrivateMessageCreateRequest { - fn from(value: PrivateMessageCreateRequestState) -> Self { - Self { - title: value.title, - raw: value.raw, - target_recipients: value.target_recipients, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct TopicUpdateRequestState { - pub topic_id: u64, - pub title: String, - pub category_id: u64, - pub tags: Vec, -} - -impl From for TopicUpdateRequest { - fn from(value: TopicUpdateRequestState) -> Self { - Self { - topic_id: value.topic_id, - title: value.title, - category_id: value.category_id, - tags: value.tags, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct PostUpdateRequestState { - pub post_id: u64, - pub raw: String, - pub edit_reason: Option, -} - -impl From for PostUpdateRequest { - fn from(value: PostUpdateRequestState) -> Self { - Self { - post_id: value.post_id, - raw: value.raw, - edit_reason: value.edit_reason, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct PostFlagRequestState { - pub post_id: u64, - pub flag_type_id: u32, - pub message: Option, -} - -impl From for PostFlagRequest { - fn from(value: PostFlagRequestState) -> Self { - Self { - post_id: value.post_id, - flag_type_id: value.flag_type_id, - message: value.message, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct PostActionTypeState { - pub id: u32, - pub name_key: String, - pub name: String, - pub description: String, - pub short_description: Option, - pub is_flag: bool, - pub require_message: bool, - pub enabled: bool, - pub position: i32, - pub applies_to: Vec, -} - -impl From for PostActionTypeState { - fn from(value: PostActionType) -> Self { - Self { - id: value.id, - name_key: value.name_key, - name: value.name, - description: value.description, - short_description: value.short_description, - is_flag: value.is_flag, - require_message: value.require_message, - enabled: value.enabled, - position: value.position, - applies_to: value.applies_to, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct UploadImageRequestState { - pub file_name: String, - pub mime_type: Option, - pub bytes: Vec, -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct UploadResultState { - pub id: Option, - pub short_url: String, - pub url: Option, - pub original_filename: Option, - pub width: Option, - pub height: Option, - pub thumbnail_width: Option, - pub thumbnail_height: Option, -} - -impl From for UploadResultState { - fn from(value: UploadResult) -> Self { - Self { - id: value.id, - short_url: value.short_url, - url: value.url, - original_filename: value.original_filename, - width: value.width, - height: value.height, - thumbnail_width: value.thumbnail_width, - thumbnail_height: value.thumbnail_height, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct ResolvedUploadUrlState { - pub short_url: String, - pub short_path: Option, - pub url: Option, -} - -impl From for ResolvedUploadUrlState { - fn from(value: ResolvedUploadUrl) -> Self { - Self { - short_url: value.short_url, - short_path: value.short_path, - url: value.url, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct TopicTimingEntryState { - pub post_number: u32, - pub milliseconds: u32, -} - -impl From for TopicTimingEntry { - fn from(value: TopicTimingEntryState) -> Self { - Self { - post_number: value.post_number, - milliseconds: value.milliseconds, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct TopicTimingsRequestState { - pub topic_id: u64, - pub topic_time_ms: u32, - pub timings: Vec, -} - -impl From for TopicTimingsRequest { - fn from(value: TopicTimingsRequestState) -> Self { - Self { - topic_id: value.topic_id, - topic_time_ms: value.topic_time_ms, - timings: value.timings.into_iter().map(Into::into).collect(), - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct PostReactionUpdateState { - pub reactions: Vec, - pub current_user_reaction: Option, -} - -impl From for PostReactionUpdateState { - fn from(value: PostReactionUpdate) -> Self { - Self { - reactions: value.reactions.into_iter().map(Into::into).collect(), - current_user_reaction: value.current_user_reaction.map(Into::into), - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct TopicReplyToUserState { - pub username: String, - pub name: Option, - pub avatar_template: Option, -} - -impl From for TopicReplyToUserState { - fn from(value: TopicReplyToUser) -> Self { - Self { - username: value.username, - name: value.name, - avatar_template: value.avatar_template, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct TopicPostAuthorMetadataState { - pub user_id: Option, - pub user_title: Option, - pub primary_group_name: Option, - pub flair_url: Option, - pub flair_name: Option, - pub flair_bg_color: Option, - pub flair_color: Option, - pub flair_group_id: Option, - pub moderator: bool, - pub admin: bool, - pub group_moderator: bool, - pub user_status_emoji: Option, - pub user_status_description: Option, -} - -impl From for TopicPostAuthorMetadataState { - fn from(value: TopicPostAuthorMetadata) -> Self { - Self { - user_id: value.user_id, - user_title: value.user_title, - primary_group_name: value.primary_group_name, - flair_url: value.flair_url, - flair_name: value.flair_name, - flair_bg_color: value.flair_bg_color, - flair_color: value.flair_color, - flair_group_id: value.flair_group_id, - moderator: value.moderator, - admin: value.admin, - group_moderator: value.group_moderator, - user_status_emoji: value.user_status_emoji, - user_status_description: value.user_status_description, - } - } -} - -impl From for TopicPostAuthorMetadata { - fn from(value: TopicPostAuthorMetadataState) -> Self { - Self { - user_id: value.user_id, - user_title: value.user_title, - primary_group_name: value.primary_group_name, - flair_url: value.flair_url, - flair_name: value.flair_name, - flair_bg_color: value.flair_bg_color, - flair_color: value.flair_color, - flair_group_id: value.flair_group_id, - moderator: value.moderator, - admin: value.admin, - group_moderator: value.group_moderator, - user_status_emoji: value.user_status_emoji, - user_status_description: value.user_status_description, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct TopicPostBoostUserState { - pub id: u64, - pub username: String, - pub name: Option, - pub avatar_template: Option, -} - -impl From for TopicPostBoostUserState { - fn from(value: TopicPostBoostUser) -> Self { - Self { - id: value.id, - username: value.username, - name: value.name, - avatar_template: value.avatar_template, - } - } -} - -impl From for TopicPostBoostUser { - fn from(value: TopicPostBoostUserState) -> Self { - Self { - id: value.id, - username: value.username, - name: value.name, - avatar_template: value.avatar_template, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct TopicPostBoostState { - pub id: u64, - pub presentation: Option>, - pub display_text: String, - pub user: TopicPostBoostUserState, - pub can_delete: bool, - pub can_flag: bool, - pub user_flag_status: Option, - pub available_flags: Vec, -} - -pub(crate) fn topic_post_boost_state_from_model( - value: TopicPostBoost, - _base_url: &str, -) -> TopicPostBoostState { - let presentation = handle_from_presented(value.presented.arc()); - TopicPostBoostState { - id: value.id, - presentation, - display_text: value.display_text, - user: value.user.into(), - can_delete: value.can_delete, - can_flag: value.can_flag, - user_flag_status: value.user_flag_status, - available_flags: value.available_flags, - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct TopicPostState { - pub id: u64, - pub username: String, - pub name: Option, - pub avatar_template: Option, - pub author_metadata: TopicPostAuthorMetadataState, - pub presentation: Option>, - pub raw: Option, - pub post_number: u32, - pub post_type: i32, - pub created_at: Option, - pub updated_at: Option, - pub like_count: u32, - pub reply_count: u32, - pub reply_to_post_number: Option, - pub reply_to_user: Option, - pub bookmarked: bool, - pub bookmark_id: Option, - pub bookmark_name: Option, - pub bookmark_reminder_at: Option, - pub reactions: Vec, - pub current_user_reaction: Option, - pub boosts: Vec, - pub can_boost: bool, - pub polls: Vec, - pub accepted_answer: bool, - pub can_accept_answer: bool, - pub can_unaccept_answer: bool, - pub can_edit: bool, - pub can_delete: bool, - pub can_recover: bool, - pub hidden: bool, -} - -fn handle_from_presented( - presented: Option>, -) -> Option> { - presented.map(intern_presented_handle) -} - -pub(crate) fn topic_post_state_from_model(value: TopicPost, base_url: &str) -> TopicPostState { - topic_post_state_from_model_ex(value, base_url, false) -} - -pub(crate) fn topic_post_state_from_model_with_raw( - value: TopicPost, - base_url: &str, -) -> TopicPostState { - topic_post_state_from_model_ex(value, base_url, true) -} - -fn topic_post_state_from_model_ex( - value: TopicPost, - base_url: &str, - include_raw: bool, -) -> TopicPostState { - let presentation = handle_from_presented(value.presented.arc()); - TopicPostState { - id: value.id, - username: value.username, - name: value.name, - avatar_template: value.avatar_template, - author_metadata: value.author_metadata.into(), - presentation, - raw: include_raw.then(|| value.raw).flatten(), - post_number: value.post_number, - post_type: value.post_type, - created_at: value.created_at, - updated_at: value.updated_at, - like_count: value.like_count, - reply_count: value.reply_count, - reply_to_post_number: value.reply_to_post_number, - reply_to_user: value.reply_to_user.map(Into::into), - bookmarked: value.bookmarked, - bookmark_id: value.bookmark_id, - bookmark_name: value.bookmark_name, - bookmark_reminder_at: value.bookmark_reminder_at, - reactions: value.reactions.into_iter().map(Into::into).collect(), - current_user_reaction: value.current_user_reaction.map(Into::into), - boosts: value - .boosts - .into_iter() - .map(|boost| topic_post_boost_state_from_model(boost, base_url)) - .collect(), - can_boost: value.can_boost, - polls: value.polls.into_iter().map(Into::into).collect(), - accepted_answer: value.accepted_answer, - can_accept_answer: value.can_accept_answer, - can_unaccept_answer: value.can_unaccept_answer, - can_edit: value.can_edit, - can_delete: value.can_delete, - can_recover: value.can_recover, - hidden: value.hidden, - } -} - -impl From for TopicReplyToUser { - fn from(value: TopicReplyToUserState) -> Self { - Self { - username: value.username, - name: value.name, - avatar_template: value.avatar_template, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct TopicPostStreamState { - pub posts: Vec, - pub stream: Vec, -} - -fn topic_post_stream_state_from_model( - value: TopicPostStream, - base_url: &str, -) -> TopicPostStreamState { - TopicPostStreamState { - posts: value - .posts - .into_iter() - .map(|post| topic_post_state_from_model(post, base_url)) - .collect(), - stream: value.stream, - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct TopicDetailCreatedByState { - pub id: u64, - pub username: String, - pub avatar_template: Option, -} - -impl From for TopicDetailCreatedByState { - fn from(value: TopicDetailCreatedBy) -> Self { - Self { - id: value.id, - username: value.username, - avatar_template: value.avatar_template, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct TopicDetailMetaState { - pub notification_level: Option, - pub can_edit: bool, - pub created_by: Option, - pub participants: Vec, -} - -impl From for TopicDetailMetaState { - fn from(value: TopicDetailMeta) -> Self { - Self { - notification_level: value.notification_level, - can_edit: value.can_edit, - created_by: value.created_by.map(Into::into), - participants: value.participants.into_iter().map(Into::into).collect(), - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct TopicHeaderState { - pub topic_id: u64, - pub message_bus_last_id: Option, - pub title: String, - pub slug: String, - pub posts_count: u32, - pub reply_count: u32, - pub category_id: Option, - pub tags: Vec, - pub views: u32, - pub like_count: u32, - pub created_at: Option, - pub highest_post_number: u32, - pub last_read_post_number: Option, - pub bookmarks: Vec, - pub bookmarked: bool, - pub bookmark_id: Option, - pub bookmark_name: Option, - pub bookmark_reminder_at: Option, - pub accepted_answer: bool, - pub has_accepted_answer: bool, - pub can_vote: bool, - pub vote_count: i32, - pub user_voted: bool, - pub summarizable: bool, - pub has_cached_summary: bool, - pub has_summary: bool, - pub archetype: Option, - pub details: TopicDetailMetaState, -} - -impl From for TopicHeaderState { - fn from(value: TopicHeader) -> Self { - Self { - topic_id: value.topic_id, - message_bus_last_id: value.message_bus_last_id, - title: value.title, - slug: value.slug, - posts_count: value.posts_count, - reply_count: value.reply_count, - category_id: value.category_id, - tags: value.tags.into_iter().map(Into::into).collect(), - views: value.views, - like_count: value.like_count, - created_at: value.created_at, - highest_post_number: value.highest_post_number, - last_read_post_number: value.last_read_post_number, - bookmarks: value.bookmarks, - bookmarked: value.bookmarked, - bookmark_id: value.bookmark_id, - bookmark_name: value.bookmark_name, - bookmark_reminder_at: value.bookmark_reminder_at, - accepted_answer: value.accepted_answer, - has_accepted_answer: value.has_accepted_answer, - can_vote: value.can_vote, - vote_count: value.vote_count, - user_voted: value.user_voted, - summarizable: value.summarizable, - has_cached_summary: value.has_cached_summary, - has_summary: value.has_summary, - archetype: value.archetype, - details: value.details.into(), - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct TopicBodyState { - pub post: TopicPostState, -} - -fn topic_body_state_from_model(value: TopicBody, base_url: &str) -> TopicBodyState { - TopicBodyState { - post: topic_post_state_from_model(value.post, base_url), - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct TopicTreeRowState { - pub post_id: u64, - pub post_number: u32, - pub root_post_number: u32, - pub parent_post_number: Option, - pub depth: u16, - pub preorder_index: u32, - pub has_children: bool, - pub descendant_count: u32, - pub sibling_index: u16, - pub is_last_sibling: bool, -} - -fn topic_tree_row_state_from_model(value: TopicTreeRow) -> TopicTreeRowState { - TopicTreeRowState { - post_id: value.post_id, - post_number: value.post_number, - root_post_number: value.root_post_number, - parent_post_number: value.parent_post_number, - depth: value.depth, - preorder_index: value.preorder_index, - has_children: value.has_children, - descendant_count: value.descendant_count, - sibling_index: value.sibling_index, - is_last_sibling: value.is_last_sibling, - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct TopicTreePresentationState { - pub original_post_id: u64, - pub original_post_number: u32, - pub reply_rows: Vec, - pub total_loaded_post_count: u32, - pub visible_root_post_numbers: Vec, - pub first_unread_root_post_number: Option, - pub gained_new_root_progress: bool, -} - -pub(crate) fn topic_tree_presentation_state_from_model( - value: TopicTreePresentation, -) -> TopicTreePresentationState { - TopicTreePresentationState { - original_post_id: value.original_post_id, - original_post_number: value.original_post_number, - reply_rows: value - .reply_rows - .into_iter() - .map(topic_tree_row_state_from_model) - .collect(), - total_loaded_post_count: value.total_loaded_post_count, - visible_root_post_numbers: value.visible_root_post_numbers, - first_unread_root_post_number: value.first_unread_root_post_number, - gained_new_root_progress: value.gained_new_root_progress, - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct TopicDetailPageState { - pub source_snapshot: TopicDetailSourceSnapshotState, - pub tree_presentation: TopicTreePresentationState, -} - -pub fn topic_detail_page_state_from_model( - value: TopicDetailPage, - base_url: &str, -) -> TopicDetailPageState { - TopicDetailPageState { - source_snapshot: topic_detail_source_snapshot_state_from_model( - value.source_snapshot, - base_url, - ), - tree_presentation: topic_tree_presentation_state_from_model(value.tree_presentation), - } -} - -pub fn topic_detail_source_snapshot_state_from_model( - value: TopicDetailSourceSnapshot, - base_url: &str, -) -> TopicDetailSourceSnapshotState { - TopicDetailSourceSnapshotState { - header: value.header.into(), - body: topic_body_state_from_model(value.body, base_url), - raw_stream_ids: value.raw_stream_ids, - loaded_posts: value - .loaded_posts - .into_iter() - .map(|post| topic_post_state_from_model(post, base_url)) - .collect(), - loaded_ranges: value.loaded_ranges.into_iter().map(Into::into).collect(), - source_cursor: value.source_cursor.map(Into::into), - source_exhausted: value.source_exhausted, - focused_post_number: value.focused_post_number, - } -} - -#[derive(uniffi::Enum, Debug, Clone, Copy)] -pub enum TopicLoadMoreStopReasonState { - GainedVisibleRootProgress, - SourceExhausted, - MaxAutoBatchesReached, - MaxAutoPostsReached, - RequestFailed, -} - -impl From for TopicLoadMoreStopReasonState { - fn from(value: TopicLoadMoreStopReason) -> Self { - match value { - TopicLoadMoreStopReason::GainedVisibleRootProgress => Self::GainedVisibleRootProgress, - TopicLoadMoreStopReason::SourceExhausted => Self::SourceExhausted, - TopicLoadMoreStopReason::MaxAutoBatchesReached => Self::MaxAutoBatchesReached, - TopicLoadMoreStopReason::MaxAutoPostsReached => Self::MaxAutoPostsReached, - TopicLoadMoreStopReason::RequestFailed => Self::RequestFailed, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct TopicLoadMoreOutcomeState { - pub appended_posts: Vec, - pub loaded_ranges: Vec, - pub source_cursor: Option, - pub source_exhausted: bool, - pub tree_presentation: TopicTreePresentationState, - pub chained_batches: u8, - pub chained_posts: u16, - pub stop_reason: TopicLoadMoreStopReasonState, -} - -pub fn topic_load_more_outcome_state_from_model( - value: TopicLoadMoreOutcome, - base_url: &str, -) -> TopicLoadMoreOutcomeState { - TopicLoadMoreOutcomeState { - appended_posts: value - .appended_posts - .into_iter() - .map(|post| topic_post_state_from_model(post, base_url)) - .collect(), - loaded_ranges: value - .source_snapshot - .loaded_ranges - .into_iter() - .map(Into::into) - .collect(), - source_cursor: value.source_snapshot.source_cursor.map(Into::into), - source_exhausted: value.source_snapshot.source_exhausted, - tree_presentation: topic_tree_presentation_state_from_model(value.tree_presentation), - chained_batches: value.chained_batches, - chained_posts: value.chained_posts, - stop_reason: value.stop_reason.into(), - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct TopicDetailState { - pub id: u64, - pub message_bus_last_id: Option, - pub title: String, - pub slug: String, - pub posts_count: u32, - pub reply_count: u32, - pub category_id: Option, - pub tags: Vec, - pub views: u32, - pub like_count: u32, - pub created_at: Option, - pub highest_post_number: u32, - pub last_read_post_number: Option, - pub bookmarks: Vec, - pub bookmarked: bool, - pub bookmark_id: Option, - pub bookmark_name: Option, - pub bookmark_reminder_at: Option, - pub accepted_answer: bool, - pub has_accepted_answer: bool, - pub can_vote: bool, - pub vote_count: i32, - pub user_voted: bool, - pub summarizable: bool, - pub has_cached_summary: bool, - pub has_summary: bool, - pub archetype: Option, - pub post_stream: TopicPostStreamState, - pub details: TopicDetailMetaState, -} - -pub fn topic_detail_state_from_model(value: TopicDetail, base_url: &str) -> TopicDetailState { - let reply_count = value.reply_count(); - TopicDetailState { - id: value.id, - message_bus_last_id: value.message_bus_last_id, - title: value.title, - slug: value.slug, - posts_count: value.posts_count, - reply_count, - category_id: value.category_id, - tags: value.tags.into_iter().map(Into::into).collect(), - views: value.views, - like_count: value.like_count, - created_at: value.created_at, - highest_post_number: value.highest_post_number, - last_read_post_number: value.last_read_post_number, - bookmarks: value.bookmarks, - bookmarked: value.bookmarked, - bookmark_id: value.bookmark_id, - bookmark_name: value.bookmark_name, - bookmark_reminder_at: value.bookmark_reminder_at, - accepted_answer: value.accepted_answer, - has_accepted_answer: value.has_accepted_answer, - can_vote: value.can_vote, - vote_count: value.vote_count, - user_voted: value.user_voted, - summarizable: value.summarizable, - has_cached_summary: value.has_cached_summary, - has_summary: value.has_summary, - archetype: value.archetype, - post_stream: topic_post_stream_state_from_model(value.post_stream, base_url), - details: value.details.into(), - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct VotedUserState { - pub id: u64, - pub username: String, - pub name: Option, - pub avatar_template: Option, -} - -impl From for VotedUserState { - fn from(value: VotedUser) -> Self { - Self { - id: value.id, - username: value.username, - name: value.name, - avatar_template: value.avatar_template, - } - } -} - -#[derive(uniffi::Record, Debug, Clone)] -pub struct VoteResponseState { - pub can_vote: bool, - pub vote_limit: u32, - pub vote_count: i32, - pub votes_left: i32, - pub alert: bool, - pub who_voted: Vec, -} - -impl From for VoteResponseState { - fn from(value: VoteResponse) -> Self { - Self { - can_vote: value.can_vote, - vote_limit: value.vote_limit, - vote_count: value.vote_count, - votes_left: value.votes_left, - alert: value.alert, - who_voted: value.who_voted.into_iter().map(Into::into).collect(), - } - } -} - -#[cfg(test)] -mod tests { - use fire_models::{TopicDetailSourceSnapshot, TopicLoadMoreOutcome, TopicPost}; - - use super::topic_load_more_outcome_state_from_model; - - #[test] - fn load_more_ffi_sends_only_appended_posts() { - let appended = TopicPost { - id: 9, - post_number: 9, - ..TopicPost::default() - }; - let existing = TopicPost { - id: 1, - post_number: 1, - ..TopicPost::default() - }; - let state = topic_load_more_outcome_state_from_model( - TopicLoadMoreOutcome { - source_snapshot: TopicDetailSourceSnapshot { - loaded_posts: vec![existing, appended.clone()], - source_exhausted: true, - ..TopicDetailSourceSnapshot::default() - }, - appended_posts: vec![appended], - ..TopicLoadMoreOutcome::default() - }, - "https://linux.do", - ); - assert_eq!(state.appended_posts.len(), 1); - assert_eq!(state.appended_posts[0].id, 9); - assert!(state.source_exhausted); - assert!(state.source_cursor.is_none()); - } -} diff --git a/rust/crates/fire-uniffi-topics/src/records/detail.rs b/rust/crates/fire-uniffi-topics/src/records/detail.rs new file mode 100644 index 00000000..fd5a5a5b --- /dev/null +++ b/rust/crates/fire-uniffi-topics/src/records/detail.rs @@ -0,0 +1,451 @@ +use std::sync::Arc; + +use fire_models::{ + LoadMoreTopicPostsQuery, Poll, PollOption, PostActionType, PostFlagRequest, PostReactionUpdate, + PostUpdateRequest, PrivateMessageCreateRequest, ReactionUser, ReactionUsersGroup, + ResolvedUploadUrl, TopicAiSummary, TopicBody, TopicCreateRequest, TopicDetail, + TopicDetailCreatedBy, TopicDetailMeta, TopicDetailPage, TopicDetailSourceQuery, + TopicDetailSourceSnapshot, TopicHeader, TopicListQuery, TopicLoadMoreOutcome, + TopicLoadMoreStopReason, TopicLoadedRange, TopicPost, TopicPostAuthorMetadata, TopicPostBoost, + TopicPostBoostUser, TopicPostStream, TopicReaction, TopicReplyRequest, TopicReplyToUser, + TopicSourceCursor, TopicTimingEntry, TopicTimingsRequest, TopicTreePresentation, TopicTreeRow, + TopicUpdateRequest, UploadResult, VoteResponse, VotedUser, +}; + +use fire_uniffi_types::{ + intern_presented_handle, RenderDocumentHandle, TopicListKindState, TopicParticipantState, + TopicTagState, +}; +use super::list::{TopicLoadedRangeState, TopicSourceCursorState}; +use super::post::{ + topic_post_state_from_model, topic_post_stream_state_from_model, TopicPostState, + TopicPostStreamState, +}; + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicDetailSourceQueryState { + pub topic_id: u64, + pub target_post_number: Option, + pub allow_suggested_unread_root: bool, + pub track_visit: bool, + pub force_load: bool, + pub initial_batch_size: u16, + pub load_more_batch_size: u16, + pub max_auto_batches_per_gesture: u8, + pub max_auto_posts_per_gesture: u16, +} + +impl From for TopicDetailSourceQuery { + fn from(value: TopicDetailSourceQueryState) -> Self { + Self { + topic_id: value.topic_id, + target_post_number: value.target_post_number, + allow_suggested_unread_root: value.allow_suggested_unread_root, + track_visit: value.track_visit, + force_load: value.force_load, + initial_batch_size: value.initial_batch_size, + load_more_batch_size: value.load_more_batch_size, + max_auto_batches_per_gesture: value.max_auto_batches_per_gesture, + max_auto_posts_per_gesture: value.max_auto_posts_per_gesture, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicDetailSourceSnapshotState { + pub header: TopicHeaderState, + pub body: TopicBodyState, + pub raw_stream_ids: Vec, + pub loaded_posts: Vec, + pub loaded_ranges: Vec, + pub source_cursor: Option, + pub source_exhausted: bool, + pub focused_post_number: Option, +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct LoadMoreTopicPostsQueryState { + pub cursor: TopicSourceCursorState, +} + +impl From for LoadMoreTopicPostsQuery { + fn from(value: LoadMoreTopicPostsQueryState) -> Self { + Self { + cursor: value.cursor.into(), + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicDetailCreatedByState { + pub id: u64, + pub username: String, + pub avatar_template: Option, +} + +impl From for TopicDetailCreatedByState { + fn from(value: TopicDetailCreatedBy) -> Self { + Self { + id: value.id, + username: value.username, + avatar_template: value.avatar_template, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicDetailMetaState { + pub notification_level: Option, + pub can_edit: bool, + pub created_by: Option, + pub participants: Vec, +} + +impl From for TopicDetailMetaState { + fn from(value: TopicDetailMeta) -> Self { + Self { + notification_level: value.notification_level, + can_edit: value.can_edit, + created_by: value.created_by.map(Into::into), + participants: value.participants.into_iter().map(Into::into).collect(), + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicHeaderState { + pub topic_id: u64, + pub message_bus_last_id: Option, + pub title: String, + pub slug: String, + pub posts_count: u32, + pub reply_count: u32, + pub category_id: Option, + pub tags: Vec, + pub views: u32, + pub like_count: u32, + pub created_at: Option, + pub highest_post_number: u32, + pub last_read_post_number: Option, + pub bookmarks: Vec, + pub bookmarked: bool, + pub bookmark_id: Option, + pub bookmark_name: Option, + pub bookmark_reminder_at: Option, + pub accepted_answer: bool, + pub has_accepted_answer: bool, + pub can_vote: bool, + pub vote_count: i32, + pub user_voted: bool, + pub summarizable: bool, + pub has_cached_summary: bool, + pub has_summary: bool, + pub archetype: Option, + pub details: TopicDetailMetaState, +} + +impl From for TopicHeaderState { + fn from(value: TopicHeader) -> Self { + Self { + topic_id: value.topic_id, + message_bus_last_id: value.message_bus_last_id, + title: value.title, + slug: value.slug, + posts_count: value.posts_count, + reply_count: value.reply_count, + category_id: value.category_id, + tags: value.tags.into_iter().map(Into::into).collect(), + views: value.views, + like_count: value.like_count, + created_at: value.created_at, + highest_post_number: value.highest_post_number, + last_read_post_number: value.last_read_post_number, + bookmarks: value.bookmarks, + bookmarked: value.bookmarked, + bookmark_id: value.bookmark_id, + bookmark_name: value.bookmark_name, + bookmark_reminder_at: value.bookmark_reminder_at, + accepted_answer: value.accepted_answer, + has_accepted_answer: value.has_accepted_answer, + can_vote: value.can_vote, + vote_count: value.vote_count, + user_voted: value.user_voted, + summarizable: value.summarizable, + has_cached_summary: value.has_cached_summary, + has_summary: value.has_summary, + archetype: value.archetype, + details: value.details.into(), + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicBodyState { + pub post: TopicPostState, +} + +fn topic_body_state_from_model(value: TopicBody, base_url: &str) -> TopicBodyState { + TopicBodyState { + post: topic_post_state_from_model(value.post, base_url), + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicTreeRowState { + pub post_id: u64, + pub post_number: u32, + pub root_post_number: u32, + pub parent_post_number: Option, + pub depth: u16, + pub preorder_index: u32, + pub has_children: bool, + pub descendant_count: u32, + pub sibling_index: u16, + pub is_last_sibling: bool, +} + +fn topic_tree_row_state_from_model(value: TopicTreeRow) -> TopicTreeRowState { + TopicTreeRowState { + post_id: value.post_id, + post_number: value.post_number, + root_post_number: value.root_post_number, + parent_post_number: value.parent_post_number, + depth: value.depth, + preorder_index: value.preorder_index, + has_children: value.has_children, + descendant_count: value.descendant_count, + sibling_index: value.sibling_index, + is_last_sibling: value.is_last_sibling, + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicTreePresentationState { + pub original_post_id: u64, + pub original_post_number: u32, + pub reply_rows: Vec, + pub total_loaded_post_count: u32, + pub visible_root_post_numbers: Vec, + pub first_unread_root_post_number: Option, + pub gained_new_root_progress: bool, +} + +pub(crate) fn topic_tree_presentation_state_from_model( + value: TopicTreePresentation, +) -> TopicTreePresentationState { + TopicTreePresentationState { + original_post_id: value.original_post_id, + original_post_number: value.original_post_number, + reply_rows: value + .reply_rows + .into_iter() + .map(topic_tree_row_state_from_model) + .collect(), + total_loaded_post_count: value.total_loaded_post_count, + visible_root_post_numbers: value.visible_root_post_numbers, + first_unread_root_post_number: value.first_unread_root_post_number, + gained_new_root_progress: value.gained_new_root_progress, + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicDetailPageState { + pub source_snapshot: TopicDetailSourceSnapshotState, + pub tree_presentation: TopicTreePresentationState, +} + +pub fn topic_detail_page_state_from_model( + value: TopicDetailPage, + base_url: &str, +) -> TopicDetailPageState { + TopicDetailPageState { + source_snapshot: topic_detail_source_snapshot_state_from_model( + value.source_snapshot, + base_url, + ), + tree_presentation: topic_tree_presentation_state_from_model(value.tree_presentation), + } +} + +pub fn topic_detail_source_snapshot_state_from_model( + value: TopicDetailSourceSnapshot, + base_url: &str, +) -> TopicDetailSourceSnapshotState { + TopicDetailSourceSnapshotState { + header: value.header.into(), + body: topic_body_state_from_model(value.body, base_url), + raw_stream_ids: value.raw_stream_ids, + loaded_posts: value + .loaded_posts + .into_iter() + .map(|post| topic_post_state_from_model(post, base_url)) + .collect(), + loaded_ranges: value.loaded_ranges.into_iter().map(Into::into).collect(), + source_cursor: value.source_cursor.map(Into::into), + source_exhausted: value.source_exhausted, + focused_post_number: value.focused_post_number, + } +} + +#[derive(uniffi::Enum, Debug, Clone, Copy)] +pub enum TopicLoadMoreStopReasonState { + GainedVisibleRootProgress, + SourceExhausted, + MaxAutoBatchesReached, + MaxAutoPostsReached, + RequestFailed, +} + +impl From for TopicLoadMoreStopReasonState { + fn from(value: TopicLoadMoreStopReason) -> Self { + match value { + TopicLoadMoreStopReason::GainedVisibleRootProgress => Self::GainedVisibleRootProgress, + TopicLoadMoreStopReason::SourceExhausted => Self::SourceExhausted, + TopicLoadMoreStopReason::MaxAutoBatchesReached => Self::MaxAutoBatchesReached, + TopicLoadMoreStopReason::MaxAutoPostsReached => Self::MaxAutoPostsReached, + TopicLoadMoreStopReason::RequestFailed => Self::RequestFailed, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicLoadMoreOutcomeState { + pub appended_posts: Vec, + pub loaded_ranges: Vec, + pub source_cursor: Option, + pub source_exhausted: bool, + pub tree_presentation: TopicTreePresentationState, + pub chained_batches: u8, + pub chained_posts: u16, + pub stop_reason: TopicLoadMoreStopReasonState, +} + +pub fn topic_load_more_outcome_state_from_model( + value: TopicLoadMoreOutcome, + base_url: &str, +) -> TopicLoadMoreOutcomeState { + TopicLoadMoreOutcomeState { + appended_posts: value + .appended_posts + .into_iter() + .map(|post| topic_post_state_from_model(post, base_url)) + .collect(), + loaded_ranges: value + .source_snapshot + .loaded_ranges + .into_iter() + .map(Into::into) + .collect(), + source_cursor: value.source_snapshot.source_cursor.map(Into::into), + source_exhausted: value.source_snapshot.source_exhausted, + tree_presentation: topic_tree_presentation_state_from_model(value.tree_presentation), + chained_batches: value.chained_batches, + chained_posts: value.chained_posts, + stop_reason: value.stop_reason.into(), + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicDetailState { + pub id: u64, + pub message_bus_last_id: Option, + pub title: String, + pub slug: String, + pub posts_count: u32, + pub reply_count: u32, + pub category_id: Option, + pub tags: Vec, + pub views: u32, + pub like_count: u32, + pub created_at: Option, + pub highest_post_number: u32, + pub last_read_post_number: Option, + pub bookmarks: Vec, + pub bookmarked: bool, + pub bookmark_id: Option, + pub bookmark_name: Option, + pub bookmark_reminder_at: Option, + pub accepted_answer: bool, + pub has_accepted_answer: bool, + pub can_vote: bool, + pub vote_count: i32, + pub user_voted: bool, + pub summarizable: bool, + pub has_cached_summary: bool, + pub has_summary: bool, + pub archetype: Option, + pub post_stream: TopicPostStreamState, + pub details: TopicDetailMetaState, +} + +pub fn topic_detail_state_from_model(value: TopicDetail, base_url: &str) -> TopicDetailState { + let reply_count = value.reply_count(); + TopicDetailState { + id: value.id, + message_bus_last_id: value.message_bus_last_id, + title: value.title, + slug: value.slug, + posts_count: value.posts_count, + reply_count, + category_id: value.category_id, + tags: value.tags.into_iter().map(Into::into).collect(), + views: value.views, + like_count: value.like_count, + created_at: value.created_at, + highest_post_number: value.highest_post_number, + last_read_post_number: value.last_read_post_number, + bookmarks: value.bookmarks, + bookmarked: value.bookmarked, + bookmark_id: value.bookmark_id, + bookmark_name: value.bookmark_name, + bookmark_reminder_at: value.bookmark_reminder_at, + accepted_answer: value.accepted_answer, + has_accepted_answer: value.has_accepted_answer, + can_vote: value.can_vote, + vote_count: value.vote_count, + user_voted: value.user_voted, + summarizable: value.summarizable, + has_cached_summary: value.has_cached_summary, + has_summary: value.has_summary, + archetype: value.archetype, + post_stream: topic_post_stream_state_from_model(value.post_stream, base_url), + details: value.details.into(), + } +} + +#[cfg(test)] +mod tests { + use fire_models::{TopicDetailSourceSnapshot, TopicLoadMoreOutcome, TopicPost}; + + use super::topic_load_more_outcome_state_from_model; + + #[test] + fn load_more_ffi_sends_only_appended_posts() { + let appended = TopicPost { + id: 9, + post_number: 9, + ..TopicPost::default() + }; + let existing = TopicPost { + id: 1, + post_number: 1, + ..TopicPost::default() + }; + let state = topic_load_more_outcome_state_from_model( + TopicLoadMoreOutcome { + source_snapshot: TopicDetailSourceSnapshot { + loaded_posts: vec![existing, appended.clone()], + source_exhausted: true, + ..TopicDetailSourceSnapshot::default() + }, + appended_posts: vec![appended], + ..TopicLoadMoreOutcome::default() + }, + "https://linux.do", + ); + assert_eq!(state.appended_posts.len(), 1); + assert_eq!(state.appended_posts[0].id, 9); + assert!(state.source_exhausted); + assert!(state.source_cursor.is_none()); + } +} diff --git a/rust/crates/fire-uniffi-topics/src/records/list.rs b/rust/crates/fire-uniffi-topics/src/records/list.rs new file mode 100644 index 00000000..bc299dce --- /dev/null +++ b/rust/crates/fire-uniffi-topics/src/records/list.rs @@ -0,0 +1,121 @@ +use std::sync::Arc; + +use fire_models::{ + LoadMoreTopicPostsQuery, Poll, PollOption, PostActionType, PostFlagRequest, PostReactionUpdate, + PostUpdateRequest, PrivateMessageCreateRequest, ReactionUser, ReactionUsersGroup, + ResolvedUploadUrl, TopicAiSummary, TopicBody, TopicCreateRequest, TopicDetail, + TopicDetailCreatedBy, TopicDetailMeta, TopicDetailPage, TopicDetailSourceQuery, + TopicDetailSourceSnapshot, TopicHeader, TopicListQuery, TopicLoadMoreOutcome, + TopicLoadMoreStopReason, TopicLoadedRange, TopicPost, TopicPostAuthorMetadata, TopicPostBoost, + TopicPostBoostUser, TopicPostStream, TopicReaction, TopicReplyRequest, TopicReplyToUser, + TopicSourceCursor, TopicTimingEntry, TopicTimingsRequest, TopicTreePresentation, TopicTreeRow, + TopicUpdateRequest, UploadResult, VoteResponse, VotedUser, +}; + +use fire_uniffi_types::{ + intern_presented_handle, RenderDocumentHandle, TopicListKindState, TopicParticipantState, + TopicTagState, +}; + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicListQueryState { + pub kind: TopicListKindState, + pub page: Option, + pub topic_ids: Vec, + pub order: Option, + pub ascending: Option, + pub category_slug: Option, + pub category_id: Option, + pub parent_category_slug: Option, + pub tag: Option, + pub additional_tags: Vec, + pub match_all_tags: bool, +} + +impl From for TopicListQueryState { + fn from(value: TopicListQuery) -> Self { + Self { + kind: value.kind.into(), + page: value.page, + topic_ids: value.topic_ids, + order: value.order, + ascending: value.ascending, + category_slug: value.category_slug, + category_id: value.category_id, + parent_category_slug: value.parent_category_slug, + tag: value.tag, + additional_tags: value.additional_tags, + match_all_tags: value.match_all_tags, + } + } +} + +impl From for TopicListQuery { + fn from(value: TopicListQueryState) -> Self { + Self { + kind: value.kind.into(), + page: value.page, + topic_ids: value.topic_ids, + order: value.order, + ascending: value.ascending, + category_slug: value.category_slug, + category_id: value.category_id, + parent_category_slug: value.parent_category_slug, + tag: value.tag, + additional_tags: value.additional_tags, + match_all_tags: value.match_all_tags, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicLoadedRangeState { + pub start_offset: u32, + pub end_offset_exclusive: u32, + pub first_post_id: u64, + pub last_post_id: u64, +} + +impl From for TopicLoadedRangeState { + fn from(value: TopicLoadedRange) -> Self { + Self { + start_offset: value.start_offset, + end_offset_exclusive: value.end_offset_exclusive, + first_post_id: value.first_post_id, + last_post_id: value.last_post_id, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicSourceCursorState { + pub topic_id: u64, + pub session_id: u64, + pub next_stream_offset: u32, + pub last_loaded_post_id: Option, + pub batch_size: u16, +} + +impl From for TopicSourceCursorState { + fn from(value: TopicSourceCursor) -> Self { + Self { + topic_id: value.topic_id, + session_id: value.session_id, + next_stream_offset: value.next_stream_offset, + last_loaded_post_id: value.last_loaded_post_id, + batch_size: value.batch_size, + } + } +} + +impl From for TopicSourceCursor { + fn from(value: TopicSourceCursorState) -> Self { + Self { + topic_id: value.topic_id, + session_id: value.session_id, + next_stream_offset: value.next_stream_offset, + last_loaded_post_id: value.last_loaded_post_id, + batch_size: value.batch_size, + } + } +} diff --git a/rust/crates/fire-uniffi-topics/src/records/mod.rs b/rust/crates/fire-uniffi-topics/src/records/mod.rs new file mode 100644 index 00000000..bb125be3 --- /dev/null +++ b/rust/crates/fire-uniffi-topics/src/records/mod.rs @@ -0,0 +1,11 @@ +mod detail; +mod list; +mod poll; +mod post; +mod upload; + +pub use detail::*; +pub use list::*; +pub use poll::*; +pub use post::*; +pub use upload::*; diff --git a/rust/crates/fire-uniffi-topics/src/records/poll.rs b/rust/crates/fire-uniffi-topics/src/records/poll.rs new file mode 100644 index 00000000..8656578b --- /dev/null +++ b/rust/crates/fire-uniffi-topics/src/records/poll.rs @@ -0,0 +1,90 @@ +use std::sync::Arc; + +use fire_models::{ + LoadMoreTopicPostsQuery, Poll, PollOption, PostActionType, PostFlagRequest, PostReactionUpdate, + PostUpdateRequest, PrivateMessageCreateRequest, ReactionUser, ReactionUsersGroup, + ResolvedUploadUrl, TopicAiSummary, TopicBody, TopicCreateRequest, TopicDetail, + TopicDetailCreatedBy, TopicDetailMeta, TopicDetailPage, TopicDetailSourceQuery, + TopicDetailSourceSnapshot, TopicHeader, TopicListQuery, TopicLoadMoreOutcome, + TopicLoadMoreStopReason, TopicLoadedRange, TopicPost, TopicPostAuthorMetadata, TopicPostBoost, + TopicPostBoostUser, TopicPostStream, TopicReaction, TopicReplyRequest, TopicReplyToUser, + TopicSourceCursor, TopicTimingEntry, TopicTimingsRequest, TopicTreePresentation, TopicTreeRow, + TopicUpdateRequest, UploadResult, VoteResponse, VotedUser, +}; + +use fire_uniffi_types::{ + intern_presented_handle, RenderDocumentHandle, TopicListKindState, TopicParticipantState, + TopicTagState, +}; + +#[derive(uniffi::Record, Debug, Clone)] +pub struct PollOptionState { + pub id: String, + pub html: String, + pub plain_text: String, + pub votes: u32, +} + +impl From for PollOptionState { + fn from(value: PollOption) -> Self { + Self { + id: value.id, + html: value.html, + plain_text: value.plain_text, + votes: value.votes, + } + } +} + +impl From for PollOption { + fn from(value: PollOptionState) -> Self { + Self { + id: value.id, + html: value.html, + plain_text: value.plain_text, + votes: value.votes, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct PollState { + pub id: u64, + pub name: String, + pub kind: String, + pub status: String, + pub results: String, + pub options: Vec, + pub voters: u32, + pub user_votes: Vec, +} + +impl From for PollState { + fn from(value: Poll) -> Self { + Self { + id: value.id, + name: value.name, + kind: value.kind, + status: value.status, + results: value.results, + options: value.options.into_iter().map(Into::into).collect(), + voters: value.voters, + user_votes: value.user_votes, + } + } +} + +impl From for Poll { + fn from(value: PollState) -> Self { + Self { + id: value.id, + name: value.name, + kind: value.kind, + status: value.status, + results: value.results, + options: value.options.into_iter().map(Into::into).collect(), + voters: value.voters, + user_votes: value.user_votes, + } + } +} diff --git a/rust/crates/fire-uniffi-topics/src/records/post.rs b/rust/crates/fire-uniffi-topics/src/records/post.rs new file mode 100644 index 00000000..f36b088d --- /dev/null +++ b/rust/crates/fire-uniffi-topics/src/records/post.rs @@ -0,0 +1,498 @@ +use std::sync::Arc; + +use fire_models::{ + LoadMoreTopicPostsQuery, Poll, PollOption, PostActionType, PostFlagRequest, PostReactionUpdate, + PostUpdateRequest, PrivateMessageCreateRequest, ReactionUser, ReactionUsersGroup, + ResolvedUploadUrl, TopicAiSummary, TopicBody, TopicCreateRequest, TopicDetail, + TopicDetailCreatedBy, TopicDetailMeta, TopicDetailPage, TopicDetailSourceQuery, + TopicDetailSourceSnapshot, TopicHeader, TopicListQuery, TopicLoadMoreOutcome, + TopicLoadMoreStopReason, TopicLoadedRange, TopicPost, TopicPostAuthorMetadata, TopicPostBoost, + TopicPostBoostUser, TopicPostStream, TopicReaction, TopicReplyRequest, TopicReplyToUser, + TopicSourceCursor, TopicTimingEntry, TopicTimingsRequest, TopicTreePresentation, TopicTreeRow, + TopicUpdateRequest, UploadResult, VoteResponse, VotedUser, +}; + +use super::poll::PollState; + +use fire_uniffi_types::{ + intern_presented_handle, RenderDocumentHandle, TopicListKindState, TopicParticipantState, + TopicTagState, +}; + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicReactionState { + pub id: String, + pub kind: Option, + pub count: u32, + pub can_undo: Option, +} + +impl From for TopicReactionState { + fn from(value: TopicReaction) -> Self { + Self { + id: value.id, + kind: value.kind, + count: value.count, + can_undo: value.can_undo, + } + } +} + +impl From for TopicReaction { + fn from(value: TopicReactionState) -> Self { + Self { + id: value.id, + kind: value.kind, + count: value.count, + can_undo: value.can_undo, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct ReactionUserState { + pub id: u64, + pub username: String, + pub name: Option, + pub avatar_template: Option, +} + +impl From for ReactionUserState { + fn from(value: ReactionUser) -> Self { + Self { + id: value.id, + username: value.username, + name: value.name, + avatar_template: value.avatar_template, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct ReactionUsersGroupState { + pub id: String, + pub count: u32, + pub users: Vec, +} + +impl From for ReactionUsersGroupState { + fn from(value: ReactionUsersGroup) -> Self { + Self { + id: value.id, + count: value.count, + users: value.users.into_iter().map(Into::into).collect(), + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicReplyRequestState { + pub topic_id: u64, + pub raw: String, + pub reply_to_post_number: Option, +} + +impl From for TopicReplyRequest { + fn from(value: TopicReplyRequestState) -> Self { + Self { + topic_id: value.topic_id, + raw: value.raw, + reply_to_post_number: value.reply_to_post_number, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicCreateRequestState { + pub title: String, + pub raw: String, + pub category_id: u64, + pub tags: Vec, +} + +impl From for TopicCreateRequest { + fn from(value: TopicCreateRequestState) -> Self { + Self { + title: value.title, + raw: value.raw, + category_id: value.category_id, + tags: value.tags, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct PrivateMessageCreateRequestState { + pub title: String, + pub raw: String, + pub target_recipients: Vec, +} + +impl From for PrivateMessageCreateRequest { + fn from(value: PrivateMessageCreateRequestState) -> Self { + Self { + title: value.title, + raw: value.raw, + target_recipients: value.target_recipients, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicUpdateRequestState { + pub topic_id: u64, + pub title: String, + pub category_id: u64, + pub tags: Vec, +} + +impl From for TopicUpdateRequest { + fn from(value: TopicUpdateRequestState) -> Self { + Self { + topic_id: value.topic_id, + title: value.title, + category_id: value.category_id, + tags: value.tags, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct PostUpdateRequestState { + pub post_id: u64, + pub raw: String, + pub edit_reason: Option, +} + +impl From for PostUpdateRequest { + fn from(value: PostUpdateRequestState) -> Self { + Self { + post_id: value.post_id, + raw: value.raw, + edit_reason: value.edit_reason, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct PostFlagRequestState { + pub post_id: u64, + pub flag_type_id: u32, + pub message: Option, +} + +impl From for PostFlagRequest { + fn from(value: PostFlagRequestState) -> Self { + Self { + post_id: value.post_id, + flag_type_id: value.flag_type_id, + message: value.message, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct PostActionTypeState { + pub id: u32, + pub name_key: String, + pub name: String, + pub description: String, + pub short_description: Option, + pub is_flag: bool, + pub require_message: bool, + pub enabled: bool, + pub position: i32, + pub applies_to: Vec, +} + +impl From for PostActionTypeState { + fn from(value: PostActionType) -> Self { + Self { + id: value.id, + name_key: value.name_key, + name: value.name, + description: value.description, + short_description: value.short_description, + is_flag: value.is_flag, + require_message: value.require_message, + enabled: value.enabled, + position: value.position, + applies_to: value.applies_to, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct PostReactionUpdateState { + pub reactions: Vec, + pub current_user_reaction: Option, +} + +impl From for PostReactionUpdateState { + fn from(value: PostReactionUpdate) -> Self { + Self { + reactions: value.reactions.into_iter().map(Into::into).collect(), + current_user_reaction: value.current_user_reaction.map(Into::into), + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicReplyToUserState { + pub username: String, + pub name: Option, + pub avatar_template: Option, +} + +impl From for TopicReplyToUserState { + fn from(value: TopicReplyToUser) -> Self { + Self { + username: value.username, + name: value.name, + avatar_template: value.avatar_template, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicPostAuthorMetadataState { + pub user_id: Option, + pub user_title: Option, + pub primary_group_name: Option, + pub flair_url: Option, + pub flair_name: Option, + pub flair_bg_color: Option, + pub flair_color: Option, + pub flair_group_id: Option, + pub moderator: bool, + pub admin: bool, + pub group_moderator: bool, + pub user_status_emoji: Option, + pub user_status_description: Option, +} + +impl From for TopicPostAuthorMetadataState { + fn from(value: TopicPostAuthorMetadata) -> Self { + Self { + user_id: value.user_id, + user_title: value.user_title, + primary_group_name: value.primary_group_name, + flair_url: value.flair_url, + flair_name: value.flair_name, + flair_bg_color: value.flair_bg_color, + flair_color: value.flair_color, + flair_group_id: value.flair_group_id, + moderator: value.moderator, + admin: value.admin, + group_moderator: value.group_moderator, + user_status_emoji: value.user_status_emoji, + user_status_description: value.user_status_description, + } + } +} + +impl From for TopicPostAuthorMetadata { + fn from(value: TopicPostAuthorMetadataState) -> Self { + Self { + user_id: value.user_id, + user_title: value.user_title, + primary_group_name: value.primary_group_name, + flair_url: value.flair_url, + flair_name: value.flair_name, + flair_bg_color: value.flair_bg_color, + flair_color: value.flair_color, + flair_group_id: value.flair_group_id, + moderator: value.moderator, + admin: value.admin, + group_moderator: value.group_moderator, + user_status_emoji: value.user_status_emoji, + user_status_description: value.user_status_description, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicPostBoostUserState { + pub id: u64, + pub username: String, + pub name: Option, + pub avatar_template: Option, +} + +impl From for TopicPostBoostUserState { + fn from(value: TopicPostBoostUser) -> Self { + Self { + id: value.id, + username: value.username, + name: value.name, + avatar_template: value.avatar_template, + } + } +} + +impl From for TopicPostBoostUser { + fn from(value: TopicPostBoostUserState) -> Self { + Self { + id: value.id, + username: value.username, + name: value.name, + avatar_template: value.avatar_template, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicPostBoostState { + pub id: u64, + pub presentation: Option>, + pub display_text: String, + pub user: TopicPostBoostUserState, + pub can_delete: bool, + pub can_flag: bool, + pub user_flag_status: Option, + pub available_flags: Vec, +} + +pub(crate) fn topic_post_boost_state_from_model( + value: TopicPostBoost, + _base_url: &str, +) -> TopicPostBoostState { + let presentation = handle_from_presented(value.presented.arc()); + TopicPostBoostState { + id: value.id, + presentation, + display_text: value.display_text, + user: value.user.into(), + can_delete: value.can_delete, + can_flag: value.can_flag, + user_flag_status: value.user_flag_status, + available_flags: value.available_flags, + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicPostState { + pub id: u64, + pub username: String, + pub name: Option, + pub avatar_template: Option, + pub author_metadata: TopicPostAuthorMetadataState, + pub presentation: Option>, + pub raw: Option, + pub post_number: u32, + pub post_type: i32, + pub created_at: Option, + pub updated_at: Option, + pub like_count: u32, + pub reply_count: u32, + pub reply_to_post_number: Option, + pub reply_to_user: Option, + pub bookmarked: bool, + pub bookmark_id: Option, + pub bookmark_name: Option, + pub bookmark_reminder_at: Option, + pub reactions: Vec, + pub current_user_reaction: Option, + pub boosts: Vec, + pub can_boost: bool, + pub polls: Vec, + pub accepted_answer: bool, + pub can_accept_answer: bool, + pub can_unaccept_answer: bool, + pub can_edit: bool, + pub can_delete: bool, + pub can_recover: bool, + pub hidden: bool, +} + +fn handle_from_presented( + presented: Option>, +) -> Option> { + presented.map(intern_presented_handle) +} + +pub(crate) fn topic_post_state_from_model(value: TopicPost, base_url: &str) -> TopicPostState { + topic_post_state_from_model_ex(value, base_url, false) +} + +pub(crate) fn topic_post_state_from_model_with_raw( + value: TopicPost, + base_url: &str, +) -> TopicPostState { + topic_post_state_from_model_ex(value, base_url, true) +} + +fn topic_post_state_from_model_ex( + value: TopicPost, + base_url: &str, + include_raw: bool, +) -> TopicPostState { + let presentation = handle_from_presented(value.presented.arc()); + TopicPostState { + id: value.id, + username: value.username, + name: value.name, + avatar_template: value.avatar_template, + author_metadata: value.author_metadata.into(), + presentation, + raw: include_raw.then(|| value.raw).flatten(), + post_number: value.post_number, + post_type: value.post_type, + created_at: value.created_at, + updated_at: value.updated_at, + like_count: value.like_count, + reply_count: value.reply_count, + reply_to_post_number: value.reply_to_post_number, + reply_to_user: value.reply_to_user.map(Into::into), + bookmarked: value.bookmarked, + bookmark_id: value.bookmark_id, + bookmark_name: value.bookmark_name, + bookmark_reminder_at: value.bookmark_reminder_at, + reactions: value.reactions.into_iter().map(Into::into).collect(), + current_user_reaction: value.current_user_reaction.map(Into::into), + boosts: value + .boosts + .into_iter() + .map(|boost| topic_post_boost_state_from_model(boost, base_url)) + .collect(), + can_boost: value.can_boost, + polls: value.polls.into_iter().map(Into::into).collect(), + accepted_answer: value.accepted_answer, + can_accept_answer: value.can_accept_answer, + can_unaccept_answer: value.can_unaccept_answer, + can_edit: value.can_edit, + can_delete: value.can_delete, + can_recover: value.can_recover, + hidden: value.hidden, + } +} + +impl From for TopicReplyToUser { + fn from(value: TopicReplyToUserState) -> Self { + Self { + username: value.username, + name: value.name, + avatar_template: value.avatar_template, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicPostStreamState { + pub posts: Vec, + pub stream: Vec, +} + +pub(super) fn topic_post_stream_state_from_model( + value: TopicPostStream, + base_url: &str, +) -> TopicPostStreamState { + TopicPostStreamState { + posts: value + .posts + .into_iter() + .map(|post| topic_post_state_from_model(post, base_url)) + .collect(), + stream: value.stream, + } +} diff --git a/rust/crates/fire-uniffi-topics/src/records/upload.rs b/rust/crates/fire-uniffi-topics/src/records/upload.rs new file mode 100644 index 00000000..1ae42641 --- /dev/null +++ b/rust/crates/fire-uniffi-topics/src/records/upload.rs @@ -0,0 +1,167 @@ +use std::sync::Arc; + +use fire_models::{ + LoadMoreTopicPostsQuery, Poll, PollOption, PostActionType, PostFlagRequest, PostReactionUpdate, + PostUpdateRequest, PrivateMessageCreateRequest, ReactionUser, ReactionUsersGroup, + ResolvedUploadUrl, TopicAiSummary, TopicBody, TopicCreateRequest, TopicDetail, + TopicDetailCreatedBy, TopicDetailMeta, TopicDetailPage, TopicDetailSourceQuery, + TopicDetailSourceSnapshot, TopicHeader, TopicListQuery, TopicLoadMoreOutcome, + TopicLoadMoreStopReason, TopicLoadedRange, TopicPost, TopicPostAuthorMetadata, TopicPostBoost, + TopicPostBoostUser, TopicPostStream, TopicReaction, TopicReplyRequest, TopicReplyToUser, + TopicSourceCursor, TopicTimingEntry, TopicTimingsRequest, TopicTreePresentation, TopicTreeRow, + TopicUpdateRequest, UploadResult, VoteResponse, VotedUser, +}; + +use fire_uniffi_types::{ + intern_presented_handle, RenderDocumentHandle, TopicListKindState, TopicParticipantState, + TopicTagState, +}; + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicAiSummaryState { + pub summarized_text: String, + pub algorithm: Option, + pub outdated: bool, + pub can_regenerate: bool, + pub new_posts_since_summary: u32, + pub updated_at: Option, +} + +impl From for TopicAiSummaryState { + fn from(value: TopicAiSummary) -> Self { + Self { + summarized_text: value.summarized_text, + algorithm: value.algorithm, + outdated: value.outdated, + can_regenerate: value.can_regenerate, + new_posts_since_summary: value.new_posts_since_summary, + updated_at: value.updated_at, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct UploadImageRequestState { + pub file_name: String, + pub mime_type: Option, + pub bytes: Vec, +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct UploadResultState { + pub id: Option, + pub short_url: String, + pub url: Option, + pub original_filename: Option, + pub width: Option, + pub height: Option, + pub thumbnail_width: Option, + pub thumbnail_height: Option, +} + +impl From for UploadResultState { + fn from(value: UploadResult) -> Self { + Self { + id: value.id, + short_url: value.short_url, + url: value.url, + original_filename: value.original_filename, + width: value.width, + height: value.height, + thumbnail_width: value.thumbnail_width, + thumbnail_height: value.thumbnail_height, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct ResolvedUploadUrlState { + pub short_url: String, + pub short_path: Option, + pub url: Option, +} + +impl From for ResolvedUploadUrlState { + fn from(value: ResolvedUploadUrl) -> Self { + Self { + short_url: value.short_url, + short_path: value.short_path, + url: value.url, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicTimingEntryState { + pub post_number: u32, + pub milliseconds: u32, +} + +impl From for TopicTimingEntry { + fn from(value: TopicTimingEntryState) -> Self { + Self { + post_number: value.post_number, + milliseconds: value.milliseconds, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicTimingsRequestState { + pub topic_id: u64, + pub topic_time_ms: u32, + pub timings: Vec, +} + +impl From for TopicTimingsRequest { + fn from(value: TopicTimingsRequestState) -> Self { + Self { + topic_id: value.topic_id, + topic_time_ms: value.topic_time_ms, + timings: value.timings.into_iter().map(Into::into).collect(), + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct VotedUserState { + pub id: u64, + pub username: String, + pub name: Option, + pub avatar_template: Option, +} + +impl From for VotedUserState { + fn from(value: VotedUser) -> Self { + Self { + id: value.id, + username: value.username, + name: value.name, + avatar_template: value.avatar_template, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct VoteResponseState { + pub can_vote: bool, + pub vote_limit: u32, + pub vote_count: i32, + pub votes_left: i32, + pub alert: bool, + pub who_voted: Vec, +} + +impl From for VoteResponseState { + fn from(value: VoteResponse) -> Self { + Self { + can_vote: value.can_vote, + vote_limit: value.vote_limit, + vote_count: value.vote_count, + votes_left: value.votes_left, + alert: value.alert, + who_voted: value.who_voted.into_iter().map(Into::into).collect(), + } + } +} + diff --git a/rust/crates/fire-uniffi-topics/src/session.rs b/rust/crates/fire-uniffi-topics/src/session.rs new file mode 100644 index 00000000..4041761c --- /dev/null +++ b/rust/crates/fire-uniffi-topics/src/session.rs @@ -0,0 +1,423 @@ +use std::panic::{self, AssertUnwindSafe}; +use std::sync::Arc; + +use fire_core::TopicDetailObserver as CoreTopicDetailObserver; +use fire_models::TopicDetailUiSnapshot; +use fire_uniffi_types::{ffi_runtime, run_on_ffi_runtime, FireUniFfiError, SharedFireCore}; + +use crate::records::TopicTimingEntryState; +use crate::ui_records::{TopicDetailOpenRequestState, TopicDetailUiSnapshotState}; +use crate::FireTopicsHandle; + +struct FfiTopicDetailObserver { + inner: Arc, +} + +impl CoreTopicDetailObserver for FfiTopicDetailObserver { + fn on_snapshot(&self, snapshot: TopicDetailUiSnapshot) { + let projected = TopicDetailUiSnapshotState::from_core(snapshot); + let inner = Arc::clone(&self.inner); + let _ = panic::catch_unwind(AssertUnwindSafe(|| inner.on_snapshot(projected))); + } +} + +#[uniffi::export(with_foreign)] +pub trait TopicDetailObserver: Send + Sync { + fn on_snapshot(&self, snapshot: TopicDetailUiSnapshotState); +} + +#[derive(uniffi::Object)] +pub struct TopicDetailSessionHandle { + shared: Arc, + inner: Arc, + topic_id: u64, + owner_token: String, +} + +#[uniffi::export] +impl FireTopicsHandle { + pub fn cancel_topic_detail_http(&self) { + self.shared.core.cancel_topic_detail_http(); + } + + pub fn close_all_topic_detail_sessions(&self) { + self.shared.core.close_all_topic_detail_sessions(); + } + + pub fn open_topic_detail( + &self, + request: TopicDetailOpenRequestState, + observer: Arc, + ) -> Result, FireUniFfiError> { + let topic_id = request.topic_id; + let owner_token = request.owner_token.clone(); + let core = Arc::clone(&self.shared.core); + let request = request.into_core(); + let observer = Arc::new(FfiTopicDetailObserver { inner: observer }); + let (tx, rx) = std::sync::mpsc::sync_channel(1); + ffi_runtime().spawn(async move { + let session = core.open_topic_detail(request, observer); + let _ = tx.send(session); + }); + let inner = rx.recv().map_err(|_| FireUniFfiError::Runtime { + details: "failed to open topic detail session".to_string(), + })?; + Ok(Arc::new(TopicDetailSessionHandle { + shared: Arc::clone(&self.shared), + inner, + topic_id, + owner_token, + })) + } +} + +#[uniffi::export] +impl TopicDetailSessionHandle { + pub fn close(&self) { + self.shared + .core + .release_topic_detail_owner(self.topic_id, &self.owner_token); + } + + pub fn reload( + &self, + target_post_number: Option, + force_load: bool, + track_visit: bool, + allow_suggested_unread_root: bool, + ) { + self.inner.reload( + target_post_number, + force_load, + track_visit, + allow_suggested_unread_root, + ); + } + + pub fn load_more(&self) { + self.inner.load_more(); + } + + pub fn note_visible_posts(&self, post_numbers: Vec) { + self.inner.note_visible_posts(post_numbers); + } + + pub fn note_filtered_feed_tail(&self, item_count: u32, visible_max_item: Option) { + self.inner + .note_filtered_feed_tail(item_count, visible_max_item); + } + + pub fn note_scroll_interaction(&self, active: bool) { + self.inner.note_scroll_interaction(active); + } + + pub fn acknowledge_scroll_target(&self, post_number: u32) { + self.inner.acknowledge_scroll_target(post_number); + } + + pub fn clear_scroll_target(&self) { + self.inner.clear_scroll_target(); + } + + pub fn begin_reply_typing(&self) { + self.inner.begin_reply_typing(); + } + + pub fn end_reply_typing(&self) { + self.inner.end_reply_typing(); + } + + pub fn reload_ai_summary(&self, skip_age_check: bool) { + self.inner.reload_ai_summary(skip_age_check); + } + + pub fn load_reply_context(&self, post_id: u64) { + self.inner.load_reply_context(post_id); + } + + pub async fn prepare_edit(&self, post_id: u64) -> Result { + let inner = Arc::clone(&self.inner); + run_on_ffi_runtime( + "prepare_edit", + Arc::clone(&self.shared.panic_state), + async move { inner.prepare_edit(post_id).await }, + ) + .await + } + + pub async fn submit_reply( + &self, + raw: String, + reply_to_post_number: Option, + scroll_to_created: bool, + ) -> Result<(), FireUniFfiError> { + let inner = Arc::clone(&self.inner); + run_on_ffi_runtime( + "submit_reply", + Arc::clone(&self.shared.panic_state), + async move { + inner + .submit_reply(raw, reply_to_post_number, scroll_to_created) + .await + }, + ) + .await + } + + pub async fn create_boost(&self, post_id: u64, raw: String) -> Result<(), FireUniFfiError> { + let inner = Arc::clone(&self.inner); + run_on_ffi_runtime( + "create_boost", + Arc::clone(&self.shared.panic_state), + async move { inner.create_boost(post_id, raw).await }, + ) + .await + } + + pub async fn delete_boost(&self, post_id: u64, boost_id: u64) -> Result<(), FireUniFfiError> { + let inner = Arc::clone(&self.inner); + run_on_ffi_runtime( + "delete_boost", + Arc::clone(&self.shared.panic_state), + async move { inner.delete_boost(post_id, boost_id).await }, + ) + .await + } + + pub async fn update_post( + &self, + post_id: u64, + raw: String, + edit_reason: Option, + ) -> Result<(), FireUniFfiError> { + let inner = Arc::clone(&self.inner); + run_on_ffi_runtime( + "update_post", + Arc::clone(&self.shared.panic_state), + async move { inner.update_post(post_id, raw, edit_reason).await }, + ) + .await + } + + pub async fn delete_post(&self, post_id: u64) -> Result<(), FireUniFfiError> { + let inner = Arc::clone(&self.inner); + run_on_ffi_runtime( + "delete_post", + Arc::clone(&self.shared.panic_state), + async move { inner.delete_post(post_id).await }, + ) + .await + } + + pub async fn recover_post(&self, post_id: u64) -> Result<(), FireUniFfiError> { + let inner = Arc::clone(&self.inner); + run_on_ffi_runtime( + "recover_post", + Arc::clone(&self.shared.panic_state), + async move { inner.recover_post(post_id).await }, + ) + .await + } + + pub async fn flag_post( + &self, + post_id: u64, + flag_type_id: u32, + message: Option, + ) -> Result<(), FireUniFfiError> { + let inner = Arc::clone(&self.inner); + run_on_ffi_runtime( + "flag_post", + Arc::clone(&self.shared.panic_state), + async move { inner.flag_post(post_id, flag_type_id, message).await }, + ) + .await + } + + pub async fn ensure_flag_types(&self) -> Result<(), FireUniFfiError> { + let inner = Arc::clone(&self.inner); + run_on_ffi_runtime( + "ensure_flag_types", + Arc::clone(&self.shared.panic_state), + async move { inner.ensure_flag_types().await }, + ) + .await + } + + pub async fn set_liked(&self, post_id: u64, liked: bool) -> Result<(), FireUniFfiError> { + let inner = Arc::clone(&self.inner); + run_on_ffi_runtime( + "set_liked", + Arc::clone(&self.shared.panic_state), + async move { inner.set_liked(post_id, liked).await }, + ) + .await + } + + pub async fn toggle_reaction( + &self, + post_id: u64, + reaction_id: String, + ) -> Result<(), FireUniFfiError> { + let inner = Arc::clone(&self.inner); + run_on_ffi_runtime( + "toggle_reaction", + Arc::clone(&self.shared.panic_state), + async move { inner.toggle_reaction(post_id, reaction_id).await }, + ) + .await + } + + pub async fn vote_poll( + &self, + post_id: u64, + poll_name: String, + options: Vec, + ) -> Result<(), FireUniFfiError> { + let inner = Arc::clone(&self.inner); + run_on_ffi_runtime( + "vote_poll", + Arc::clone(&self.shared.panic_state), + async move { inner.vote_poll(post_id, poll_name, options).await }, + ) + .await + } + + pub async fn unvote_poll( + &self, + post_id: u64, + poll_name: String, + ) -> Result<(), FireUniFfiError> { + let inner = Arc::clone(&self.inner); + run_on_ffi_runtime( + "unvote_poll", + Arc::clone(&self.shared.panic_state), + async move { inner.unvote_poll(post_id, poll_name).await }, + ) + .await + } + + pub async fn vote_topic(&self, voted: bool) -> Result<(), FireUniFfiError> { + let inner = Arc::clone(&self.inner); + run_on_ffi_runtime( + "vote_topic", + Arc::clone(&self.shared.panic_state), + async move { inner.vote_topic(voted).await }, + ) + .await + } + + pub async fn accept_solution( + &self, + post_id: u64, + accepted: bool, + ) -> Result<(), FireUniFfiError> { + let inner = Arc::clone(&self.inner); + run_on_ffi_runtime( + "accept_solution", + Arc::clone(&self.shared.panic_state), + async move { inner.accept_solution(post_id, accepted).await }, + ) + .await + } + + pub async fn create_bookmark( + &self, + bookmarkable_id: u64, + bookmarkable_type: String, + name: Option, + reminder_at: Option, + auto_delete_preference: Option, + ) -> Result<(), FireUniFfiError> { + let inner = Arc::clone(&self.inner); + run_on_ffi_runtime( + "create_bookmark", + Arc::clone(&self.shared.panic_state), + async move { + inner + .create_bookmark( + bookmarkable_id, + bookmarkable_type, + name, + reminder_at, + auto_delete_preference, + ) + .await + }, + ) + .await + } + + pub async fn update_bookmark( + &self, + bookmark_id: u64, + name: Option, + reminder_at: Option, + auto_delete_preference: Option, + ) -> Result<(), FireUniFfiError> { + let inner = Arc::clone(&self.inner); + run_on_ffi_runtime( + "update_bookmark", + Arc::clone(&self.shared.panic_state), + async move { + inner + .update_bookmark(bookmark_id, name, reminder_at, auto_delete_preference) + .await + }, + ) + .await + } + + pub async fn delete_bookmark(&self, bookmark_id: u64) -> Result<(), FireUniFfiError> { + let inner = Arc::clone(&self.inner); + run_on_ffi_runtime( + "delete_bookmark", + Arc::clone(&self.shared.panic_state), + async move { inner.delete_bookmark(bookmark_id).await }, + ) + .await + } + + pub async fn set_notification_level(&self, level: i32) -> Result<(), FireUniFfiError> { + let inner = Arc::clone(&self.inner); + run_on_ffi_runtime( + "set_notification_level", + Arc::clone(&self.shared.panic_state), + async move { inner.set_notification_level(level).await }, + ) + .await + } + + pub async fn update_topic( + &self, + title: String, + category_id: u64, + tags: Vec, + ) -> Result<(), FireUniFfiError> { + let inner = Arc::clone(&self.inner); + run_on_ffi_runtime( + "update_topic", + Arc::clone(&self.shared.panic_state), + async move { inner.update_topic(title, category_id, tags).await }, + ) + .await + } + + pub async fn report_timings( + &self, + topic_time_ms: u32, + timings: Vec, + ) -> Result { + let inner = Arc::clone(&self.inner); + let timings = timings + .into_iter() + .map(fire_models::TopicTimingEntry::from) + .collect(); + run_on_ffi_runtime( + "report_timings", + Arc::clone(&self.shared.panic_state), + async move { inner.report_timings(topic_time_ms, timings).await }, + ) + .await + } +} diff --git a/rust/crates/fire-uniffi-topics/src/ui_records.rs b/rust/crates/fire-uniffi-topics/src/ui_records.rs new file mode 100644 index 00000000..5892d831 --- /dev/null +++ b/rust/crates/fire-uniffi-topics/src/ui_records.rs @@ -0,0 +1,569 @@ +use std::sync::Arc; + +use fire_models::{ + TopicDetailAuthorDisplay, TopicDetailBoostDisplay, TopicDetailChrome, TopicDetailComposerModel, + TopicDetailLoadError, TopicDetailNotice, TopicDetailPhase, TopicDetailPollDisplay, + TopicDetailReactionChip, TopicDetailReplyContext, TopicDetailSidecarModel, + TopicDetailTypingUser, TopicDetailUiRow, TopicDetailUiSnapshot, TopicHomeRowCountPatch, + TopicHomeUnreadDecision, +}; +use fire_uniffi_types::{intern_presented_handle, RenderDocumentHandle}; + +use crate::records::{PollOptionState, PollState, PostActionTypeState}; + +fn presentation_handle( + presented: &fire_models::AttachedPresentation, +) -> Option> { + presented.arc().map(intern_presented_handle) +} + +#[derive(uniffi::Enum, Debug, Clone, PartialEq, Eq)] +pub enum TopicDetailPhaseState { + Loading, + Ready, + Failed, +} + +impl From for TopicDetailPhaseState { + fn from(value: TopicDetailPhase) -> Self { + match value { + TopicDetailPhase::Loading => Self::Loading, + TopicDetailPhase::Ready => Self::Ready, + TopicDetailPhase::Failed => Self::Failed, + } + } +} + +#[derive(uniffi::Enum, Debug, Clone, PartialEq, Eq)] +pub enum TopicDetailLoadErrorState { + Network, + LoginRequired, + Unrecoverable { message: String }, +} + +impl From for TopicDetailLoadErrorState { + fn from(value: TopicDetailLoadError) -> Self { + match value { + TopicDetailLoadError::Network => Self::Network, + TopicDetailLoadError::LoginRequired => Self::LoginRequired, + TopicDetailLoadError::Unrecoverable { message } => Self::Unrecoverable { message }, + } + } +} + +#[derive(uniffi::Enum, Debug, Clone, Copy, PartialEq, Eq)] +pub enum TopicHomeUnreadDecisionState { + WhenLastReadMissing, + CaughtUp, + StillUnread, +} + +impl From for TopicHomeUnreadDecisionState { + fn from(value: TopicHomeUnreadDecision) -> Self { + match value { + TopicHomeUnreadDecision::WhenLastReadMissing => Self::WhenLastReadMissing, + TopicHomeUnreadDecision::CaughtUp => Self::CaughtUp, + TopicHomeUnreadDecision::StillUnread => Self::StillUnread, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicDetailNoticeState { + pub title: Option, + pub message: String, + pub retryable: bool, + pub emphasizes_error: bool, +} + +impl From for TopicDetailNoticeState { + fn from(value: TopicDetailNotice) -> Self { + Self { + title: value.title, + message: value.message, + retryable: value.retryable, + emphasizes_error: value.emphasizes_error, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicHomeRowCountPatchState { + pub topic_id: u64, + pub posts_count: u32, + pub reply_count: u32, + pub views: u32, + pub last_read_post_number: Option, + pub highest_post_number: u32, + pub unread: TopicHomeUnreadDecisionState, +} + +impl From for TopicHomeRowCountPatchState { + fn from(value: TopicHomeRowCountPatch) -> Self { + Self { + topic_id: value.topic_id, + posts_count: value.posts_count, + reply_count: value.reply_count, + views: value.views, + last_read_post_number: value.last_read_post_number, + highest_post_number: value.highest_post_number, + unread: value.unread.into(), + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicDetailAuthorDisplayState { + pub username: String, + pub name: Option, + pub avatar_template: Option, + pub user_id: Option, + pub user_title: Option, + pub primary_group_name: Option, + pub flair_url: Option, + pub flair_name: Option, + pub flair_bg_color: Option, + pub flair_color: Option, + pub flair_group_id: Option, + pub moderator: bool, + pub admin: bool, + pub group_moderator: bool, + pub user_status_emoji: Option, + pub user_status_description: Option, +} + +impl From for TopicDetailAuthorDisplayState { + fn from(value: TopicDetailAuthorDisplay) -> Self { + Self { + username: value.username, + name: value.name, + avatar_template: value.avatar_template, + user_id: value.user_id, + user_title: value.user_title, + primary_group_name: value.primary_group_name, + flair_url: value.flair_url, + flair_name: value.flair_name, + flair_bg_color: value.flair_bg_color, + flair_color: value.flair_color, + flair_group_id: value.flair_group_id, + moderator: value.moderator, + admin: value.admin, + group_moderator: value.group_moderator, + user_status_emoji: value.user_status_emoji, + user_status_description: value.user_status_description, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicDetailParticipantDisplayState { + pub user_id: u64, + pub username: String, + pub name: Option, +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicDetailReactionChipState { + pub id: String, + pub kind: Option, + pub count: u32, + pub can_undo: Option, + pub selected: bool, +} + +impl From for TopicDetailReactionChipState { + fn from(value: TopicDetailReactionChip) -> Self { + Self { + id: value.id, + kind: value.kind, + count: value.count, + can_undo: value.can_undo, + selected: value.selected, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicDetailBoostUserDisplayState { + pub id: u64, + pub username: String, + pub name: Option, + pub avatar_template: Option, +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicDetailBoostDisplayState { + pub id: u64, + pub display_text: String, + pub user: TopicDetailBoostUserDisplayState, + pub can_delete: bool, + pub can_flag: bool, + pub user_flag_status: Option, + pub available_flags: Vec, + pub presentation: Option>, +} + +impl From for TopicDetailBoostDisplayState { + fn from(value: TopicDetailBoostDisplay) -> Self { + Self { + id: value.id, + display_text: value.display_text, + user: TopicDetailBoostUserDisplayState { + id: value.user.id, + username: value.user.username, + name: value.user.name, + avatar_template: value.user.avatar_template, + }, + can_delete: value.can_delete, + can_flag: value.can_flag, + user_flag_status: value.user_flag_status, + available_flags: value.available_flags, + presentation: presentation_handle(&value.presentation), + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicDetailReplyUserDisplayState { + pub username: String, + pub name: Option, + pub avatar_template: Option, +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicDetailTypingUserState { + pub id: u64, + pub username: String, + pub avatar_template: Option, +} + +impl From for TopicDetailTypingUserState { + fn from(value: TopicDetailTypingUser) -> Self { + Self { + id: value.id, + username: value.username, + avatar_template: value.avatar_template, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicDetailChromeState { + pub title: String, + pub slug: String, + pub archetype: Option, + pub bookmarked: bool, + pub bookmark_id: Option, + pub bookmark_name: Option, + pub bookmark_reminder_at: Option, + pub notification_level: Option, + pub can_edit: bool, + pub category_id: Option, + pub tags: Vec, + pub views: u32, + pub posts_count: u32, + pub reply_count: u32, + pub like_count: u32, + pub vote_count: i32, + pub user_voted: bool, + pub can_vote: bool, + pub has_accepted_answer: bool, + pub created_at: Option, + pub highest_post_number: u32, + pub last_read_post_number: Option, + pub participants: Vec, + pub summarizable: bool, +} + +impl From for TopicDetailChromeState { + fn from(value: TopicDetailChrome) -> Self { + Self { + title: value.title, + slug: value.slug, + archetype: value.archetype, + bookmarked: value.bookmarked, + bookmark_id: value.bookmark_id, + bookmark_name: value.bookmark_name, + bookmark_reminder_at: value.bookmark_reminder_at, + notification_level: value.notification_level, + can_edit: value.can_edit, + category_id: value.category_id, + tags: value.tags, + views: value.views, + posts_count: value.posts_count, + reply_count: value.reply_count, + like_count: value.like_count, + vote_count: value.vote_count, + user_voted: value.user_voted, + can_vote: value.can_vote, + has_accepted_answer: value.has_accepted_answer, + created_at: value.created_at, + highest_post_number: value.highest_post_number, + last_read_post_number: value.last_read_post_number, + participants: value + .participants + .into_iter() + .map(|participant| TopicDetailParticipantDisplayState { + user_id: participant.user_id, + username: participant.username, + name: participant.name, + }) + .collect(), + summarizable: value.summarizable, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicDetailComposerModelState { + pub typing_users: Vec, + pub is_submitting: bool, +} + +impl From for TopicDetailComposerModelState { + fn from(value: TopicDetailComposerModel) -> Self { + Self { + typing_users: value.typing_users.into_iter().map(Into::into).collect(), + is_submitting: value.is_submitting, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicDetailSidecarModelState { + pub summarized_text: Option, + pub algorithm: Option, + pub outdated: bool, + pub can_regenerate: bool, + pub new_posts_since_summary: u32, + pub updated_at: Option, + pub is_loading: bool, + pub error: Option, +} + +impl From for TopicDetailSidecarModelState { + fn from(value: TopicDetailSidecarModel) -> Self { + Self { + summarized_text: value.summarized_text, + algorithm: value.algorithm, + outdated: value.outdated, + can_regenerate: value.can_regenerate, + new_posts_since_summary: value.new_posts_since_summary, + updated_at: value.updated_at, + is_loading: value.is_loading, + error: value.error, + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicDetailUiRowState { + pub post_id: u64, + pub post_number: u32, + pub root_post_number: u32, + pub parent_post_number: Option, + pub depth: u16, + pub has_children: bool, + pub is_last_sibling: bool, + pub descendant_count: u32, + pub author: TopicDetailAuthorDisplayState, + pub presentation: Option>, + pub layout_checksum: u64, + pub interaction_checksum: u64, + pub created_at: Option, + pub updated_at: Option, + pub post_type: i32, + pub reply_count: u32, + pub reply_to_username: Option, + pub reply_to_user: Option, + pub like_count: u32, + pub reactions: Vec, + pub current_reaction_id: Option, + pub polls: Vec, + pub boosts: Vec, + pub accepted_answer: bool, + pub can_accept_answer: bool, + pub can_unaccept_answer: bool, + pub can_edit: bool, + pub can_delete: bool, + pub can_recover: bool, + pub can_boost: bool, + pub bookmarked: bool, + pub bookmark_id: Option, + pub bookmark_name: Option, + pub bookmark_reminder_at: Option, + pub hidden: bool, + pub is_mutating: bool, + pub is_loading_reply_context: bool, + pub is_original_post: bool, +} + +impl From for TopicDetailUiRowState { + fn from(value: TopicDetailUiRow) -> Self { + Self { + post_id: value.post_id, + post_number: value.post_number, + root_post_number: value.root_post_number, + parent_post_number: value.parent_post_number, + depth: value.depth, + has_children: value.has_children, + is_last_sibling: value.is_last_sibling, + descendant_count: value.descendant_count, + author: value.author.into(), + presentation: presentation_handle(&value.presentation), + layout_checksum: value.layout_checksum, + interaction_checksum: value.interaction_checksum, + created_at: value.created_at, + updated_at: value.updated_at, + post_type: value.post_type, + reply_count: value.reply_count, + reply_to_username: value.reply_to_username, + reply_to_user: value.reply_to_user.map(|user| TopicDetailReplyUserDisplayState { + username: user.username, + name: user.name, + avatar_template: user.avatar_template, + }), + like_count: value.like_count, + reactions: value.reactions.into_iter().map(Into::into).collect(), + current_reaction_id: value.current_reaction_id, + polls: value.polls.into_iter().map(poll_state_from_display).collect(), + boosts: value.boosts.into_iter().map(Into::into).collect(), + accepted_answer: value.accepted_answer, + can_accept_answer: value.can_accept_answer, + can_unaccept_answer: value.can_unaccept_answer, + can_edit: value.can_edit, + can_delete: value.can_delete, + can_recover: value.can_recover, + can_boost: value.can_boost, + bookmarked: value.bookmarked, + bookmark_id: value.bookmark_id, + bookmark_name: value.bookmark_name, + bookmark_reminder_at: value.bookmark_reminder_at, + hidden: value.hidden, + is_mutating: value.is_mutating, + is_loading_reply_context: value.is_loading_reply_context, + is_original_post: value.is_original_post, + } + } +} + +fn poll_state_from_display(poll: TopicDetailPollDisplay) -> PollState { + PollState { + id: poll.id, + name: poll.name, + kind: poll.kind, + status: poll.status, + results: poll.results, + options: poll + .options + .into_iter() + .map(|option| PollOptionState { + id: option.id, + html: option.html, + plain_text: option.plain_text, + votes: option.votes, + }) + .collect(), + voters: poll.voters, + user_votes: poll.user_votes, + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicDetailReplyContextState { + pub root_post_id: u64, + pub appended_post_ids: Vec, + pub history_rows: Vec, +} + +impl From for TopicDetailReplyContextState { + fn from(value: TopicDetailReplyContext) -> Self { + Self { + root_post_id: value.root_post_id, + appended_post_ids: value.appended_post_ids, + history_rows: value.history_rows.into_iter().map(Into::into).collect(), + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicDetailUiSnapshotState { + pub topic_id: u64, + pub generation: u64, + pub phase: TopicDetailPhaseState, + pub load_error: Option, + pub notice: Option, + pub has_more: bool, + pub is_loading_more: bool, + pub load_more_error: Option, + pub scroll_target_post_number: Option, + pub collection_revision: u64, + pub chrome_revision: u64, + pub sidecar_revision: u64, + pub interaction_revision: u64, + pub chrome: TopicDetailChromeState, + pub composer: TopicDetailComposerModelState, + pub sidecar: TopicDetailSidecarModelState, + pub rows: Vec, + pub focused_reply_context: Option, + pub flag_types: Vec, + pub home_row_patch: Option, +} + +impl TopicDetailUiSnapshotState { + pub fn from_core(snapshot: TopicDetailUiSnapshot) -> Self { + Self { + topic_id: snapshot.topic_id, + generation: snapshot.generation, + phase: snapshot.phase.into(), + load_error: snapshot.load_error.map(Into::into), + notice: snapshot.notice.map(Into::into), + has_more: snapshot.has_more, + is_loading_more: snapshot.is_loading_more, + load_more_error: snapshot.load_more_error, + scroll_target_post_number: snapshot.scroll_target_post_number, + collection_revision: snapshot.collection_revision, + chrome_revision: snapshot.chrome_revision, + sidecar_revision: snapshot.sidecar_revision, + interaction_revision: snapshot.interaction_revision, + chrome: snapshot.chrome.into(), + composer: snapshot.composer.into(), + sidecar: snapshot.sidecar.into(), + rows: snapshot.rows.into_iter().map(Into::into).collect(), + focused_reply_context: snapshot.focused_reply_context.map(Into::into), + flag_types: snapshot + .flag_types + .into_iter() + .map(PostActionTypeState::from) + .collect(), + home_row_patch: snapshot.home_row_patch.map(Into::into), + } + } +} + +#[derive(uniffi::Record, Debug, Clone)] +pub struct TopicDetailOpenRequestState { + pub topic_id: u64, + pub owner_token: String, + pub slug_hint: Option, + pub target_post_number: Option, + pub bypass_cache: bool, + pub force_load: bool, + pub track_visit: bool, + pub allow_suggested_unread_root: bool, +} + +impl TopicDetailOpenRequestState { + pub fn into_core(self) -> fire_core::TopicDetailOpenRequest { + fire_core::TopicDetailOpenRequest { + topic_id: self.topic_id, + owner_token: self.owner_token, + slug_hint: self.slug_hint, + target_post_number: self.target_post_number, + bypass_cache: self.bypass_cache, + force_load: self.force_load, + track_visit: self.track_visit, + allow_suggested_unread_root: self.allow_suggested_unread_root, + } + } +} From 743d92bf0c6fa8a829024ca7940e7e3226dc2618 Mon Sep 17 00:00:00 2001 From: peter rich Date: Tue, 22 Sep 2026 17:48:41 +0800 Subject: [PATCH 02/11] fix(ci): unblock topic-detail session lint and host builds Format and clippy-clean the new Rust modules, rename session handle close to release for Kotlin AutoCloseable, fix Android unread decision FFI name, and regenerate Fire.xcodeproj for the new Swift snapshots. Co-authored-by: Cursor --- .../2026-09-22-ios-topic-detail-session.md | 5 +- .../fire/app/ui/home/HomeTopicDetailPatch.kt | 10 +- .../ui/topicdetail/TopicDetailViewModel.kt | 4 +- .../app/ui/home/HomeTopicDetailPatcherTest.kt | 4 +- .../App/Stores/FireTopicDetailStore.swift | 4 +- native/ios-app/Fire.xcodeproj/project.pbxproj | 89 ++++----- .../fire-core/src/core/messagebus/channels.rs | 9 +- .../fire-core/src/core/messagebus/mod.rs | 16 +- .../fire-core/src/core/messagebus/parse.rs | 9 +- .../fire-core/src/core/messagebus/poll.rs | 19 +- .../fire-core/src/core/messagebus/runtime.rs | 64 +++--- rust/crates/fire-core/src/core/mod.rs | 2 +- .../fire-core/src/core/topic_detail/actor.rs | 37 ++-- .../fire-core/src/core/topic_detail/bus.rs | 11 +- .../fire-core/src/core/topic_detail/load.rs | 13 +- .../fire-core/src/core/topic_detail/mod.rs | 8 +- .../src/core/topic_detail/mutations.rs | 9 +- .../src/core/topic_detail/publish.rs | 13 +- .../src/core/topic_detail/reactions.rs | 17 +- .../src/core/topic_detail/registry.rs | 35 ++-- .../src/core/topic_detail/session.rs | 1 - .../src/core/topic_detail/summary.rs | 28 +-- .../fire-core/src/core/topic_detail/tests.rs | 186 +++++++++--------- .../fire-core/src/core/topic_detail/window.rs | 28 ++- .../src/core/topic_detail_project.rs | 73 +++---- rust/crates/fire-core/src/core/topics/list.rs | 5 +- rust/crates/fire-core/src/core/topics/mod.rs | 3 +- .../crates/fire-core/src/core/topics/posts.rs | 5 +- .../src/core/topics/source/hydrate.rs | 25 ++- .../fire-core/src/core/topics/source/load.rs | 23 +-- .../fire-core/src/core/topics/source/mod.rs | 7 +- .../src/core/topics/source/session.rs | 32 +-- rust/crates/fire-core/src/core/topics/tree.rs | 6 +- rust/crates/fire-uniffi-session/src/lib.rs | 9 +- .../fire-uniffi-topics/src/records/detail.rs | 19 +- .../fire-uniffi-topics/src/records/list.rs | 19 +- .../fire-uniffi-topics/src/records/poll.rs | 19 +- .../fire-uniffi-topics/src/records/post.rs | 20 +- .../fire-uniffi-topics/src/records/upload.rs | 19 +- rust/crates/fire-uniffi-topics/src/session.rs | 2 +- .../fire-uniffi-topics/src/ui_records.rs | 18 +- 41 files changed, 386 insertions(+), 539 deletions(-) diff --git a/docs/architecture/2026-09-22-ios-topic-detail-session.md b/docs/architecture/2026-09-22-ios-topic-detail-session.md index 4587dcc9..8502faac 100644 --- a/docs/architecture/2026-09-22-ios-topic-detail-session.md +++ b/docs/architecture/2026-09-22-ios-topic-detail-session.md @@ -813,9 +813,10 @@ impl FireTopicsHandle { #[uniffi::export] impl TopicDetailSessionHandle { - /// Handle stores the owner token from open. close calls + /// Handle stores the owner token from open. `release` calls /// registry.release(topic_id, owner_token) for that owner only. - pub fn close(&self); + /// Named `release` (not `close`) so Kotlin UniFFI does not collide with `AutoCloseable.close`. + pub fn release(&self); /// Always HTTP. `force_load` is `TopicDetailSourceQuery.force_load`, not a cache bypass. pub fn reload( &self, diff --git a/native/android-app/src/main/java/com/fire/app/ui/home/HomeTopicDetailPatch.kt b/native/android-app/src/main/java/com/fire/app/ui/home/HomeTopicDetailPatch.kt index 92570e2d..6acdc4bf 100644 --- a/native/android-app/src/main/java/com/fire/app/ui/home/HomeTopicDetailPatch.kt +++ b/native/android-app/src/main/java/com/fire/app/ui/home/HomeTopicDetailPatch.kt @@ -3,7 +3,7 @@ package com.fire.app.ui.home import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import uniffi.fire_uniffi_topics.TopicHomeRowCountPatchState -import uniffi.fire_uniffi_topics.TopicHomeUnreadDecision +import uniffi.fire_uniffi_topics.TopicHomeUnreadDecisionState import uniffi.fire_uniffi_types.TopicRowState data class HomeTopicDetailPatch( @@ -13,7 +13,7 @@ data class HomeTopicDetailPatch( val views: UInt, val lastReadPostNumber: UInt?, val highestPostNumber: UInt, - val unread: TopicHomeUnreadDecision = TopicHomeUnreadDecision.STILL_UNREAD, + val unread: TopicHomeUnreadDecisionState = TopicHomeUnreadDecisionState.STILL_UNREAD, ) { companion object { fun from(patch: TopicHomeRowCountPatchState): HomeTopicDetailPatch { @@ -53,7 +53,7 @@ object HomeTopicDetailPatcher { val nextNewPosts: UInt val nextHasUnreadPosts: Boolean when (patch.unread) { - TopicHomeUnreadDecision.WHEN_LAST_READ_MISSING -> { + TopicHomeUnreadDecisionState.WHEN_LAST_READ_MISSING -> { nextHasUnreadPosts = row.hasUnreadPosts if (row.hasUnreadPosts) { nextUnreadPosts = topic.unreadPosts @@ -63,12 +63,12 @@ object HomeTopicDetailPatcher { nextNewPosts = 0u } } - TopicHomeUnreadDecision.CAUGHT_UP -> { + TopicHomeUnreadDecisionState.CAUGHT_UP -> { nextUnreadPosts = 0u nextNewPosts = 0u nextHasUnreadPosts = false } - TopicHomeUnreadDecision.STILL_UNREAD -> { + TopicHomeUnreadDecisionState.STILL_UNREAD -> { nextUnreadPosts = topic.unreadPosts nextNewPosts = topic.newPosts nextHasUnreadPosts = true diff --git a/native/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailViewModel.kt b/native/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailViewModel.kt index da0536fe..5eb65d11 100644 --- a/native/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailViewModel.kt +++ b/native/android-app/src/main/java/com/fire/app/ui/topicdetail/TopicDetailViewModel.kt @@ -156,7 +156,7 @@ class TopicDetailViewModel( private fun prepareForTopicLoad(topicId: ULong) { val previousTopicId = sourceSnapshot?.header?.topicId ?: _detail.value?.id ?: subscribedTopicId if (previousTopicId != null && previousTopicId != topicId) { - sessionHandle?.close() + sessionHandle?.release() sessionHandle = null } if (previousTopicId == null || previousTopicId == topicId) { @@ -1037,7 +1037,7 @@ class TopicDetailViewModel( override fun onCleared() { topicAiSummaryJob?.cancel() - sessionHandle?.close() + sessionHandle?.release() sessionHandle = null releaseTopicDetailMessageBus() super.onCleared() diff --git a/native/android-app/src/test/java/com/fire/app/ui/home/HomeTopicDetailPatcherTest.kt b/native/android-app/src/test/java/com/fire/app/ui/home/HomeTopicDetailPatcherTest.kt index 7b65639b..0f8fde3f 100644 --- a/native/android-app/src/test/java/com/fire/app/ui/home/HomeTopicDetailPatcherTest.kt +++ b/native/android-app/src/test/java/com/fire/app/ui/home/HomeTopicDetailPatcherTest.kt @@ -3,7 +3,7 @@ package com.fire.app.ui.home import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Test -import uniffi.fire_uniffi_topics.TopicHomeUnreadDecision +import uniffi.fire_uniffi_topics.TopicHomeUnreadDecisionState import uniffi.fire_uniffi_types.TopicRowState import uniffi.fire_uniffi_types.TopicSummaryState @@ -82,7 +82,7 @@ class HomeTopicDetailPatcherTest { views = 321u, lastReadPostNumber = 9u, highestPostNumber = 9u, - unread = TopicHomeUnreadDecision.CAUGHT_UP, + unread = TopicHomeUnreadDecisionState.CAUGHT_UP, ), ) diff --git a/native/ios-app/App/Stores/FireTopicDetailStore.swift b/native/ios-app/App/Stores/FireTopicDetailStore.swift index 56ed68cf..795d33e6 100644 --- a/native/ios-app/App/Stores/FireTopicDetailStore.swift +++ b/native/ios-app/App/Stores/FireTopicDetailStore.swift @@ -54,7 +54,7 @@ final class FireTopicDetailStore: ObservableObject { func close(topicId: UInt64, ownerToken: String) { let key = handleKey(topicId: topicId, ownerToken: ownerToken) - handles.removeValue(forKey: key)?.close() + handles.removeValue(forKey: key)?.release() ownersByTopic[topicId]?.remove(ownerToken) if ownersByTopic[topicId]?.isEmpty != false { ownersByTopic[topicId] = nil @@ -98,7 +98,7 @@ final class FireTopicDetailStore: ObservableObject { let loggedOut = !session.readiness.hasLoginCookie && !session.readiness.hasCurrentUser if loggedOut { for handle in handles.values { - handle.close() + handle.release() } handles.removeAll() ownersByTopic.removeAll() diff --git a/native/ios-app/Fire.xcodeproj/project.pbxproj b/native/ios-app/Fire.xcodeproj/project.pbxproj index 931d9fc6..95dd7d6e 100644 --- a/native/ios-app/Fire.xcodeproj/project.pbxproj +++ b/native/ios-app/Fire.xcodeproj/project.pbxproj @@ -46,7 +46,6 @@ 256CB81681004BB26E0431B7 /* FireTopicDetailSharedModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = 925CD02F862E958CC79BC60A /* FireTopicDetailSharedModels.swift */; }; 2693C86EB9B8D438930E1B26 /* FireOnboardingValidatingView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A248DED21DCF11B55E331D29 /* FireOnboardingValidatingView.swift */; }; 2697DC8A389656A42CCEE78F /* Nuke in Frameworks */ = {isa = PBXBuildFile; productRef = 3F5DB59F34DC2099A84C0F6F /* Nuke */; }; - 26E51A13E796BFEF885FBD28 /* fire_uniffi_topics.swift in Sources */ = {isa = PBXBuildFile; fileRef = DDCE76B3F360C1C5631A950C /* fire_uniffi_topics.swift */; }; 26F6FF8DF720B6F46F3C5226 /* FireTopicDetailToolbarCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = DB73A3AE7A4D6E47C61CAE52 /* FireTopicDetailToolbarCoordinator.swift */; }; 27D3B7AADEF91C6DE3B41618 /* FireTopicEditorView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 577A99743CDCAA0033E2398C /* FireTopicEditorView.swift */; }; 27F8780AB48C65663BA8CF6A /* FireProfileActivityRow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 07E3386C6FC3093869C79E57 /* FireProfileActivityRow.swift */; }; @@ -67,7 +66,6 @@ 390219653B0C0A96C81D8962 /* FireAPMEventStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 373861687BBCD8EB8E350DA4 /* FireAPMEventStore.swift */; }; 3A20BD9A2A4CE944762B0BD7 /* FireReadHistoryViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C8AEE7516614D73C079F860 /* FireReadHistoryViewController.swift */; }; 3A339550AA3EE966F7EA50E5 /* FireProfileViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5DF67696B342C706CB3FAAFB /* FireProfileViewModel.swift */; }; - 3AFFAE192ADFE0FE4E054809 /* fire_uniffi_user.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F1F015314914FD74B56CC5D /* fire_uniffi_user.swift */; }; 3C9FA7D66DAA4DAE2B1BF45D /* FireProfileActivityTimelineView.swift in Sources */ = {isa = PBXBuildFile; fileRef = EFE429D39ACE68653A226FE9 /* FireProfileActivityTimelineView.swift */; }; 3CA9AF0BFA58C32834B441F3 /* FirePresentationIdentity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 019B4B93D3FDB4C799492775 /* FirePresentationIdentity.swift */; }; 3E37BA0BB7E0C48B9DAF40DE /* FireChatMessageCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 423DFD492305E9502EEFFCF9 /* FireChatMessageCell.swift */; }; @@ -85,7 +83,6 @@ 489C515305D468C608C7315D /* FirePostCellNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 093EEF1E0EBDB24ED7106CDD /* FirePostCellNode.swift */; }; 4E69EA800D7956E3C1989CFC /* FireCookieSelfHealingCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = C203C63EB7CB10843B8AB0EC /* FireCookieSelfHealingCoordinator.swift */; }; 4F0305B9162423D8D821A304 /* FireRouteParserTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 46C35F105D036EECAAE7B93D /* FireRouteParserTests.swift */; }; - 4F762CD9E7B43DB0534791C8 /* fire_uniffi.swift in Sources */ = {isa = PBXBuildFile; fileRef = EF98E1072E78DFC9F5057D67 /* fire_uniffi.swift */; }; 51D27C6354C43E1E83FEA3FB /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 6958AA64094FA7BB21B5FC36 /* PrivacyInfo.xcprivacy */; }; 522CA82334EAC05D23624720 /* FireTopicDetailModalViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8BC7B03BAACE572DDB87E810 /* FireTopicDetailModalViews.swift */; }; 52CF002705A0E18AAB2E9E62 /* FireTopicDetailRootNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = BEC29D6B75CD01B9ADD53F1A /* FireTopicDetailRootNode.swift */; }; @@ -133,17 +130,15 @@ 78009659A664B236D8AD3434 /* FireBadgeDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = BF5B6841F5556D86C606379F /* FireBadgeDetailView.swift */; }; 7848D667BF692B25B4194E57 /* FirePostCellLayoutCalculator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 24E7CCCA8B867D5E6B0CE198 /* FirePostCellLayoutCalculator.swift */; }; 790B44E436B0CF137B1FD8A7 /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E69013450F80AEC210D5512D /* Security.framework */; }; - 79B77A4E828C4862BE1BAA53 /* fire_uniffi_ldc.swift in Sources */ = {isa = PBXBuildFile; fileRef = A680E7A822BDD20CE84C04EE /* fire_uniffi_ldc.swift */; }; 7A0A8240B294336D5787C364 /* FirePublicProfileViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D23F3B2881A5E7C08D90A767 /* FirePublicProfileViewController.swift */; }; 7A1883792B3FD63EAEAA8336 /* SessionState+Helpers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3FC109FBAA1787EF49336258 /* SessionState+Helpers.swift */; }; 7A7A14663C8D777827CA6768 /* FireWidgetSnapshotWriter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E86F61501D5E51FA1584156 /* FireWidgetSnapshotWriter.swift */; }; 7B1B888CA814A35E5354CA0D /* FireHomeScopePresentation.swift in Sources */ = {isa = PBXBuildFile; fileRef = E355FDE3F6E9A5FFB6229374 /* FireHomeScopePresentation.swift */; }; 7B772557813420536690D938 /* FireAppViewModel+Diagnostics.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1F1F872C6062881E7513980D /* FireAppViewModel+Diagnostics.swift */; }; - 7C8E2507194A4B1C79F2BF4B /* fire_uniffi_session.swift in Sources */ = {isa = PBXBuildFile; fileRef = 48A7EA25CD5ADF94676BE48E /* fire_uniffi_session.swift */; }; 7CB85DA7DE5A93B262C29757 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 40B24CD54573A1C053B37121 /* PrivacyInfo.xcprivacy */; }; 7EFB42D38DCA6C0F63720AE3 /* FirePostCellNode+Reactions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A763199D74A1026B2ADB530 /* FirePostCellNode+Reactions.swift */; }; - 800930BED241B0CF61E5FD0A /* fire_uniffi_types.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0F09DBDDAC9BA75DCC865D23 /* fire_uniffi_types.swift */; }; 8146E8382FB40C8617EF19B7 /* FireWebViewCookieActionSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5103D4725A903220359B1C42 /* FireWebViewCookieActionSupportTests.swift */; }; + 8169E3FD365AE9F655517F7C /* FireTopicDetailArticleSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8928D817CE60A917A5BA0C9 /* FireTopicDetailArticleSnapshot.swift */; }; 816DB34CD28CD94ED88EF9C6 /* FirePaginatedStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D0D5E6727E0D21855DDEA2F /* FirePaginatedStore.swift */; }; 83C439B40A75418E1406961F /* FireTopicPresentation.swift in Sources */ = {isa = PBXBuildFile; fileRef = ECBDE8779B6F7E32204263F4 /* FireTopicPresentation.swift */; }; 8414458CE31AB953097CF014 /* FireSelectableRichTextNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = C08AC6976AD62C1DAB2DBB2F /* FireSelectableRichTextNode.swift */; }; @@ -161,7 +156,6 @@ 94474296599507819BE086D1 /* FireTopicDetailKeyboardLayoutTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 456ECA20E14DB2A1CB683621 /* FireTopicDetailKeyboardLayoutTests.swift */; }; 957DADCF16F936D3BCCDE7F5 /* FireAppServiceHost.swift in Sources */ = {isa = PBXBuildFile; fileRef = E083189F2BF692A04EB7CF23 /* FireAppServiceHost.swift */; }; 9726B24BBA832290EA063E8F /* libiconv.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = FD5A94769988E39B8BEA7B56 /* libiconv.tbd */; }; - 974A21358F0BAA6942E6FDFC /* fire_uniffi_messagebus.swift in Sources */ = {isa = PBXBuildFile; fileRef = E5B34317DAE5858951DCD928 /* fire_uniffi_messagebus.swift */; }; 9912E13751119248F5626F77 /* FireMainTabBarController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6CABC863F0E7DDEACF5B980D /* FireMainTabBarController.swift */; }; 997549C307522F353C2C4354 /* FireWebViewBrowserProfile.swift in Sources */ = {isa = PBXBuildFile; fileRef = E6A1ACC49B5E391857645187 /* FireWebViewBrowserProfile.swift */; }; 9B0DABDC5BA87A4CAFF3232D /* FireEntityStateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = BADC2ED47CF65AD5BE795908 /* FireEntityStateTests.swift */; }; @@ -169,14 +163,12 @@ 9E7B9F6741C79AF8E6C3D0DA /* FirePostLayoutManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A1B0239607F0ABAEA1ABCE0 /* FirePostLayoutManager.swift */; }; 9F734046F02B45409AD5F1C6 /* FireTopicListMessageBusRefreshTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 859219285EC36B189AF68256 /* FireTopicListMessageBusRefreshTests.swift */; }; A04B275253CDF8FAAC9D8C6C /* FireSearchStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 25FD219C2BFB0727FD0D3DD2 /* FireSearchStore.swift */; }; - A04F6299B25D5CC6C7D21B14 /* fire_uniffi_chat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 25741FA2801D3AD5A8DDD0C0 /* fire_uniffi_chat.swift */; }; A07A9808A87A0F9C08F72CC3 /* FireAccountStatusView.swift in Sources */ = {isa = PBXBuildFile; fileRef = FF475D56C78AFC82413AED55 /* FireAccountStatusView.swift */; }; A29E21413FA011161D518004 /* FireSessionStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8834ADE6E3ADB8A03391560C /* FireSessionStore.swift */; }; A2BA00121D5BF00E4543EF13 /* FireMotionEffects.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F51908C9A24B5866A517797 /* FireMotionEffects.swift */; }; A2C954EBAE5163E708B3F189 /* FirePostImageNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8092585A18BAFAC8ECAB670D /* FirePostImageNode.swift */; }; A2F884CB6FB920BCEA213B94 /* FireViewProfileIntent.swift in Sources */ = {isa = PBXBuildFile; fileRef = B680C9357B6A7ACD65F6B211 /* FireViewProfileIntent.swift */; }; A31CB94E768166B1D7907774 /* FireProfileHeaderComponents.swift in Sources */ = {isa = PBXBuildFile; fileRef = 631A4F82AE7302B3D139F94C /* FireProfileHeaderComponents.swift */; }; - A37D27214981E5D36E7DFD2C /* fire_uniffi_notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = FF89DCFCD77D9F81CD8DB801 /* fire_uniffi_notifications.swift */; }; A7657EA99808CEBE3F038176 /* CrashReporter in Frameworks */ = {isa = PBXBuildFile; productRef = 601B450FB4E87A5243FAE5F9 /* CrashReporter */; }; ABCB88B6D78156FB353E922B /* FireDiagnosticsViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2E4063863B8521F7719DD75F /* FireDiagnosticsViewModel.swift */; }; B0AA426C24E27249B4AE2E57 /* FireAppViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6C063DC3D3814082F9655534 /* FireAppViewModel.swift */; }; @@ -190,8 +182,8 @@ B9E25AF09D46C9889B98E8A2 /* FireComponents.swift in Sources */ = {isa = PBXBuildFile; fileRef = 24186C615A12A722B2ABEE06 /* FireComponents.swift */; }; BB4439D1D0537CEC232DF789 /* FireWidgetViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 06CDD24C8A021152FA0A67AE /* FireWidgetViews.swift */; }; BB6794B89B439C61B8A5620C /* FireFeedbackPresenter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F2E6EEDE9F6AACB5DBE9B79 /* FireFeedbackPresenter.swift */; }; + BBE9EB26A016A92092A4D0F2 /* FireTopicDetailPageSkeleton.swift in Sources */ = {isa = PBXBuildFile; fileRef = B3C653495E2307C802BB389A /* FireTopicDetailPageSkeleton.swift */; }; BD0F6BE28D1D0143383BAF2A /* FireProfileStatsRow.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8C1BF19AD44A73E451313B6 /* FireProfileStatsRow.swift */; }; - BD294B1545CC5167CAB3620E /* fire_uniffi_search.swift in Sources */ = {isa = PBXBuildFile; fileRef = C37B06D0B580C355652E1934 /* fire_uniffi_search.swift */; }; BDBF0CEBD8F5F7C1C19769B7 /* FireMessageBusCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0C11839708BD8C370EB52334 /* FireMessageBusCoordinator.swift */; }; BE531BCFF96A8C23E0180F6B /* FireLogDiagnosticsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 429B9F8B7087E197A8366D2D /* FireLogDiagnosticsView.swift */; }; BE820074BC6560ABBCF9BAFB /* SnapKit in Frameworks */ = {isa = PBXBuildFile; productRef = 92E5B8F5C5B099E404AB7A52 /* SnapKit */; }; @@ -220,6 +212,7 @@ D1A666B9F78D411F32B91FFC /* FireTextureAttributedTextTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 548ED4AC247F6D252A3A6FF9 /* FireTextureAttributedTextTests.swift */; }; D201FF0609323A45827C583F /* FireAutoLoginPlanner.swift in Sources */ = {isa = PBXBuildFile; fileRef = 99B66C15EE15F4C35AE369C7 /* FireAutoLoginPlanner.swift */; }; D2D1EA7C7D1208AEE0932A86 /* FireFollowListViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D5C18328DFF8C1C3145C2DAC /* FireFollowListViewController.swift */; }; + D668649DC871BC807613F946 /* FireTopicDetailCommentListSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1D0C004FB6FE17D6896FF17C /* FireTopicDetailCommentListSnapshot.swift */; }; D89E51A2B4024E06147DAEE7 /* FireShortcuts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 949B945E18FF2C7CF0F29CB4 /* FireShortcuts.swift */; }; D914CE5CE076533C2C932623 /* FirePushDiagnosticsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C710FF0F248498E25E02037D /* FirePushDiagnosticsView.swift */; }; DA3519D17B33A6FF56FAD600 /* FireDohSourceViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E4AF197F76705D49E465A05B /* FireDohSourceViewController.swift */; }; @@ -257,7 +250,6 @@ F3EE595ECC3F647D419D1833 /* FireSmallWidget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 44E64FAEF7CBC79DBC2491BB /* FireSmallWidget.swift */; }; F41EBD87EC59341D3A7DD381 /* FireOnboardingCredentialFormView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F112BF5A6A226C1D21861F90 /* FireOnboardingCredentialFormView.swift */; }; F4E23711C352DB67C48DDEDA /* FireUIKitSkeleton.swift in Sources */ = {isa = PBXBuildFile; fileRef = F45FD2D6B300FDC58C2FD04A /* FireUIKitSkeleton.swift */; }; - F53E86700CE39C9DD948CFF6 /* fire_uniffi_diagnostics.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1800DA0F94ED3D7B3099DB89 /* fire_uniffi_diagnostics.swift */; }; F6B73F0BFAB8573C89C89CCA /* FireTextureAttributedText.swift in Sources */ = {isa = PBXBuildFile; fileRef = 852D9E719DC6FE610CC4F084 /* FireTextureAttributedText.swift */; }; F6C8A1554FC2C48FB67706A3 /* FireChatViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5D9CBC157BF5867CEBE3B65B /* FireChatViewController.swift */; }; F7F1533B87EEF235D54BA201 /* FireAppRoutePresentationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0AE9014C1B335916BCACBC54 /* FireAppRoutePresentationTests.swift */; }; @@ -316,7 +308,6 @@ 0C933069DE6C026030AAB6EF /* FireTests.xctest */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.cfbundle; path = FireTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 0D70983A36756650D4B734B7 /* FirePostCellNode+Body.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FirePostCellNode+Body.swift"; sourceTree = ""; }; 0DB69FD096A581A18D9D16C5 /* Fire-Local-Release.example.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Fire-Local-Release.example.xcconfig"; sourceTree = ""; }; - 0F09DBDDAC9BA75DCC865D23 /* fire_uniffi_types.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = fire_uniffi_types.swift; sourceTree = ""; }; 0F45C6AFED397DB19D9A361E /* FireMessageBusCoordinatorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireMessageBusCoordinatorTests.swift; sourceTree = ""; }; 10DDE042BE2C24CFD782C785 /* FireTopicDetailStore+Reactions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailStore+Reactions.swift"; sourceTree = ""; }; 1127D7C4622ADFEED430046E /* FireExportDiagnosticsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireExportDiagnosticsView.swift; sourceTree = ""; }; @@ -325,7 +316,7 @@ 1481ACDF04D249FF61B1D0DF /* FireDeveloperToolsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireDeveloperToolsView.swift; sourceTree = ""; }; 149C3D9916D55374B1B4A37C /* FireAppRouteControllerFactory.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAppRouteControllerFactory.swift; sourceTree = ""; }; 151CF08DEE9DBAE7D98495AC /* FireTopicPostStateFixtures.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicPostStateFixtures.swift; sourceTree = ""; }; - 1800DA0F94ED3D7B3099DB89 /* fire_uniffi_diagnostics.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = fire_uniffi_diagnostics.swift; sourceTree = ""; }; + 1D0C004FB6FE17D6896FF17C /* FireTopicDetailCommentListSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailCommentListSnapshot.swift; sourceTree = ""; }; 1EDE93D07235A87438E6E563 /* FireRenderPresentation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireRenderPresentation.swift; sourceTree = ""; }; 1EF6B1D638EEA75C75B2B2D5 /* FirePostCellLayoutCalculatorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirePostCellLayoutCalculatorTests.swift; sourceTree = ""; }; 1F1F872C6062881E7513980D /* FireAppViewModel+Diagnostics.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireAppViewModel+Diagnostics.swift"; sourceTree = ""; }; @@ -336,7 +327,6 @@ 24186C615A12A722B2ABEE06 /* FireComponents.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireComponents.swift; sourceTree = ""; }; 242BD5DA9E84D24E217AFBBB /* FireNotificationPresentation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireNotificationPresentation.swift; sourceTree = ""; }; 24E7CCCA8B867D5E6B0CE198 /* FirePostCellLayoutCalculator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirePostCellLayoutCalculator.swift; sourceTree = ""; }; - 25741FA2801D3AD5A8DDD0C0 /* fire_uniffi_chat.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = fire_uniffi_chat.swift; sourceTree = ""; }; 25A9FA3A65196B334165E0C6 /* FireMotionUIKitTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireMotionUIKitTests.swift; sourceTree = ""; }; 25FD219C2BFB0727FD0D3DD2 /* FireSearchStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireSearchStore.swift; sourceTree = ""; }; 2641F70C8CEAE937D1D4A75D /* FireTopicDetailStore+Presence.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailStore+Presence.swift"; sourceTree = ""; }; @@ -383,7 +373,6 @@ 46CF09F1CBAC6CFAA0E9128A /* FireAppRoute.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAppRoute.swift; sourceTree = ""; }; 480E9E260E7348B77576F392 /* FireInlineReactionPickerScrollNode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireInlineReactionPickerScrollNode.swift; sourceTree = ""; }; 48153CE6A692130B4F8D97C5 /* FireHomeScopeChromeViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireHomeScopeChromeViews.swift; sourceTree = ""; }; - 48A7EA25CD5ADF94676BE48E /* fire_uniffi_session.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = fire_uniffi_session.swift; sourceTree = ""; }; 48CAB0E38556929FC140E25D /* Fire.app */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.application; path = Fire.app; sourceTree = BUILT_PRODUCTS_DIR; }; 49784F572BD41F7D9F024F55 /* FirePostFlagSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirePostFlagSheet.swift; sourceTree = ""; }; 4B2A79D53BB06F4FE60BE258 /* FireBottomInputBarTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireBottomInputBarTests.swift; sourceTree = ""; }; @@ -457,7 +446,6 @@ 9B970247E0258DD4D4F34101 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; 9D354D83C07C326288699E3D /* FireAppearanceEnvironment.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAppearanceEnvironment.swift; sourceTree = ""; }; 9E0BF86E469C2F6F845BBC27 /* FireWidgetEntry.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireWidgetEntry.swift; sourceTree = ""; }; - 9F1F015314914FD74B56CC5D /* fire_uniffi_user.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = fire_uniffi_user.swift; sourceTree = ""; }; 9F51908C9A24B5866A517797 /* FireMotionEffects.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireMotionEffects.swift; sourceTree = ""; }; A0AFFF5DCC989B801C9DF88E /* Fire-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Fire-Debug.xcconfig"; sourceTree = ""; }; A156E14A65C530B5582956CC /* FireRichTextRenderer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireRichTextRenderer.swift; sourceTree = ""; }; @@ -466,7 +454,6 @@ A283C548CFC6BEDC0D406679 /* FireTopicDetailVisibilityCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailVisibilityCoordinator.swift; sourceTree = ""; }; A5264103A412DF3C9798D470 /* FireAPMModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAPMModels.swift; sourceTree = ""; }; A67A6C835A2196246871D5FD /* FireComposerValidationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireComposerValidationTests.swift; sourceTree = ""; }; - A680E7A822BDD20CE84C04EE /* fire_uniffi_ldc.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = fire_uniffi_ldc.swift; sourceTree = ""; }; AA736A1F443337C34A6E33D6 /* Fire.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Fire.entitlements; sourceTree = ""; }; ABA36C072D3004B0CFDF73D3 /* FireCloudflareChallengeCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireCloudflareChallengeCoordinator.swift; sourceTree = ""; }; AD777ED45F66FF150D5AD9C0 /* FireBottomInputBar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireBottomInputBar.swift; sourceTree = ""; }; @@ -474,6 +461,7 @@ AFECA37BF8132D011E6B5506 /* FireHomeScopePresentationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireHomeScopePresentationTests.swift; sourceTree = ""; }; B17BF0CB4137B71949AACC0C /* FireSearchStoreTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireSearchStoreTests.swift; sourceTree = ""; }; B220305F1DFD0C508260CFA9 /* FirePostCellLayout.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirePostCellLayout.swift; sourceTree = ""; }; + B3C653495E2307C802BB389A /* FireTopicDetailPageSkeleton.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailPageSkeleton.swift; sourceTree = ""; }; B4F09B0F010E9C41B77F4B40 /* FireHomeScopePanelController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireHomeScopePanelController.swift; sourceTree = ""; }; B5619EAAFA6C1DCD6B3E1A15 /* FireMediumWidget.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireMediumWidget.swift; sourceTree = ""; }; B5E5271F93B7DF18859B101F /* FireWebViewLoginCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireWebViewLoginCoordinator.swift; sourceTree = ""; }; @@ -496,7 +484,6 @@ C20BDF82CCD1BF22BB3C7729 /* FireAPMMainThreadStallMonitor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAPMMainThreadStallMonitor.swift; sourceTree = ""; }; C313FFDD8D569FA6D9B1C0E0 /* FireAuthCookieKeychainStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAuthCookieKeychainStore.swift; sourceTree = ""; }; C32FFB215F2C0CDDE5C1221C /* FireTopicOneboxNode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicOneboxNode.swift; sourceTree = ""; }; - C37B06D0B580C355652E1934 /* fire_uniffi_search.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = fire_uniffi_search.swift; sourceTree = ""; }; C3ECAD5FF1893C381DB94E34 /* FireSettingsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireSettingsViewController.swift; sourceTree = ""; }; C65C6A52FE7362DF04A8445B /* FireRichTextHeightConsistencyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireRichTextHeightConsistencyTests.swift; sourceTree = ""; }; C6DEF53357E681E40E482813 /* FireAPMResourceSampler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAPMResourceSampler.swift; sourceTree = ""; }; @@ -517,7 +504,6 @@ DC543177753C32906EE6BE24 /* FireHomeView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireHomeView.swift; sourceTree = ""; }; DCE4042C9DCEB3DD3BEC7892 /* FirePrivateMessagesView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirePrivateMessagesView.swift; sourceTree = ""; }; DDC30347DC7392AAA6A27435 /* FireTopicDetailControllerHost.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailControllerHost.swift; sourceTree = ""; }; - DDCE76B3F360C1C5631A950C /* fire_uniffi_topics.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = fire_uniffi_topics.swift; sourceTree = ""; }; DFBA718C5E89D3669A9C6D22 /* FireTopicDetailStoreTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailStoreTests.swift; sourceTree = ""; }; E083189F2BF692A04EB7CF23 /* FireAppServiceHost.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAppServiceHost.swift; sourceTree = ""; }; E0AA3F1257384BF109634D21 /* FireTheme.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTheme.swift; sourceTree = ""; }; @@ -526,7 +512,6 @@ E436AB70851CCBCFCD8B8D96 /* FireTopicDetailInteractionCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailInteractionCoordinator.swift; sourceTree = ""; }; E4616E00DD2F43C18973E520 /* FireUIKitErrorBannerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireUIKitErrorBannerView.swift; sourceTree = ""; }; E4AF197F76705D49E465A05B /* FireDohSourceViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireDohSourceViewController.swift; sourceTree = ""; }; - E5B34317DAE5858951DCD928 /* fire_uniffi_messagebus.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = fire_uniffi_messagebus.swift; sourceTree = ""; }; E5FFB93F34563ABE34B99183 /* FireUIKitDesignLanguage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireUIKitDesignLanguage.swift; sourceTree = ""; }; E650ABD9C06621BC41908D59 /* FireContextMenus.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireContextMenus.swift; sourceTree = ""; }; E66E1B11B9D76557B4BB0603 /* FireTopicListMessageBusRefresh.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicListMessageBusRefresh.swift; sourceTree = ""; }; @@ -543,7 +528,6 @@ ECBDE8779B6F7E32204263F4 /* FireTopicPresentation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicPresentation.swift; sourceTree = ""; }; EDE93F98F58126B7BEDDB4F7 /* FireTopicTimingTrackerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicTimingTrackerTests.swift; sourceTree = ""; }; EF66373F7EF72A887F722CF0 /* FireMotionUIKit.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireMotionUIKit.swift; sourceTree = ""; }; - EF98E1072E78DFC9F5057D67 /* fire_uniffi.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = fire_uniffi.swift; sourceTree = ""; }; EFE429D39ACE68653A226FE9 /* FireProfileActivityTimelineView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireProfileActivityTimelineView.swift; sourceTree = ""; }; F01E5248AEF9002E2919AC0F /* FireCfClearanceRefreshService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireCfClearanceRefreshService.swift; sourceTree = ""; }; F112BF5A6A226C1D21861F90 /* FireOnboardingCredentialFormView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireOnboardingCredentialFormView.swift; sourceTree = ""; }; @@ -551,6 +535,7 @@ F74563DD6B9E870850553DDA /* FireAppViewModel+Profile.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireAppViewModel+Profile.swift"; sourceTree = ""; }; F7C061876458A31F793EE975 /* FireWebViewBrowserViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireWebViewBrowserViewController.swift; sourceTree = ""; }; F7F4881067D974AA645C77FC /* FireWidgetExtension.appex */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = "wrapper.app-extension"; path = FireWidgetExtension.appex; sourceTree = BUILT_PRODUCTS_DIR; }; + F8928D817CE60A917A5BA0C9 /* FireTopicDetailArticleSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailArticleSnapshot.swift; sourceTree = ""; }; F90878A611124AD41C0288B7 /* FireTopicDetailModalRouter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailModalRouter.swift; sourceTree = ""; }; F9384B4FECD3434E8DCCB3BA /* FireFilteredTopicListView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireFilteredTopicListView.swift; sourceTree = ""; }; FA8E7753E3E1BB8E3CD88E96 /* Fire-Shared.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Fire-Shared.xcconfig"; sourceTree = ""; }; @@ -558,7 +543,6 @@ FB21BB9232240035114A9653 /* FireProfileBadgeChip.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireProfileBadgeChip.swift; sourceTree = ""; }; FD5A94769988E39B8BEA7B56 /* libiconv.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libiconv.tbd; path = usr/lib/libiconv.tbd; sourceTree = SDKROOT; }; FF475D56C78AFC82413AED55 /* FireAccountStatusView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAccountStatusView.swift; sourceTree = ""; }; - FF89DCFCD77D9F81CD8DB801 /* fire_uniffi_notifications.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = fire_uniffi_notifications.swift; sourceTree = ""; }; FFB6B1F10783D1D78B2D1F63 /* FireListSectionModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireListSectionModel.swift; sourceTree = ""; }; /* End PBXFileReference section */ @@ -725,6 +709,14 @@ path = APM; sourceTree = ""; }; + 432B61BE05D9E5BC2CC09D19 /* Shell */ = { + isa = PBXGroup; + children = ( + B3C653495E2307C802BB389A /* FireTopicDetailPageSkeleton.swift */, + ); + path = Shell; + sourceTree = ""; + }; 5490C8448BFCBD09FDBC1287 /* DeveloperTools */ = { isa = PBXGroup; children = ( @@ -768,6 +760,14 @@ path = State; sourceTree = ""; }; + 5F657D2B6414BE9FDC38DE3B /* Comments */ = { + isa = PBXGroup; + children = ( + 1D0C004FB6FE17D6896FF17C /* FireTopicDetailCommentListSnapshot.swift */, + ); + path = Comments; + sourceTree = ""; + }; 5F7AA7499A2F1D712BD81C5A /* Feedback */ = { isa = PBXGroup; children = ( @@ -974,7 +974,6 @@ 73EB36381D2DB9DA74378162 /* App */, BD212BBA5E9DA62F41FF41F4 /* Configs */, 32338F9E71B0E67C5112C300 /* FireAppSession */, - F6A48714E0F87937027A25E4 /* FireUniFfi */, 7044DC07E4881033F1BC8F64 /* FireWidget */, 8FCD2C1B029D07F4C1B82746 /* Unit */, 9C9371C0E9747855874B64BD /* Widgets */, @@ -1101,10 +1100,13 @@ CEBB259DDDBA31DF0CA406A9 /* TopicDetail */ = { isa = PBXGroup; children = ( + E576A1F6733B5D50E3718FD8 /* Article */, + 5F657D2B6414BE9FDC38DE3B /* Comments */, 2CF8A481ECB4FF480F527B2C /* Controller */, 9104AB2B5E8F79AB50DBDAA1 /* Feed */, 2607C3DFEA87D8037E7D8539 /* Host */, 1D4EA522AEB920803774F33C /* Nodes */, + 432B61BE05D9E5BC2CC09D19 /* Shell */, 5BA314EE5B2BBD55F0914150 /* State */, AC8A5608257313F526A24227 /* Support */, ); @@ -1172,6 +1174,14 @@ name = Frameworks; sourceTree = ""; }; + E576A1F6733B5D50E3718FD8 /* Article */ = { + isa = PBXGroup; + children = ( + F8928D817CE60A917A5BA0C9 /* FireTopicDetailArticleSnapshot.swift */, + ); + path = Article; + sourceTree = ""; + }; E6FFE443DA18651279314100 /* Composer */ = { isa = PBXGroup; children = ( @@ -1202,25 +1212,6 @@ path = Core; sourceTree = ""; }; - F6A48714E0F87937027A25E4 /* FireUniFfi */ = { - isa = PBXGroup; - children = ( - 25741FA2801D3AD5A8DDD0C0 /* fire_uniffi_chat.swift */, - 1800DA0F94ED3D7B3099DB89 /* fire_uniffi_diagnostics.swift */, - A680E7A822BDD20CE84C04EE /* fire_uniffi_ldc.swift */, - E5B34317DAE5858951DCD928 /* fire_uniffi_messagebus.swift */, - FF89DCFCD77D9F81CD8DB801 /* fire_uniffi_notifications.swift */, - C37B06D0B580C355652E1934 /* fire_uniffi_search.swift */, - 48A7EA25CD5ADF94676BE48E /* fire_uniffi_session.swift */, - DDCE76B3F360C1C5631A950C /* fire_uniffi_topics.swift */, - 0F09DBDDAC9BA75DCC865D23 /* fire_uniffi_types.swift */, - 9F1F015314914FD74B56CC5D /* fire_uniffi_user.swift */, - EF98E1072E78DFC9F5057D67 /* fire_uniffi.swift */, - ); - name = FireUniFfi; - path = Generated/FireUniFfi; - sourceTree = ""; - }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -1588,6 +1579,8 @@ 0738F9AD86263ECE2016A8D4 /* FireTagPickerSheet.swift in Sources */, F6B73F0BFAB8573C89C89CCA /* FireTextureAttributedText.swift in Sources */, 09DEF34E484D68FE6A3A1AC5 /* FireTheme.swift in Sources */, + 8169E3FD365AE9F655517F7C /* FireTopicDetailArticleSnapshot.swift in Sources */, + D668649DC871BC807613F946 /* FireTopicDetailCommentListSnapshot.swift in Sources */, 04AB0C15F52072F2E720E47F /* FireTopicDetailControllerHost.swift in Sources */, E38E8CABB24B1AD415D69203 /* FireTopicDetailFeedCellFactory.swift in Sources */, B7784C41CA7002BF3223029B /* FireTopicDetailFeedCells.swift in Sources */, @@ -1597,6 +1590,7 @@ CE0D834262ED55561F6BC409 /* FireTopicDetailInteractionCoordinator.swift in Sources */, 24F82A793D9593417C1E59EA /* FireTopicDetailModalRouter.swift in Sources */, 522CA82334EAC05D23624720 /* FireTopicDetailModalViews.swift in Sources */, + BBE9EB26A016A92092A4D0F2 /* FireTopicDetailPageSkeleton.swift in Sources */, 6C52C8A80C6D33CEEF5F6B18 /* FireTopicDetailPageSnapshot.swift in Sources */, F25C8C5E91D29F5BEDB35E9A /* FireTopicDetailPageState.swift in Sources */, E5268113A96209626BB13FEA /* FireTopicDetailPaginationCoordinator.swift in Sources */, @@ -1639,17 +1633,6 @@ 0829CF9A9EE33EA119F94468 /* FireWidgetData.swift in Sources */, 7A7A14663C8D777827CA6768 /* FireWidgetSnapshotWriter.swift in Sources */, 7A1883792B3FD63EAEAA8336 /* SessionState+Helpers.swift in Sources */, - 4F762CD9E7B43DB0534791C8 /* fire_uniffi.swift in Sources */, - A04F6299B25D5CC6C7D21B14 /* fire_uniffi_chat.swift in Sources */, - F53E86700CE39C9DD948CFF6 /* fire_uniffi_diagnostics.swift in Sources */, - 79B77A4E828C4862BE1BAA53 /* fire_uniffi_ldc.swift in Sources */, - 974A21358F0BAA6942E6FDFC /* fire_uniffi_messagebus.swift in Sources */, - A37D27214981E5D36E7DFD2C /* fire_uniffi_notifications.swift in Sources */, - BD294B1545CC5167CAB3620E /* fire_uniffi_search.swift in Sources */, - 7C8E2507194A4B1C79F2BF4B /* fire_uniffi_session.swift in Sources */, - 26E51A13E796BFEF885FBD28 /* fire_uniffi_topics.swift in Sources */, - 800930BED241B0CF61E5FD0A /* fire_uniffi_types.swift in Sources */, - 3AFFAE192ADFE0FE4E054809 /* fire_uniffi_user.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/rust/crates/fire-core/src/core/messagebus/channels.rs b/rust/crates/fire-core/src/core/messagebus/channels.rs index c5a5e248..8570ede7 100644 --- a/rust/crates/fire-core/src/core/messagebus/channels.rs +++ b/rust/crates/fire-core/src/core/messagebus/channels.rs @@ -1,10 +1,6 @@ -use std::sync::{ - Arc, Mutex, - }; +use std::sync::{Arc, Mutex}; -use fire_models::{ - MessageBusClientMode, NotificationAlert, TopicListKind, -}; +use fire_models::{MessageBusClientMode, NotificationAlert, TopicListKind}; use serde_json::Value; use super::runtime::client_id_for_mode; @@ -69,7 +65,6 @@ pub(super) fn notification_alert_from_raw(message: &RawMessageBusMessage) -> Not } } - pub(super) fn topic_list_kind_for_channel(channel: &str) -> Option { match channel { "/latest" => Some(TopicListKind::Latest), diff --git a/rust/crates/fire-core/src/core/messagebus/mod.rs b/rust/crates/fire-core/src/core/messagebus/mod.rs index 3894ae6f..fabc3163 100644 --- a/rust/crates/fire-core/src/core/messagebus/mod.rs +++ b/rust/crates/fire-core/src/core/messagebus/mod.rs @@ -1,15 +1,10 @@ use std::{ collections::BTreeMap, - sync::{ - atomic::AtomicU64, - Arc, Mutex, RwLock, - }, + sync::{atomic::AtomicU64, Arc, Mutex, RwLock}, time::Duration, }; -use fire_models::{ - MessageBusClientMode, MessageBusEvent, MessageBusSubscriptionScope, -}; +use fire_models::{MessageBusClientMode, MessageBusEvent, MessageBusSubscriptionScope}; use serde_json::Value; use tokio::{ runtime::Handle, @@ -19,10 +14,8 @@ use tokio::{ use url::Url; use super::{ - network::FireNetworkLayer, - notifications::FireNotificationRuntime, - presence::FireTopicPresenceRuntime, - FireCore, FireSessionRuntimeState, + network::FireNetworkLayer, notifications::FireNotificationRuntime, + presence::FireTopicPresenceRuntime, FireCore, FireSessionRuntimeState, }; use crate::diagnostics::FireDiagnosticsStore; @@ -101,7 +94,6 @@ struct RawMessageBusMessage { data: Value, } - mod channels; mod parse; mod poll; diff --git a/rust/crates/fire-core/src/core/messagebus/parse.rs b/rust/crates/fire-core/src/core/messagebus/parse.rs index 395531ec..24f746c3 100644 --- a/rust/crates/fire-core/src/core/messagebus/parse.rs +++ b/rust/crates/fire-core/src/core/messagebus/parse.rs @@ -1,10 +1,6 @@ -use std::sync::{ - Arc, Mutex, - }; +use std::sync::{Arc, Mutex}; -use fire_models::{ - MessageBusEvent, MessageBusEventKind, -}; +use fire_models::{MessageBusEvent, MessageBusEventKind}; use serde_json::Value; use tracing::warn; @@ -248,4 +244,3 @@ pub(super) fn message_bus_event_from_raw(message: &RawMessageBusMessage) -> Mess ..MessageBusEvent::default() } } - diff --git a/rust/crates/fire-core/src/core/messagebus/poll.rs b/rust/crates/fire-core/src/core/messagebus/poll.rs index 25b237fe..146fec24 100644 --- a/rust/crates/fire-core/src/core/messagebus/poll.rs +++ b/rust/crates/fire-core/src/core/messagebus/poll.rs @@ -1,11 +1,8 @@ -use std::sync::{ - atomic::Ordering, - Arc, - }; +use std::sync::{atomic::Ordering, Arc}; use fire_models::{ - MessageBusClientMode, MessageBusEvent, MessageBusEventKind, - NotificationAlertPollResult, SessionSnapshot, + MessageBusClientMode, MessageBusEvent, MessageBusEventKind, NotificationAlertPollResult, + SessionSnapshot, }; use http::{Method, Request, Response}; use http_body_util::BodyExt; @@ -29,9 +26,7 @@ use super::super::{ }; use super::*; use crate::{ - diagnostics::FireDiagnosticsStore, - error::FireCoreError, - json_helpers::integer_i64, + diagnostics::FireDiagnosticsStore, error::FireCoreError, json_helpers::integer_i64, sync_utils::read_rwlock, }; @@ -546,7 +541,10 @@ pub(super) fn process_notification_alert_chunk( } } -pub(super) fn process_chunk(context: &MessageBusPollContext, chunk: &str) -> Result { +pub(super) fn process_chunk( + context: &MessageBusPollContext, + chunk: &str, +) -> Result { let Some(messages) = parse_message_bus_messages(chunk, &context.client_id, "message bus") else { return Ok(true); @@ -612,7 +610,6 @@ pub(super) fn process_chunk(context: &MessageBusPollContext, chunk: &str) -> Res Ok(true) } - #[cfg(test)] mod tests { use openwire::WireError; diff --git a/rust/crates/fire-core/src/core/messagebus/runtime.rs b/rust/crates/fire-core/src/core/messagebus/runtime.rs index 652995a1..2fb7449a 100644 --- a/rust/crates/fire-core/src/core/messagebus/runtime.rs +++ b/rust/crates/fire-core/src/core/messagebus/runtime.rs @@ -1,18 +1,13 @@ use std::{ collections::{BTreeMap, HashMap}, - sync::{ - atomic::Ordering, - Arc, Mutex, - }, + sync::{atomic::Ordering, Arc, Mutex}, time::{Duration, SystemTime, UNIX_EPOCH}, }; use fire_models::{ - BootstrapArtifacts, MessageBusClientMode, MessageBusEvent, - MessageBusSubscription, MessageBusSubscriptionScope, - NotificationAlertPollResult, + BootstrapArtifacts, MessageBusClientMode, MessageBusEvent, MessageBusSubscription, + MessageBusSubscriptionScope, NotificationAlertPollResult, }; -use http_body_util::BodyExt; use openwire::WireErrorKind; use serde_json::Value; use tokio::{ @@ -23,20 +18,14 @@ use tracing::{debug, info, warn}; use url::Url; use super::super::{ - network::{ - request_origin, - FireCallProfile, - }, + network::{request_origin, FireCallProfile}, presence::clear_topic_presence_snapshot, FireCore, }; use super::channels::*; use super::poll::*; use super::*; -use crate::{ - error::FireCoreError, - json_helpers::integer_i64, -}; +use crate::{error::FireCoreError, json_helpers::integer_i64}; impl FireCore { pub fn subscribe_message_bus_channel( @@ -181,19 +170,15 @@ impl FireCore { .message_bus .lock() .expect("message bus runtime lock poisoned"); - runtime.next_internal_listener_id = runtime - .next_internal_listener_id - .saturating_add(1) - .max(1); + runtime.next_internal_listener_id = + runtime.next_internal_listener_id.saturating_add(1).max(1); let id = runtime.next_internal_listener_id; - runtime - .internal_listeners - .push(MessageBusInternalListener { - id, - on_event, - on_stopped, - on_started, - }); + runtime.internal_listeners.push(MessageBusInternalListener { + id, + on_event, + on_stopped, + on_started, + }); id } @@ -274,7 +259,6 @@ impl FireCore { } } - fn ensure_bootstrap_subscriptions( bootstrap: &BootstrapArtifacts, runtime: &mut FireMessageBusRuntime, @@ -320,7 +304,9 @@ fn ensure_bootstrap_subscriptions( changed } -pub(super) fn bootstrap_tracking_subscriptions(bootstrap: &BootstrapArtifacts) -> Vec<(String, i64)> { +pub(super) fn bootstrap_tracking_subscriptions( + bootstrap: &BootstrapArtifacts, +) -> Vec<(String, i64)> { let Some(raw) = bootstrap.topic_tracking_state_meta.as_deref() else { return Vec::new(); }; @@ -362,7 +348,10 @@ pub(super) fn apply_topic_tracking_state_meta( changed } -pub(super) fn bootstrap_message_id_for_channel(bootstrap: &BootstrapArtifacts, channel: &str) -> Option { +pub(super) fn bootstrap_message_id_for_channel( + bootstrap: &BootstrapArtifacts, + channel: &str, +) -> Option { if let Some(notification_channel) = bootstrap_notification_channel(bootstrap) { if notification_channel.0 == channel { return Some(notification_channel.1); @@ -376,14 +365,19 @@ pub(super) fn bootstrap_message_id_for_channel(bootstrap: &BootstrapArtifacts, c }) } -pub(super) fn bootstrap_notification_channel(bootstrap: &BootstrapArtifacts) -> Option<(String, i64)> { +pub(super) fn bootstrap_notification_channel( + bootstrap: &BootstrapArtifacts, +) -> Option<(String, i64)> { Some(( format!("/notification/{}", bootstrap.current_user_id?), bootstrap.notification_channel_position?, )) } -pub(super) fn client_id_for_mode(runtime: &mut FireMessageBusRuntime, mode: MessageBusClientMode) -> String { +pub(super) fn client_id_for_mode( + runtime: &mut FireMessageBusRuntime, + mode: MessageBusClientMode, +) -> String { match mode { MessageBusClientMode::Foreground => runtime .foreground_client_id @@ -482,7 +476,9 @@ pub(super) fn mark_subscriptions_changed(runtime: &mut FireMessageBusRuntime) { } } -pub(super) fn subscription_updates_receiver(runtime: &mut FireMessageBusRuntime) -> watch::Receiver { +pub(super) fn subscription_updates_receiver( + runtime: &mut FireMessageBusRuntime, +) -> watch::Receiver { if let Some(sender) = &runtime.subscription_updates { sender.subscribe() } else { diff --git a/rust/crates/fire-core/src/core/mod.rs b/rust/crates/fire-core/src/core/mod.rs index 57908853..986a5620 100644 --- a/rust/crates/fire-core/src/core/mod.rs +++ b/rust/crates/fire-core/src/core/mod.rs @@ -17,8 +17,8 @@ mod presence; mod rate_limit; mod search; mod session; -mod topic_detail_project; mod topic_detail; +mod topic_detail_project; mod topics; mod users; diff --git a/rust/crates/fire-core/src/core/topic_detail/actor.rs b/rust/crates/fire-core/src/core/topic_detail/actor.rs index dc725daa..31e71912 100644 --- a/rust/crates/fire-core/src/core/topic_detail/actor.rs +++ b/rust/crates/fire-core/src/core/topic_detail/actor.rs @@ -4,8 +4,8 @@ use fire_models::TopicDetailPhase; use tokio::sync::mpsc; use super::super::FireCore; -use super::*; use super::bus::presence_channel; +use super::*; impl ActorState { pub(super) fn new(topic_id: u64) -> Self { @@ -82,14 +82,15 @@ impl ActorState { Command::CancelHttp => { self.http_epoch = self.http_epoch.saturating_add(1); self.refresh_inflight = false; - if self.phase == TopicDetailPhase::Loading { - if self.published.as_ref().is_some_and(|snapshot| { - snapshot.phase == TopicDetailPhase::Ready - }) { - self.phase = TopicDetailPhase::Ready; - self.load_error = None; - self.publish(core, false); - } + if self.phase == TopicDetailPhase::Loading + && self + .published + .as_ref() + .is_some_and(|snapshot| snapshot.phase == TopicDetailPhase::Ready) + { + self.phase = TopicDetailPhase::Ready; + self.load_error = None; + self.publish(core, false); } } Command::Reload { @@ -146,7 +147,7 @@ impl ActorState { match std::mem::replace(&mut self.deferred, DeferredRefresh::None) { DeferredRefresh::Ready(snapshot) => { self.defer_publish = false; - self.publish_snapshot(core, snapshot); + self.publish_snapshot(core, *snapshot); } DeferredRefresh::Pending => { self.arm_refresh(tx); @@ -182,9 +183,7 @@ impl ActorState { } Command::EndTyping => { self.typing = false; - let _ = core - .update_topic_reply_presence(self.topic_id, false) - .await; + let _ = core.update_topic_reply_presence(self.topic_id, false).await; let _ = core.unsubscribe_message_bus_channel( self.bus_owner(), presence_channel(self.topic_id), @@ -193,9 +192,7 @@ impl ActorState { } Command::PresenceHeartbeat => { if self.typing { - let _ = core - .update_topic_reply_presence(self.topic_id, true) - .await; + let _ = core.update_topic_reply_presence(self.topic_id, true).await; let tx = tx.clone(); tokio::spawn(async move { tokio::time::sleep(TOPIC_DETAIL_PRESENCE_HEARTBEAT).await; @@ -254,7 +251,11 @@ impl ActorState { .await, ); } - Command::CreateBoost { post_id, raw, reply } => { + Command::CreateBoost { + post_id, + raw, + reply, + } => { let _ = reply.send(self.create_boost(core, tx, post_id, raw).await); } Command::DeleteBoost { @@ -400,8 +401,6 @@ impl ActorState { } true } - - } pub(super) async fn run_actor( diff --git a/rust/crates/fire-core/src/core/topic_detail/bus.rs b/rust/crates/fire-core/src/core/topic_detail/bus.rs index fe4a1f9f..ca5e0963 100644 --- a/rust/crates/fire-core/src/core/topic_detail/bus.rs +++ b/rust/crates/fire-core/src/core/topic_detail/bus.rs @@ -1,8 +1,7 @@ use std::sync::Arc; use fire_models::{ - MessageBusEvent, MessageBusEventKind, MessageBusSubscription, - MessageBusSubscriptionScope, + MessageBusEvent, MessageBusEventKind, MessageBusSubscription, MessageBusSubscriptionScope, }; use tokio::sync::mpsc; @@ -20,7 +19,11 @@ impl ActorState { }); } - pub(super) fn install_bus_listener(&mut self, core: &FireCore, tx: mpsc::UnboundedSender) { + pub(super) fn install_bus_listener( + &mut self, + core: &FireCore, + tx: mpsc::UnboundedSender, + ) { let topic_id = self.topic_id; let on_event_tx = tx.clone(); let on_started_tx = tx; @@ -98,8 +101,6 @@ impl ActorState { self.typing_users = core.topic_reply_presence_state(self.topic_id).users; self.publish(core, false); } - - } pub(super) fn event_matches_topic(event: &MessageBusEvent, topic_id: u64) -> bool { diff --git a/rust/crates/fire-core/src/core/topic_detail/load.rs b/rust/crates/fire-core/src/core/topic_detail/load.rs index 6dd64230..e724f0da 100644 --- a/rust/crates/fire-core/src/core/topic_detail/load.rs +++ b/rust/crates/fire-core/src/core/topic_detail/load.rs @@ -1,15 +1,11 @@ use std::collections::HashSet; use fire_models::{ - LoadMoreTopicPostsQuery, - TopicDetailLoadError, TopicDetailPhase, TopicDetailSourceQuery, + LoadMoreTopicPostsQuery, TopicDetailLoadError, TopicDetailPhase, TopicDetailSourceQuery, }; use tokio::sync::mpsc; -use super::super::topics::{ - load_more_topic_detail_posts, - load_topic_detail_page, -}; +use super::super::topics::{load_more_topic_detail_posts, load_topic_detail_page}; use super::super::FireCore; use super::*; use crate::error::FireCoreError; @@ -47,6 +43,7 @@ impl ActorState { .await; } + #[allow(clippy::too_many_arguments)] pub(super) async fn load_http( &mut self, core: &FireCore, @@ -92,7 +89,7 @@ impl ActorState { self.subscribe_channels(core); if self.defer_publish && self.scroll_active { let snapshot = self.make_snapshot(core); - self.deferred = DeferredRefresh::Ready(snapshot); + self.deferred = DeferredRefresh::Ready(Box::new(snapshot)); self.defer_publish = false; } else { self.defer_publish = false; @@ -226,8 +223,6 @@ impl ActorState { } self.publish(core, false); } - - } fn actor_query( diff --git a/rust/crates/fire-core/src/core/topic_detail/mod.rs b/rust/crates/fire-core/src/core/topic_detail/mod.rs index 00b6826e..d5326a05 100644 --- a/rust/crates/fire-core/src/core/topic_detail/mod.rs +++ b/rust/crates/fire-core/src/core/topic_detail/mod.rs @@ -6,10 +6,8 @@ use std::{ }; use fire_models::{ - PostActionType, TopicAiSummary, - TopicDetailLoadError, TopicDetailPhase, - TopicDetailUiSnapshot, TopicHeader, TopicPost, - TopicPresenceUser, + PostActionType, TopicAiSummary, TopicDetailLoadError, TopicDetailPhase, TopicDetailUiSnapshot, + TopicHeader, TopicPost, TopicPresenceUser, }; use tokio::sync::oneshot; @@ -50,7 +48,7 @@ pub trait TopicDetailObserver: Send + Sync { enum DeferredRefresh { None, Pending, - Ready(TopicDetailUiSnapshot), + Ready(Box), } struct TopicWindow { diff --git a/rust/crates/fire-core/src/core/topic_detail/mutations.rs b/rust/crates/fire-core/src/core/topic_detail/mutations.rs index df9285a3..6d91562d 100644 --- a/rust/crates/fire-core/src/core/topic_detail/mutations.rs +++ b/rust/crates/fire-core/src/core/topic_detail/mutations.rs @@ -1,7 +1,4 @@ - -use fire_models::{ - TopicReplyRequest, TopicUpdateRequest, -}; +use fire_models::{TopicReplyRequest, TopicUpdateRequest}; use tokio::sync::mpsc; use super::super::FireCore; @@ -181,7 +178,6 @@ impl ActorState { Ok(()) } - pub(super) async fn vote_poll( &mut self, core: &FireCore, @@ -264,6 +260,7 @@ impl ActorState { Ok(()) } + #[allow(clippy::too_many_arguments)] pub(super) async fn create_bookmark( &mut self, core: &FireCore, @@ -444,6 +441,4 @@ impl ActorState { .await; Ok(()) } - - } diff --git a/rust/crates/fire-core/src/core/topic_detail/publish.rs b/rust/crates/fire-core/src/core/topic_detail/publish.rs index 75256d99..0b5a8648 100644 --- a/rust/crates/fire-core/src/core/topic_detail/publish.rs +++ b/rust/crates/fire-core/src/core/topic_detail/publish.rs @@ -1,14 +1,13 @@ use std::panic::{self, AssertUnwindSafe}; use fire_models::{ - TopicDetailSourceSnapshot, - TopicDetailUiSnapshot, TopicHeader, TopicTreePresentation, + TopicDetailSourceSnapshot, TopicDetailUiSnapshot, TopicHeader, TopicTreePresentation, }; use super::super::topic_detail_project::{ - chrome_fields_changed, header_counts_changed, - home_row_patch_for_header, interaction_checksums_changed, layout_checksums_changed, project_topic_detail_snapshot, sidecar_changed, structure_changed, - ProjectionChrome, + chrome_fields_changed, header_counts_changed, home_row_patch_for_header, + interaction_checksums_changed, layout_checksums_changed, project_topic_detail_snapshot, + sidecar_changed, structure_changed, ProjectionChrome, }; use super::super::topics::build_topic_tree_presentation_from_source_snapshot; use super::super::FireCore; @@ -20,7 +19,7 @@ impl ActorState { if self.defer_publish && self.scroll_active { let mut snapshot = self.make_snapshot(core); self.assign_revisions(&mut snapshot); - self.deferred = DeferredRefresh::Ready(snapshot); + self.deferred = DeferredRefresh::Ready(Box::new(snapshot)); return; } let mut snapshot = self.make_snapshot(core); @@ -130,7 +129,6 @@ impl ActorState { project_topic_detail_snapshot(&source, &tree, &chrome) } - pub(super) fn projection_chrome(&self, core: &FireCore) -> ProjectionChrome { ProjectionChrome { phase: self.phase, @@ -157,5 +155,4 @@ impl ActorState { interaction_revision: self.interaction_revision, } } - } diff --git a/rust/crates/fire-core/src/core/topic_detail/reactions.rs b/rust/crates/fire-core/src/core/topic_detail/reactions.rs index 1cb799a2..ff904003 100644 --- a/rust/crates/fire-core/src/core/topic_detail/reactions.rs +++ b/rust/crates/fire-core/src/core/topic_detail/reactions.rs @@ -1,4 +1,3 @@ - use tokio::sync::mpsc; use super::super::FireCore; @@ -52,9 +51,11 @@ impl ActorState { reaction_id: String, ) -> Result<(), FireCoreError> { let current = core.with_topic_source_session_mut(self.topic_id, None, |session| { - session - .post(post_id) - .and_then(|post| post.current_user_reaction.as_ref().map(|reaction| reaction.id.clone())) + session.post(post_id).and_then(|post| { + post.current_user_reaction + .as_ref() + .map(|reaction| reaction.id.clone()) + }) }); let desired = match current.flatten() { Some(current) if current == reaction_id => None, @@ -153,11 +154,13 @@ impl ActorState { self.mutating.remove(&post_id); self.publish(core, false); } - - } -fn adjust_reaction_count(reactions: &mut Vec, id: Option<&str>, delta: i32) { +fn adjust_reaction_count( + reactions: &mut Vec, + id: Option<&str>, + delta: i32, +) { let Some(id) = id else { return; }; diff --git a/rust/crates/fire-core/src/core/topic_detail/registry.rs b/rust/crates/fire-core/src/core/topic_detail/registry.rs index fdc426c2..e2df6488 100644 --- a/rust/crates/fire-core/src/core/topic_detail/registry.rs +++ b/rust/crates/fire-core/src/core/topic_detail/registry.rs @@ -3,19 +3,15 @@ use std::{ sync::{Arc, Mutex, OnceLock}, }; -use fire_models::{ - ReadPathLoginRequest, TopicHomeRowCountPatch, TopicListResponse, -}; +use fire_models::{ReadPathLoginRequest, TopicHomeRowCountPatch, TopicListResponse}; use tokio::sync::mpsc; use tracing::warn; -use super::super::topic_detail_project::{ - apply_patch_to_row, apply_patch_to_summary, -}; +use super::super::topic_detail_project::{apply_patch_to_row, apply_patch_to_summary}; use super::super::topics::topic_list_cache_scope_key; use super::super::FireCore; -use super::*; use super::actor::run_actor; +use super::*; struct Slot { session: Arc, @@ -102,10 +98,7 @@ impl TopicDetailSessionRegistry { }; slot.owners.remove(owner_token); if slot.owners.is_empty() { - let session = guard - .sessions - .remove(&topic_id) - .map(|slot| slot.session); + let session = guard.sessions.remove(&topic_id).map(|slot| slot.session); self.inner_clear_waiters(&mut guard, topic_id); drop(guard); if let Some(session) = session { @@ -115,10 +108,7 @@ impl TopicDetailSessionRegistry { let owners = slot.owners.clone(); let session = Arc::clone(&slot.session); drop(guard); - let _ = session.tx.send(Command::SyncOwners { - owners, - open: None, - }); + let _ = session.tx.send(Command::SyncOwners { owners, open: None }); } } @@ -180,9 +170,11 @@ impl TopicDetailSessionRegistry { pub(super) fn register_waiter(&self, generation: u64, topic_id: u64, track_visit: bool) { let mut guard = self.inner.lock().expect("topic detail registry poisoned"); - if guard.login_waiters.iter().any(|waiter| { - waiter.generation == generation && waiter.topic_id == topic_id - }) { + if guard + .login_waiters + .iter() + .any(|waiter| waiter.generation == generation && waiter.topic_id == topic_id) + { return; } guard.login_waiters.push(LoginWaiter { @@ -263,10 +255,8 @@ impl FireCore { let snapshot = session.snapshot.clone(); (snapshot, generation, false) } else { - session.read_path_login_generation = session - .read_path_login_generation - .saturating_add(1) - .max(1); + session.read_path_login_generation = + session.read_path_login_generation.saturating_add(1).max(1); let request = ReadPathLoginRequest { generation: session.read_path_login_generation, operation: operation.to_string(), @@ -357,4 +347,3 @@ impl FireCore { } } } - diff --git a/rust/crates/fire-core/src/core/topic_detail/session.rs b/rust/crates/fire-core/src/core/topic_detail/session.rs index 0a30b7b7..ac6b8f34 100644 --- a/rust/crates/fire-core/src/core/topic_detail/session.rs +++ b/rust/crates/fire-core/src/core/topic_detail/session.rs @@ -1,4 +1,3 @@ - use tokio::sync::{mpsc, oneshot}; use super::*; diff --git a/rust/crates/fire-core/src/core/topic_detail/summary.rs b/rust/crates/fire-core/src/core/topic_detail/summary.rs index 3aee8f39..d59f119c 100644 --- a/rust/crates/fire-core/src/core/topic_detail/summary.rs +++ b/rust/crates/fire-core/src/core/topic_detail/summary.rs @@ -1,5 +1,3 @@ - - use super::super::topic_detail_project::project_history_rows; use super::super::FireCore; use super::*; @@ -37,16 +35,20 @@ impl ActorState { self.publish(core, false); } - pub(super) async fn prepare_edit(&self, core: &FireCore, post_id: u64) -> Result { - if let Some(raw) = core.with_topic_source_session_mut(self.topic_id, None, |session| { - session - .post(post_id) - .and_then(|post| post.raw.clone()) - .filter(|raw| !raw.is_empty()) - }) { - if let Some(raw) = raw { - return Ok(raw); - } + pub(super) async fn prepare_edit( + &self, + core: &FireCore, + post_id: u64, + ) -> Result { + if let Some(Some(raw)) = + core.with_topic_source_session_mut(self.topic_id, None, |session| { + session + .post(post_id) + .and_then(|post| post.raw.clone()) + .filter(|raw| !raw.is_empty()) + }) + { + return Ok(raw); } let post = core.fetch_post(post_id).await?; let raw = post.raw.clone().unwrap_or_default(); @@ -65,7 +67,6 @@ impl ActorState { Ok(()) } - pub(super) async fn load_reply_context(&mut self, core: &FireCore, post_id: u64) { self.loading_reply_context.insert(post_id); self.publish(core, false); @@ -99,5 +100,4 @@ impl ActorState { self.loading_reply_context.remove(&post_id); self.publish(core, true); } - } diff --git a/rust/crates/fire-core/src/core/topic_detail/tests.rs b/rust/crates/fire-core/src/core/topic_detail/tests.rs index cac50c3d..fb70cc9e 100644 --- a/rust/crates/fire-core/src/core/topic_detail/tests.rs +++ b/rust/crates/fire-core/src/core/topic_detail/tests.rs @@ -6,107 +6,107 @@ use super::super::FireCore; use super::{TopicDetailObserver, TopicDetailOpenRequest}; use crate::config::FireCoreConfig; - struct RecordingObserver { - snapshots: StdMutex>, - } - - impl TopicDetailObserver for RecordingObserver { - fn on_snapshot(&self, snapshot: TopicDetailUiSnapshot) { - self.snapshots.lock().expect("observer").push(snapshot); - } - } +struct RecordingObserver { + snapshots: StdMutex>, +} - fn test_core() -> FireCore { - FireCore::new(FireCoreConfig::default()).expect("core") +impl TopicDetailObserver for RecordingObserver { + fn on_snapshot(&self, snapshot: TopicDetailUiSnapshot) { + self.snapshots.lock().expect("observer").push(snapshot); } +} - fn seed(core: &FireCore) { - let body = TopicPost { - id: 1, - username: "alice".into(), - cooked: "

op

".into(), - post_number: 1, - ..TopicPost::default() - }; - core.seed_topic_detail_source_for_test( - TopicHeader { - topic_id: 42, - title: "topic".into(), - slug: "topic".into(), - posts_count: 1, - ..TopicHeader::default() - }, - body, - Vec::new(), - vec![1], - ); - } +fn test_core() -> FireCore { + FireCore::new(FireCoreConfig::default()).expect("core") +} - fn open_request(owner: &str) -> TopicDetailOpenRequest { - TopicDetailOpenRequest { +fn seed(core: &FireCore) { + let body = TopicPost { + id: 1, + username: "alice".into(), + cooked: "

op

".into(), + post_number: 1, + ..TopicPost::default() + }; + core.seed_topic_detail_source_for_test( + TopicHeader { topic_id: 42, - owner_token: owner.into(), - slug_hint: None, - target_post_number: None, - bypass_cache: false, - force_load: false, - track_visit: false, - allow_suggested_unread_root: false, - } + title: "topic".into(), + slug: "topic".into(), + posts_count: 1, + ..TopicHeader::default() + }, + body, + Vec::new(), + vec![1], + ); +} + +fn open_request(owner: &str) -> TopicDetailOpenRequest { + TopicDetailOpenRequest { + topic_id: 42, + owner_token: owner.into(), + slug_hint: None, + target_post_number: None, + bypass_cache: false, + force_load: false, + track_visit: false, + allow_suggested_unread_root: false, } +} - #[tokio::test] - async fn same_owner_reopen_replaces_observer_and_release_keeps_the_other() { - let core = test_core(); - seed(&core); - let first = Arc::new(RecordingObserver { - snapshots: StdMutex::new(Vec::new()), - }); - let second = Arc::new(RecordingObserver { - snapshots: StdMutex::new(Vec::new()), - }); - let third = Arc::new(RecordingObserver { - snapshots: StdMutex::new(Vec::new()), - }); - let session = core.topic_detail_sessions.open( - &core, - open_request("owner-a"), - first.clone() as Arc, - ); - session.sync_for_test().await; - let first_count = first.snapshots.lock().expect("first").len(); - assert!(first_count >= 1); +#[tokio::test] +async fn same_owner_reopen_replaces_observer_and_release_keeps_the_other() { + let core = test_core(); + seed(&core); + let first = Arc::new(RecordingObserver { + snapshots: StdMutex::new(Vec::new()), + }); + let second = Arc::new(RecordingObserver { + snapshots: StdMutex::new(Vec::new()), + }); + let third = Arc::new(RecordingObserver { + snapshots: StdMutex::new(Vec::new()), + }); + let session = core.topic_detail_sessions.open( + &core, + open_request("owner-a"), + first.clone() as Arc, + ); + session.sync_for_test().await; + let first_count = first.snapshots.lock().expect("first").len(); + assert!(first_count >= 1); - core.topic_detail_sessions.open( - &core, - open_request("owner-a"), - second.clone() as Arc, - ); - session.sync_for_test().await; - let first_after_replace = first.snapshots.lock().expect("first").len(); - assert!(second.snapshots.lock().expect("second").len() >= 1); + core.topic_detail_sessions.open( + &core, + open_request("owner-a"), + second.clone() as Arc, + ); + session.sync_for_test().await; + let first_after_replace = first.snapshots.lock().expect("first").len(); + assert!(!second.snapshots.lock().expect("second").is_empty()); - core.topic_detail_sessions.open( - &core, - open_request("owner-b"), - third.clone() as Arc, - ); - session.sync_for_test().await; - assert_eq!(core.topic_detail_sessions.session_count(), 1); + core.topic_detail_sessions.open( + &core, + open_request("owner-b"), + third.clone() as Arc, + ); + session.sync_for_test().await; + assert_eq!(core.topic_detail_sessions.session_count(), 1); - core.topic_detail_sessions.release(42, "owner-a"); - session.sync_for_test().await; - assert_eq!(core.topic_detail_sessions.session_count(), 1); - let third_before = third.snapshots.lock().expect("third").len(); - session.clear_scroll_target(); - session.sync_for_test().await; - assert!(third.snapshots.lock().expect("third").len() > third_before); - assert_eq!( - first.snapshots.lock().expect("first").len(), - first_after_replace - ); + core.topic_detail_sessions.release(42, "owner-a"); + session.sync_for_test().await; + assert_eq!(core.topic_detail_sessions.session_count(), 1); + let third_before = third.snapshots.lock().expect("third").len(); + session.clear_scroll_target(); + session.sync_for_test().await; + assert!(third.snapshots.lock().expect("third").len() > third_before); + assert_eq!( + first.snapshots.lock().expect("first").len(), + first_after_replace + ); - core.topic_detail_sessions.release(42, "owner-b"); - session.sync_for_test().await; - assert_eq!(core.topic_detail_sessions.session_count(), 0); - } + core.topic_detail_sessions.release(42, "owner-b"); + session.sync_for_test().await; + assert_eq!(core.topic_detail_sessions.session_count(), 0); +} diff --git a/rust/crates/fire-core/src/core/topic_detail/window.rs b/rust/crates/fire-core/src/core/topic_detail/window.rs index 8316dce6..506b36b0 100644 --- a/rust/crates/fire-core/src/core/topic_detail/window.rs +++ b/rust/crates/fire-core/src/core/topic_detail/window.rs @@ -1,14 +1,13 @@ use std::ops::Range; - use super::super::FireCore; use super::*; impl ActorState { pub(super) fn expand_window_for_visible(&mut self, core: &FireCore, visible: &[u32]) { - let Some(total) = core.with_topic_source_session_mut(self.topic_id, None, |session| { - session.raw_stream_len() - }) else { + let Some(total) = core + .with_topic_source_session_mut(self.topic_id, None, |session| session.raw_stream_len()) + else { return; }; let indices = visible @@ -98,9 +97,9 @@ impl ActorState { } pub(super) fn extend_window_to_loaded(&mut self, core: &FireCore) { - let Some(total) = core.with_topic_source_session_mut(self.topic_id, None, |session| { - session.raw_stream_len() - }) else { + let Some(total) = core + .with_topic_source_session_mut(self.topic_id, None, |session| session.raw_stream_len()) + else { return; }; if self.window.requested.end >= total.saturating_sub(TOPIC_DETAIL_HYDRATION_PAGE) { @@ -154,10 +153,14 @@ impl ActorState { } }); } - } -fn bounded_range(mut lower: usize, mut upper: usize, total: usize, anchor: Option) -> Range { +fn bounded_range( + mut lower: usize, + mut upper: usize, + total: usize, + anchor: Option, +) -> Range { if total == 0 { return 0..0; } @@ -226,7 +229,12 @@ fn next_range_for_target( let forward = if let Some(max_loaded) = loaded.iter().copied().max() { if post_number > max_loaded { true - } else if loaded.iter().copied().min().is_some_and(|min| post_number < min) { + } else if loaded + .iter() + .copied() + .min() + .is_some_and(|min| post_number < min) + { false } else { total - current.end >= current.start diff --git a/rust/crates/fire-core/src/core/topic_detail_project.rs b/rust/crates/fire-core/src/core/topic_detail_project.rs index 7fbee418..48ba3d4b 100644 --- a/rust/crates/fire-core/src/core/topic_detail_project.rs +++ b/rust/crates/fire-core/src/core/topic_detail_project.rs @@ -43,7 +43,10 @@ pub(crate) fn project_topic_detail_snapshot( let posts = posts_by_id(source); let original_id = tree.original_post_id; let mut rows = Vec::new(); - if let Some(post) = posts.get(&original_id).or_else(|| posts.get(&source.body.post.id)) { + if let Some(post) = posts + .get(&original_id) + .or_else(|| posts.get(&source.body.post.id)) + { rows.push(project_row( post, &TopicTreeRow { @@ -53,9 +56,10 @@ pub(crate) fn project_topic_detail_snapshot( parent_post_number: None, depth: 0, preorder_index: 0, - has_children: tree.reply_rows.iter().any(|row| { - row.parent_post_number == Some(post.post_number) || row.depth == 1 - }), + has_children: tree + .reply_rows + .iter() + .any(|row| row.parent_post_number == Some(post.post_number) || row.depth == 1), sibling_index: 0, is_last_sibling: true, descendant_count: post.reply_count, @@ -212,7 +216,10 @@ fn project_row( .reactions .iter() .map(|reaction| { - TopicDetailReactionChip::from_reaction(reaction, Some(&reaction.id) == selected_id.as_ref()) + TopicDetailReactionChip::from_reaction( + reaction, + Some(&reaction.id) == selected_id.as_ref(), + ) }) .collect::>(); let author = author_display(post); @@ -263,15 +270,15 @@ fn project_row( .reply_to_user .as_ref() .map(|user| user.username.clone()) - .or_else(|| { - post.reply_to_post_number - .map(|number| format!("#{number}")) + .or_else(|| post.reply_to_post_number.map(|number| format!("#{number}"))), + reply_to_user: post + .reply_to_user + .as_ref() + .map(|user| TopicDetailReplyUserDisplay { + username: user.username.clone(), + name: user.name.clone(), + avatar_template: user.avatar_template.clone(), }), - reply_to_user: post.reply_to_user.as_ref().map(|user| TopicDetailReplyUserDisplay { - username: user.username.clone(), - name: user.name.clone(), - avatar_template: user.avatar_template.clone(), - }), like_count: post.like_count, reactions, current_reaction_id: selected_id, @@ -329,10 +336,7 @@ fn posts_by_id(source: &TopicDetailSourceSnapshot) -> HashMap { posts } -pub(crate) fn unread_decision( - last_read: Option, - highest: u32, -) -> TopicHomeUnreadDecision { +pub(crate) fn unread_decision(last_read: Option, highest: u32) -> TopicHomeUnreadDecision { match last_read { None => TopicHomeUnreadDecision::WhenLastReadMissing, Some(last_read) if last_read >= highest => TopicHomeUnreadDecision::CaughtUp, @@ -391,8 +395,12 @@ pub(crate) fn apply_patch_to_summary( summary.last_read_post_number = patch.last_read_post_number; summary.highest_post_number = patch.highest_post_number; let has_unread = row_has_unread.unwrap_or(summary.unread_posts > 0 || summary.new_posts > 0); - let (unread_posts, new_posts, _) = - apply_home_unread_counts(has_unread, patch.unread, summary.unread_posts, summary.new_posts); + let (unread_posts, new_posts, _) = apply_home_unread_counts( + has_unread, + patch.unread, + summary.unread_posts, + summary.new_posts, + ); summary.unread_posts = unread_posts; summary.new_posts = new_posts; } @@ -426,7 +434,11 @@ pub(crate) fn structure_changed( || previous.has_more != next.has_more || previous.is_loading_more != next.is_loading_more || previous.load_more_error != next.load_more_error - || previous.rows.iter().map(|row| row.post_id).collect::>() + || previous + .rows + .iter() + .map(|row| row.post_id) + .collect::>() != next.rows.iter().map(|row| row.post_id).collect::>() } @@ -468,7 +480,10 @@ pub(crate) fn interaction_checksums_changed( }) || previous.composer != next.composer } -pub(crate) fn chrome_fields_changed(previous: &TopicDetailChrome, next: &TopicDetailChrome) -> bool { +pub(crate) fn chrome_fields_changed( + previous: &TopicDetailChrome, + next: &TopicDetailChrome, +) -> bool { previous.title != next.title || previous.slug != next.slug || previous.bookmarked != next.bookmarked @@ -668,23 +683,15 @@ mod tests { #[test] fn when_last_read_missing_zeros_counts_when_has_unread_is_false() { - let (unread, new_posts, flag) = apply_home_unread_counts( - false, - TopicHomeUnreadDecision::WhenLastReadMissing, - 4, - 2, - ); + let (unread, new_posts, flag) = + apply_home_unread_counts(false, TopicHomeUnreadDecision::WhenLastReadMissing, 4, 2); assert_eq!((unread, new_posts, flag), (0, 0, false)); } #[test] fn when_last_read_missing_keeps_counts_when_has_unread_is_true() { - let (unread, new_posts, flag) = apply_home_unread_counts( - true, - TopicHomeUnreadDecision::WhenLastReadMissing, - 4, - 2, - ); + let (unread, new_posts, flag) = + apply_home_unread_counts(true, TopicHomeUnreadDecision::WhenLastReadMissing, 4, 2); assert_eq!((unread, new_posts, flag), (4, 2, true)); } diff --git a/rust/crates/fire-core/src/core/topics/list.rs b/rust/crates/fire-core/src/core/topics/list.rs index f368c00a..12926e56 100644 --- a/rust/crates/fire-core/src/core/topics/list.rs +++ b/rust/crates/fire-core/src/core/topics/list.rs @@ -2,10 +2,7 @@ use fire_models::{TopicListKind, TopicListQuery, TopicListResponse}; use tracing::{info, warn}; use super::super::{network::expect_success, FireCore}; -use crate::{ - error::FireCoreError, - topic_payloads::RawTopicListResponse, -}; +use crate::{error::FireCoreError, topic_payloads::RawTopicListResponse}; pub(crate) fn topic_list_cache_scope_key(query: &TopicListQuery) -> String { let mut parts = vec![ diff --git a/rust/crates/fire-core/src/core/topics/mod.rs b/rust/crates/fire-core/src/core/topics/mod.rs index 41edd496..16cc383c 100644 --- a/rust/crates/fire-core/src/core/topics/mod.rs +++ b/rust/crates/fire-core/src/core/topics/mod.rs @@ -5,7 +5,6 @@ mod tree; pub(crate) use list::topic_list_cache_scope_key; pub(crate) use source::{ - load_more_topic_detail_posts, load_topic_detail_page, - FireTopicDetailSourceRuntime, + load_more_topic_detail_posts, load_topic_detail_page, FireTopicDetailSourceRuntime, }; pub(crate) use tree::build_topic_tree_presentation_from_source_snapshot; diff --git a/rust/crates/fire-core/src/core/topics/posts.rs b/rust/crates/fire-core/src/core/topics/posts.rs index fda10631..30166306 100644 --- a/rust/crates/fire-core/src/core/topics/posts.rs +++ b/rust/crates/fire-core/src/core/topics/posts.rs @@ -68,7 +68,10 @@ pub(super) fn topic_posts_for_requested_ids( ordered_posts.extend(trailing_posts); ordered_posts } -pub(super) fn missing_post_ids_from_ids(ordered_post_ids: &[u64], loaded_posts: &[TopicPost]) -> Vec { +pub(super) fn missing_post_ids_from_ids( + ordered_post_ids: &[u64], + loaded_posts: &[TopicPost], +) -> Vec { let loaded_post_ids: HashSet = loaded_posts.iter().map(|post| post.id).collect(); ordered_post_ids .iter() diff --git a/rust/crates/fire-core/src/core/topics/source/hydrate.rs b/rust/crates/fire-core/src/core/topics/source/hydrate.rs index 6850f199..f9253f8f 100644 --- a/rust/crates/fire-core/src/core/topics/source/hydrate.rs +++ b/rust/crates/fire-core/src/core/topics/source/hydrate.rs @@ -1,11 +1,8 @@ -use std::collections::{HashMap, HashSet}; -use std::time::Instant; +use std::collections::HashSet; use fire_models::{ - LoadMoreTopicPostsQuery, TopicAiSummary, TopicBody, TopicDetail, TopicDetailPage, - TopicDetailQuery, TopicDetailSourceAppend, TopicDetailSourceQuery, TopicDetailSourceSnapshot, - TopicHeader, TopicLoadMoreOutcome, TopicLoadMoreStopReason, TopicLoadedRange, TopicPost, - TopicSourceCursor, TopicThread, TopicTreePresentation, + TopicAiSummary, TopicDetail, TopicDetailQuery, TopicDetailSourceSnapshot, TopicPost, + TopicThread, }; use http::StatusCode; use serde_json::Value; @@ -13,18 +10,14 @@ use tracing::{info, warn}; use super::super::super::{network::expect_success, FireCore}; use super::super::posts::{ - merge_topic_posts, missing_post_ids_from_ids, missing_topic_post_ids, - ordered_unique_post_ids, topic_posts_for_requested_ids, -}; -use super::super::tree::{ - build_topic_tree_presentation_from_source_snapshot, topic_detail_source_cooked_byte_count, - topic_tree_needs_unread_root_extension, + merge_topic_posts, missing_topic_post_ids, ordered_unique_post_ids, + topic_posts_for_requested_ids, }; use super::*; use crate::{ error::FireCoreError, json_helpers::invalid_json, - topic_payloads::{parse_topic_ai_summary_value, parse_topic_post_stream_value, RawTopicDetail}, + topic_payloads::{parse_topic_ai_summary_value, parse_topic_post_stream_value}, }; impl FireCore { pub async fn fetch_topic_posts( @@ -107,7 +100,11 @@ impl FireCore { session.posts_for_ids(post_ids) } - pub(super) fn cache_topic_posts_for_active_source_session(&self, topic_id: u64, posts: &[TopicPost]) { + pub(super) fn cache_topic_posts_for_active_source_session( + &self, + topic_id: u64, + posts: &[TopicPost], + ) { if posts.is_empty() { return; } diff --git a/rust/crates/fire-core/src/core/topics/source/load.rs b/rust/crates/fire-core/src/core/topics/source/load.rs index 187220b3..a366c680 100644 --- a/rust/crates/fire-core/src/core/topics/source/load.rs +++ b/rust/crates/fire-core/src/core/topics/source/load.rs @@ -1,31 +1,21 @@ -use std::collections::{HashMap, HashSet}; +use std::collections::HashSet; use std::time::Instant; use fire_models::{ - LoadMoreTopicPostsQuery, TopicAiSummary, TopicBody, TopicDetail, TopicDetailPage, - TopicDetailQuery, TopicDetailSourceAppend, TopicDetailSourceQuery, TopicDetailSourceSnapshot, - TopicHeader, TopicLoadMoreOutcome, TopicLoadMoreStopReason, TopicLoadedRange, TopicPost, - TopicSourceCursor, TopicThread, TopicTreePresentation, + LoadMoreTopicPostsQuery, TopicDetail, TopicDetailPage, TopicDetailQuery, + TopicDetailSourceAppend, TopicDetailSourceQuery, TopicDetailSourceSnapshot, + TopicLoadMoreOutcome, TopicLoadMoreStopReason, TopicSourceCursor, TopicTreePresentation, }; -use http::StatusCode; -use serde_json::Value; use tracing::{info, warn}; use super::super::super::{network::expect_success, FireCore}; -use super::super::posts::{ - merge_topic_posts, missing_post_ids_from_ids, missing_topic_post_ids, - ordered_unique_post_ids, topic_posts_for_requested_ids, -}; +use super::super::posts::{merge_topic_posts, missing_post_ids_from_ids}; use super::super::tree::{ build_topic_tree_presentation_from_source_snapshot, topic_detail_source_cooked_byte_count, topic_tree_needs_unread_root_extension, }; use super::*; -use crate::{ - error::FireCoreError, - json_helpers::invalid_json, - topic_payloads::{parse_topic_ai_summary_value, parse_topic_post_stream_value, RawTopicDetail}, -}; +use crate::{error::FireCoreError, topic_payloads::RawTopicDetail}; pub(crate) async fn load_topic_detail_source_snapshot( core: &FireCore, query: TopicDetailSourceQuery, @@ -667,5 +657,4 @@ impl FireCore { ensure_requested_topic_detail(query.topic_id, detail.id)?; Ok(detail) } - } diff --git a/rust/crates/fire-core/src/core/topics/source/mod.rs b/rust/crates/fire-core/src/core/topics/source/mod.rs index 4660f80e..302dbb1d 100644 --- a/rust/crates/fire-core/src/core/topics/source/mod.rs +++ b/rust/crates/fire-core/src/core/topics/source/mod.rs @@ -2,7 +2,7 @@ use std::collections::{HashMap, HashSet}; use fire_models::{ TopicDetailSourceSnapshot, TopicHeader, TopicLoadMoreOutcome, TopicLoadMoreStopReason, - TopicLoadedRange, TopicPost, TopicSourceCursor, TopicTreePresentation, + TopicLoadedRange, TopicPost, TopicTreePresentation, }; use crate::error::FireCoreError; @@ -11,9 +11,7 @@ mod hydrate; mod load; mod session; -pub(crate) use load::{ - load_more_topic_detail_posts, load_topic_detail_page, load_topic_detail_source_snapshot, -}; +pub(crate) use load::{load_more_topic_detail_posts, load_topic_detail_page}; const TOPIC_POST_BATCH_SIZE: usize = 50; const FETCH_TOPIC_AI_SUMMARY_OPERATION: &str = "fetch topic ai summary"; @@ -143,4 +141,3 @@ fn gained_visible_root_progress(previous: &[u32], current: &[u32]) -> bool { .copied() .any(|post_number| !previous_roots.contains(&post_number)) } - diff --git a/rust/crates/fire-core/src/core/topics/source/session.rs b/rust/crates/fire-core/src/core/topics/source/session.rs index f7c4d0eb..7ae80c3a 100644 --- a/rust/crates/fire-core/src/core/topics/source/session.rs +++ b/rust/crates/fire-core/src/core/topics/source/session.rs @@ -1,31 +1,12 @@ use std::collections::{HashMap, HashSet}; -use std::time::Instant; use fire_models::{ - LoadMoreTopicPostsQuery, TopicAiSummary, TopicBody, TopicDetail, TopicDetailPage, - TopicDetailQuery, TopicDetailSourceAppend, TopicDetailSourceQuery, TopicDetailSourceSnapshot, - TopicHeader, TopicLoadMoreOutcome, TopicLoadMoreStopReason, TopicLoadedRange, TopicPost, - TopicSourceCursor, TopicThread, TopicTreePresentation, -}; -use http::StatusCode; -use serde_json::Value; -use tracing::{info, warn}; - -use super::super::super::{network::expect_success, FireCore}; -use super::super::posts::{ - merge_topic_posts, missing_post_ids_from_ids, missing_topic_post_ids, - ordered_unique_post_ids, topic_posts_for_requested_ids, -}; -use super::super::tree::{ - build_topic_tree_presentation_from_source_snapshot, topic_detail_source_cooked_byte_count, - topic_tree_needs_unread_root_extension, + TopicBody, TopicDetailSourceSnapshot, TopicHeader, TopicLoadedRange, TopicPost, + TopicSourceCursor, }; + +use super::super::posts::merge_topic_posts; use super::*; -use crate::{ - error::FireCoreError, - json_helpers::invalid_json, - topic_payloads::{parse_topic_ai_summary_value, parse_topic_post_stream_value, RawTopicDetail}, -}; impl TopicDetailSourceSession { pub(crate) fn raw_stream_len(&self) -> usize { self.raw_stream_ids.len() @@ -265,12 +246,11 @@ impl TopicDetailSourceSession { } } - #[cfg(test)] mod tests { - use super::*; - use super::super::gained_visible_root_progress; use super::super::super::posts::ordered_unique_post_ids; + use super::super::gained_visible_root_progress; + use super::*; use fire_models::{TopicHeader, TopicPost}; use std::collections::HashSet; diff --git a/rust/crates/fire-core/src/core/topics/tree.rs b/rust/crates/fire-core/src/core/topics/tree.rs index b5717502..73e176c3 100644 --- a/rust/crates/fire-core/src/core/topics/tree.rs +++ b/rust/crates/fire-core/src/core/topics/tree.rs @@ -7,9 +7,7 @@ use fire_models::{ TopicTreeRow, }; -use super::posts::{ - deduplicate_topic_posts_by_id, merge_topic_posts, ordered_unique_post_ids, -}; +use super::posts::{deduplicate_topic_posts_by_id, merge_topic_posts, ordered_unique_post_ids}; use super::super::FireCore; @@ -558,6 +556,4 @@ mod tests { assert_eq!(presentation.visible_root_post_numbers, vec![2]); assert_eq!(presentation.first_unread_root_post_number, None); } - - } diff --git a/rust/crates/fire-uniffi-session/src/lib.rs b/rust/crates/fire-uniffi-session/src/lib.rs index fa73b228..5662973e 100644 --- a/rust/crates/fire-uniffi-session/src/lib.rs +++ b/rust/crates/fire-uniffi-session/src/lib.rs @@ -20,11 +20,10 @@ pub use records::{ HomeTopicListScopeState, LoginFailureKindState, LoginFailureState, LoginFinalizationResultState, LoginPhaseState, LoginStateDeterminationState, LoginSyncState, NuclearResetPlanState, PassiveLogoutTriggerState, PlatformCookieState, PreloadedDataStateState, - RefreshBatchState, RefreshTriggerState, SecondFactorRequirementState, SessionPersistenceState, - SessionReadinessState, SessionState, ReadPathLoginRequestState, TopicCategoryState, - WebViewCookieActionState, - WebViewCookieInfoState, WebViewLoginDecisionState, WebViewLoginJsResultState, - WebViewLoginPhaseState, + ReadPathLoginRequestState, RefreshBatchState, RefreshTriggerState, + SecondFactorRequirementState, SessionPersistenceState, SessionReadinessState, SessionState, + TopicCategoryState, WebViewCookieActionState, WebViewCookieInfoState, + WebViewLoginDecisionState, WebViewLoginJsResultState, WebViewLoginPhaseState, }; #[derive(uniffi::Object)] diff --git a/rust/crates/fire-uniffi-topics/src/records/detail.rs b/rust/crates/fire-uniffi-topics/src/records/detail.rs index fd5a5a5b..4fc971f2 100644 --- a/rust/crates/fire-uniffi-topics/src/records/detail.rs +++ b/rust/crates/fire-uniffi-topics/src/records/detail.rs @@ -1,26 +1,15 @@ -use std::sync::Arc; - use fire_models::{ - LoadMoreTopicPostsQuery, Poll, PollOption, PostActionType, PostFlagRequest, PostReactionUpdate, - PostUpdateRequest, PrivateMessageCreateRequest, ReactionUser, ReactionUsersGroup, - ResolvedUploadUrl, TopicAiSummary, TopicBody, TopicCreateRequest, TopicDetail, - TopicDetailCreatedBy, TopicDetailMeta, TopicDetailPage, TopicDetailSourceQuery, - TopicDetailSourceSnapshot, TopicHeader, TopicListQuery, TopicLoadMoreOutcome, - TopicLoadMoreStopReason, TopicLoadedRange, TopicPost, TopicPostAuthorMetadata, TopicPostBoost, - TopicPostBoostUser, TopicPostStream, TopicReaction, TopicReplyRequest, TopicReplyToUser, - TopicSourceCursor, TopicTimingEntry, TopicTimingsRequest, TopicTreePresentation, TopicTreeRow, - TopicUpdateRequest, UploadResult, VoteResponse, VotedUser, + LoadMoreTopicPostsQuery, TopicBody, TopicDetail, TopicDetailCreatedBy, TopicDetailMeta, + TopicDetailPage, TopicDetailSourceQuery, TopicDetailSourceSnapshot, TopicHeader, + TopicLoadMoreOutcome, TopicLoadMoreStopReason, TopicTreePresentation, TopicTreeRow, }; -use fire_uniffi_types::{ - intern_presented_handle, RenderDocumentHandle, TopicListKindState, TopicParticipantState, - TopicTagState, -}; use super::list::{TopicLoadedRangeState, TopicSourceCursorState}; use super::post::{ topic_post_state_from_model, topic_post_stream_state_from_model, TopicPostState, TopicPostStreamState, }; +use fire_uniffi_types::{TopicParticipantState, TopicTagState}; #[derive(uniffi::Record, Debug, Clone)] pub struct TopicDetailSourceQueryState { diff --git a/rust/crates/fire-uniffi-topics/src/records/list.rs b/rust/crates/fire-uniffi-topics/src/records/list.rs index bc299dce..e53fbd42 100644 --- a/rust/crates/fire-uniffi-topics/src/records/list.rs +++ b/rust/crates/fire-uniffi-topics/src/records/list.rs @@ -1,21 +1,6 @@ -use std::sync::Arc; +use fire_models::{TopicListQuery, TopicLoadedRange, TopicSourceCursor}; -use fire_models::{ - LoadMoreTopicPostsQuery, Poll, PollOption, PostActionType, PostFlagRequest, PostReactionUpdate, - PostUpdateRequest, PrivateMessageCreateRequest, ReactionUser, ReactionUsersGroup, - ResolvedUploadUrl, TopicAiSummary, TopicBody, TopicCreateRequest, TopicDetail, - TopicDetailCreatedBy, TopicDetailMeta, TopicDetailPage, TopicDetailSourceQuery, - TopicDetailSourceSnapshot, TopicHeader, TopicListQuery, TopicLoadMoreOutcome, - TopicLoadMoreStopReason, TopicLoadedRange, TopicPost, TopicPostAuthorMetadata, TopicPostBoost, - TopicPostBoostUser, TopicPostStream, TopicReaction, TopicReplyRequest, TopicReplyToUser, - TopicSourceCursor, TopicTimingEntry, TopicTimingsRequest, TopicTreePresentation, TopicTreeRow, - TopicUpdateRequest, UploadResult, VoteResponse, VotedUser, -}; - -use fire_uniffi_types::{ - intern_presented_handle, RenderDocumentHandle, TopicListKindState, TopicParticipantState, - TopicTagState, -}; +use fire_uniffi_types::TopicListKindState; #[derive(uniffi::Record, Debug, Clone)] pub struct TopicListQueryState { diff --git a/rust/crates/fire-uniffi-topics/src/records/poll.rs b/rust/crates/fire-uniffi-topics/src/records/poll.rs index 8656578b..c71908ef 100644 --- a/rust/crates/fire-uniffi-topics/src/records/poll.rs +++ b/rust/crates/fire-uniffi-topics/src/records/poll.rs @@ -1,21 +1,4 @@ -use std::sync::Arc; - -use fire_models::{ - LoadMoreTopicPostsQuery, Poll, PollOption, PostActionType, PostFlagRequest, PostReactionUpdate, - PostUpdateRequest, PrivateMessageCreateRequest, ReactionUser, ReactionUsersGroup, - ResolvedUploadUrl, TopicAiSummary, TopicBody, TopicCreateRequest, TopicDetail, - TopicDetailCreatedBy, TopicDetailMeta, TopicDetailPage, TopicDetailSourceQuery, - TopicDetailSourceSnapshot, TopicHeader, TopicListQuery, TopicLoadMoreOutcome, - TopicLoadMoreStopReason, TopicLoadedRange, TopicPost, TopicPostAuthorMetadata, TopicPostBoost, - TopicPostBoostUser, TopicPostStream, TopicReaction, TopicReplyRequest, TopicReplyToUser, - TopicSourceCursor, TopicTimingEntry, TopicTimingsRequest, TopicTreePresentation, TopicTreeRow, - TopicUpdateRequest, UploadResult, VoteResponse, VotedUser, -}; - -use fire_uniffi_types::{ - intern_presented_handle, RenderDocumentHandle, TopicListKindState, TopicParticipantState, - TopicTagState, -}; +use fire_models::{Poll, PollOption}; #[derive(uniffi::Record, Debug, Clone)] pub struct PollOptionState { diff --git a/rust/crates/fire-uniffi-topics/src/records/post.rs b/rust/crates/fire-uniffi-topics/src/records/post.rs index f36b088d..44a209d4 100644 --- a/rust/crates/fire-uniffi-topics/src/records/post.rs +++ b/rust/crates/fire-uniffi-topics/src/records/post.rs @@ -1,23 +1,15 @@ use std::sync::Arc; use fire_models::{ - LoadMoreTopicPostsQuery, Poll, PollOption, PostActionType, PostFlagRequest, PostReactionUpdate, - PostUpdateRequest, PrivateMessageCreateRequest, ReactionUser, ReactionUsersGroup, - ResolvedUploadUrl, TopicAiSummary, TopicBody, TopicCreateRequest, TopicDetail, - TopicDetailCreatedBy, TopicDetailMeta, TopicDetailPage, TopicDetailSourceQuery, - TopicDetailSourceSnapshot, TopicHeader, TopicListQuery, TopicLoadMoreOutcome, - TopicLoadMoreStopReason, TopicLoadedRange, TopicPost, TopicPostAuthorMetadata, TopicPostBoost, - TopicPostBoostUser, TopicPostStream, TopicReaction, TopicReplyRequest, TopicReplyToUser, - TopicSourceCursor, TopicTimingEntry, TopicTimingsRequest, TopicTreePresentation, TopicTreeRow, - TopicUpdateRequest, UploadResult, VoteResponse, VotedUser, + PostActionType, PostFlagRequest, PostReactionUpdate, PostUpdateRequest, + PrivateMessageCreateRequest, ReactionUser, ReactionUsersGroup, TopicCreateRequest, TopicPost, + TopicPostAuthorMetadata, TopicPostBoost, TopicPostBoostUser, TopicPostStream, TopicReaction, + TopicReplyRequest, TopicReplyToUser, TopicUpdateRequest, }; use super::poll::PollState; -use fire_uniffi_types::{ - intern_presented_handle, RenderDocumentHandle, TopicListKindState, TopicParticipantState, - TopicTagState, -}; +use fire_uniffi_types::{intern_presented_handle, RenderDocumentHandle}; #[derive(uniffi::Record, Debug, Clone)] pub struct TopicReactionState { @@ -435,7 +427,7 @@ fn topic_post_state_from_model_ex( avatar_template: value.avatar_template, author_metadata: value.author_metadata.into(), presentation, - raw: include_raw.then(|| value.raw).flatten(), + raw: include_raw.then_some(value.raw).flatten(), post_number: value.post_number, post_type: value.post_type, created_at: value.created_at, diff --git a/rust/crates/fire-uniffi-topics/src/records/upload.rs b/rust/crates/fire-uniffi-topics/src/records/upload.rs index 1ae42641..0236af70 100644 --- a/rust/crates/fire-uniffi-topics/src/records/upload.rs +++ b/rust/crates/fire-uniffi-topics/src/records/upload.rs @@ -1,20 +1,6 @@ -use std::sync::Arc; - use fire_models::{ - LoadMoreTopicPostsQuery, Poll, PollOption, PostActionType, PostFlagRequest, PostReactionUpdate, - PostUpdateRequest, PrivateMessageCreateRequest, ReactionUser, ReactionUsersGroup, - ResolvedUploadUrl, TopicAiSummary, TopicBody, TopicCreateRequest, TopicDetail, - TopicDetailCreatedBy, TopicDetailMeta, TopicDetailPage, TopicDetailSourceQuery, - TopicDetailSourceSnapshot, TopicHeader, TopicListQuery, TopicLoadMoreOutcome, - TopicLoadMoreStopReason, TopicLoadedRange, TopicPost, TopicPostAuthorMetadata, TopicPostBoost, - TopicPostBoostUser, TopicPostStream, TopicReaction, TopicReplyRequest, TopicReplyToUser, - TopicSourceCursor, TopicTimingEntry, TopicTimingsRequest, TopicTreePresentation, TopicTreeRow, - TopicUpdateRequest, UploadResult, VoteResponse, VotedUser, -}; - -use fire_uniffi_types::{ - intern_presented_handle, RenderDocumentHandle, TopicListKindState, TopicParticipantState, - TopicTagState, + ResolvedUploadUrl, TopicAiSummary, TopicTimingEntry, TopicTimingsRequest, UploadResult, + VoteResponse, VotedUser, }; #[derive(uniffi::Record, Debug, Clone)] @@ -164,4 +150,3 @@ impl From for VoteResponseState { } } } - diff --git a/rust/crates/fire-uniffi-topics/src/session.rs b/rust/crates/fire-uniffi-topics/src/session.rs index 4041761c..417d3cdd 100644 --- a/rust/crates/fire-uniffi-topics/src/session.rs +++ b/rust/crates/fire-uniffi-topics/src/session.rs @@ -73,7 +73,7 @@ impl FireTopicsHandle { #[uniffi::export] impl TopicDetailSessionHandle { - pub fn close(&self) { + pub fn release(&self) { self.shared .core .release_topic_detail_owner(self.topic_id, &self.owner_token); diff --git a/rust/crates/fire-uniffi-topics/src/ui_records.rs b/rust/crates/fire-uniffi-topics/src/ui_records.rs index 5892d831..cf2b12f5 100644 --- a/rust/crates/fire-uniffi-topics/src/ui_records.rs +++ b/rust/crates/fire-uniffi-topics/src/ui_records.rs @@ -418,15 +418,21 @@ impl From for TopicDetailUiRowState { post_type: value.post_type, reply_count: value.reply_count, reply_to_username: value.reply_to_username, - reply_to_user: value.reply_to_user.map(|user| TopicDetailReplyUserDisplayState { - username: user.username, - name: user.name, - avatar_template: user.avatar_template, - }), + reply_to_user: value + .reply_to_user + .map(|user| TopicDetailReplyUserDisplayState { + username: user.username, + name: user.name, + avatar_template: user.avatar_template, + }), like_count: value.like_count, reactions: value.reactions.into_iter().map(Into::into).collect(), current_reaction_id: value.current_reaction_id, - polls: value.polls.into_iter().map(poll_state_from_display).collect(), + polls: value + .polls + .into_iter() + .map(poll_state_from_display) + .collect(), boosts: value.boosts.into_iter().map(Into::into).collect(), accepted_answer: value.accepted_answer, can_accept_answer: value.can_accept_answer, From b09abaa5f94d467a8813eab071a38a1bf1a024a3 Mon Sep 17 00:00:00 2001 From: peter rich Date: Tue, 22 Sep 2026 18:07:42 +0800 Subject: [PATCH 03/11] fix(ios): regenerate Xcode project with UniFFI sources present xcodegen only includes Generated/FireUniFfi when those files exist; regenerate with stubs so CI's post-artifact project check matches. Co-authored-by: Cursor --- native/ios-app/Fire.xcodeproj/project.pbxproj | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/native/ios-app/Fire.xcodeproj/project.pbxproj b/native/ios-app/Fire.xcodeproj/project.pbxproj index 95dd7d6e..0df81cee 100644 --- a/native/ios-app/Fire.xcodeproj/project.pbxproj +++ b/native/ios-app/Fire.xcodeproj/project.pbxproj @@ -46,6 +46,7 @@ 256CB81681004BB26E0431B7 /* FireTopicDetailSharedModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = 925CD02F862E958CC79BC60A /* FireTopicDetailSharedModels.swift */; }; 2693C86EB9B8D438930E1B26 /* FireOnboardingValidatingView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A248DED21DCF11B55E331D29 /* FireOnboardingValidatingView.swift */; }; 2697DC8A389656A42CCEE78F /* Nuke in Frameworks */ = {isa = PBXBuildFile; productRef = 3F5DB59F34DC2099A84C0F6F /* Nuke */; }; + 26E51A13E796BFEF885FBD28 /* fire_uniffi_topics.swift in Sources */ = {isa = PBXBuildFile; fileRef = DDCE76B3F360C1C5631A950C /* fire_uniffi_topics.swift */; }; 26F6FF8DF720B6F46F3C5226 /* FireTopicDetailToolbarCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = DB73A3AE7A4D6E47C61CAE52 /* FireTopicDetailToolbarCoordinator.swift */; }; 27D3B7AADEF91C6DE3B41618 /* FireTopicEditorView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 577A99743CDCAA0033E2398C /* FireTopicEditorView.swift */; }; 27F8780AB48C65663BA8CF6A /* FireProfileActivityRow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 07E3386C6FC3093869C79E57 /* FireProfileActivityRow.swift */; }; @@ -66,6 +67,7 @@ 390219653B0C0A96C81D8962 /* FireAPMEventStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 373861687BBCD8EB8E350DA4 /* FireAPMEventStore.swift */; }; 3A20BD9A2A4CE944762B0BD7 /* FireReadHistoryViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C8AEE7516614D73C079F860 /* FireReadHistoryViewController.swift */; }; 3A339550AA3EE966F7EA50E5 /* FireProfileViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5DF67696B342C706CB3FAAFB /* FireProfileViewModel.swift */; }; + 3AFFAE192ADFE0FE4E054809 /* fire_uniffi_user.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F1F015314914FD74B56CC5D /* fire_uniffi_user.swift */; }; 3C9FA7D66DAA4DAE2B1BF45D /* FireProfileActivityTimelineView.swift in Sources */ = {isa = PBXBuildFile; fileRef = EFE429D39ACE68653A226FE9 /* FireProfileActivityTimelineView.swift */; }; 3CA9AF0BFA58C32834B441F3 /* FirePresentationIdentity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 019B4B93D3FDB4C799492775 /* FirePresentationIdentity.swift */; }; 3E37BA0BB7E0C48B9DAF40DE /* FireChatMessageCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 423DFD492305E9502EEFFCF9 /* FireChatMessageCell.swift */; }; @@ -83,6 +85,7 @@ 489C515305D468C608C7315D /* FirePostCellNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 093EEF1E0EBDB24ED7106CDD /* FirePostCellNode.swift */; }; 4E69EA800D7956E3C1989CFC /* FireCookieSelfHealingCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = C203C63EB7CB10843B8AB0EC /* FireCookieSelfHealingCoordinator.swift */; }; 4F0305B9162423D8D821A304 /* FireRouteParserTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 46C35F105D036EECAAE7B93D /* FireRouteParserTests.swift */; }; + 4F762CD9E7B43DB0534791C8 /* fire_uniffi.swift in Sources */ = {isa = PBXBuildFile; fileRef = EF98E1072E78DFC9F5057D67 /* fire_uniffi.swift */; }; 51D27C6354C43E1E83FEA3FB /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 6958AA64094FA7BB21B5FC36 /* PrivacyInfo.xcprivacy */; }; 522CA82334EAC05D23624720 /* FireTopicDetailModalViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8BC7B03BAACE572DDB87E810 /* FireTopicDetailModalViews.swift */; }; 52CF002705A0E18AAB2E9E62 /* FireTopicDetailRootNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = BEC29D6B75CD01B9ADD53F1A /* FireTopicDetailRootNode.swift */; }; @@ -130,13 +133,16 @@ 78009659A664B236D8AD3434 /* FireBadgeDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = BF5B6841F5556D86C606379F /* FireBadgeDetailView.swift */; }; 7848D667BF692B25B4194E57 /* FirePostCellLayoutCalculator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 24E7CCCA8B867D5E6B0CE198 /* FirePostCellLayoutCalculator.swift */; }; 790B44E436B0CF137B1FD8A7 /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E69013450F80AEC210D5512D /* Security.framework */; }; + 79B77A4E828C4862BE1BAA53 /* fire_uniffi_ldc.swift in Sources */ = {isa = PBXBuildFile; fileRef = A680E7A822BDD20CE84C04EE /* fire_uniffi_ldc.swift */; }; 7A0A8240B294336D5787C364 /* FirePublicProfileViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D23F3B2881A5E7C08D90A767 /* FirePublicProfileViewController.swift */; }; 7A1883792B3FD63EAEAA8336 /* SessionState+Helpers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3FC109FBAA1787EF49336258 /* SessionState+Helpers.swift */; }; 7A7A14663C8D777827CA6768 /* FireWidgetSnapshotWriter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E86F61501D5E51FA1584156 /* FireWidgetSnapshotWriter.swift */; }; 7B1B888CA814A35E5354CA0D /* FireHomeScopePresentation.swift in Sources */ = {isa = PBXBuildFile; fileRef = E355FDE3F6E9A5FFB6229374 /* FireHomeScopePresentation.swift */; }; 7B772557813420536690D938 /* FireAppViewModel+Diagnostics.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1F1F872C6062881E7513980D /* FireAppViewModel+Diagnostics.swift */; }; + 7C8E2507194A4B1C79F2BF4B /* fire_uniffi_session.swift in Sources */ = {isa = PBXBuildFile; fileRef = 48A7EA25CD5ADF94676BE48E /* fire_uniffi_session.swift */; }; 7CB85DA7DE5A93B262C29757 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 40B24CD54573A1C053B37121 /* PrivacyInfo.xcprivacy */; }; 7EFB42D38DCA6C0F63720AE3 /* FirePostCellNode+Reactions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A763199D74A1026B2ADB530 /* FirePostCellNode+Reactions.swift */; }; + 800930BED241B0CF61E5FD0A /* fire_uniffi_types.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0F09DBDDAC9BA75DCC865D23 /* fire_uniffi_types.swift */; }; 8146E8382FB40C8617EF19B7 /* FireWebViewCookieActionSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5103D4725A903220359B1C42 /* FireWebViewCookieActionSupportTests.swift */; }; 8169E3FD365AE9F655517F7C /* FireTopicDetailArticleSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8928D817CE60A917A5BA0C9 /* FireTopicDetailArticleSnapshot.swift */; }; 816DB34CD28CD94ED88EF9C6 /* FirePaginatedStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D0D5E6727E0D21855DDEA2F /* FirePaginatedStore.swift */; }; @@ -156,6 +162,7 @@ 94474296599507819BE086D1 /* FireTopicDetailKeyboardLayoutTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 456ECA20E14DB2A1CB683621 /* FireTopicDetailKeyboardLayoutTests.swift */; }; 957DADCF16F936D3BCCDE7F5 /* FireAppServiceHost.swift in Sources */ = {isa = PBXBuildFile; fileRef = E083189F2BF692A04EB7CF23 /* FireAppServiceHost.swift */; }; 9726B24BBA832290EA063E8F /* libiconv.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = FD5A94769988E39B8BEA7B56 /* libiconv.tbd */; }; + 974A21358F0BAA6942E6FDFC /* fire_uniffi_messagebus.swift in Sources */ = {isa = PBXBuildFile; fileRef = E5B34317DAE5858951DCD928 /* fire_uniffi_messagebus.swift */; }; 9912E13751119248F5626F77 /* FireMainTabBarController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6CABC863F0E7DDEACF5B980D /* FireMainTabBarController.swift */; }; 997549C307522F353C2C4354 /* FireWebViewBrowserProfile.swift in Sources */ = {isa = PBXBuildFile; fileRef = E6A1ACC49B5E391857645187 /* FireWebViewBrowserProfile.swift */; }; 9B0DABDC5BA87A4CAFF3232D /* FireEntityStateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = BADC2ED47CF65AD5BE795908 /* FireEntityStateTests.swift */; }; @@ -163,12 +170,14 @@ 9E7B9F6741C79AF8E6C3D0DA /* FirePostLayoutManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A1B0239607F0ABAEA1ABCE0 /* FirePostLayoutManager.swift */; }; 9F734046F02B45409AD5F1C6 /* FireTopicListMessageBusRefreshTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 859219285EC36B189AF68256 /* FireTopicListMessageBusRefreshTests.swift */; }; A04B275253CDF8FAAC9D8C6C /* FireSearchStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 25FD219C2BFB0727FD0D3DD2 /* FireSearchStore.swift */; }; + A04F6299B25D5CC6C7D21B14 /* fire_uniffi_chat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 25741FA2801D3AD5A8DDD0C0 /* fire_uniffi_chat.swift */; }; A07A9808A87A0F9C08F72CC3 /* FireAccountStatusView.swift in Sources */ = {isa = PBXBuildFile; fileRef = FF475D56C78AFC82413AED55 /* FireAccountStatusView.swift */; }; A29E21413FA011161D518004 /* FireSessionStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8834ADE6E3ADB8A03391560C /* FireSessionStore.swift */; }; A2BA00121D5BF00E4543EF13 /* FireMotionEffects.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F51908C9A24B5866A517797 /* FireMotionEffects.swift */; }; A2C954EBAE5163E708B3F189 /* FirePostImageNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8092585A18BAFAC8ECAB670D /* FirePostImageNode.swift */; }; A2F884CB6FB920BCEA213B94 /* FireViewProfileIntent.swift in Sources */ = {isa = PBXBuildFile; fileRef = B680C9357B6A7ACD65F6B211 /* FireViewProfileIntent.swift */; }; A31CB94E768166B1D7907774 /* FireProfileHeaderComponents.swift in Sources */ = {isa = PBXBuildFile; fileRef = 631A4F82AE7302B3D139F94C /* FireProfileHeaderComponents.swift */; }; + A37D27214981E5D36E7DFD2C /* fire_uniffi_notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = FF89DCFCD77D9F81CD8DB801 /* fire_uniffi_notifications.swift */; }; A7657EA99808CEBE3F038176 /* CrashReporter in Frameworks */ = {isa = PBXBuildFile; productRef = 601B450FB4E87A5243FAE5F9 /* CrashReporter */; }; ABCB88B6D78156FB353E922B /* FireDiagnosticsViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2E4063863B8521F7719DD75F /* FireDiagnosticsViewModel.swift */; }; B0AA426C24E27249B4AE2E57 /* FireAppViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6C063DC3D3814082F9655534 /* FireAppViewModel.swift */; }; @@ -184,6 +193,7 @@ BB6794B89B439C61B8A5620C /* FireFeedbackPresenter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4F2E6EEDE9F6AACB5DBE9B79 /* FireFeedbackPresenter.swift */; }; BBE9EB26A016A92092A4D0F2 /* FireTopicDetailPageSkeleton.swift in Sources */ = {isa = PBXBuildFile; fileRef = B3C653495E2307C802BB389A /* FireTopicDetailPageSkeleton.swift */; }; BD0F6BE28D1D0143383BAF2A /* FireProfileStatsRow.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8C1BF19AD44A73E451313B6 /* FireProfileStatsRow.swift */; }; + BD294B1545CC5167CAB3620E /* fire_uniffi_search.swift in Sources */ = {isa = PBXBuildFile; fileRef = C37B06D0B580C355652E1934 /* fire_uniffi_search.swift */; }; BDBF0CEBD8F5F7C1C19769B7 /* FireMessageBusCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0C11839708BD8C370EB52334 /* FireMessageBusCoordinator.swift */; }; BE531BCFF96A8C23E0180F6B /* FireLogDiagnosticsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 429B9F8B7087E197A8366D2D /* FireLogDiagnosticsView.swift */; }; BE820074BC6560ABBCF9BAFB /* SnapKit in Frameworks */ = {isa = PBXBuildFile; productRef = 92E5B8F5C5B099E404AB7A52 /* SnapKit */; }; @@ -250,6 +260,7 @@ F3EE595ECC3F647D419D1833 /* FireSmallWidget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 44E64FAEF7CBC79DBC2491BB /* FireSmallWidget.swift */; }; F41EBD87EC59341D3A7DD381 /* FireOnboardingCredentialFormView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F112BF5A6A226C1D21861F90 /* FireOnboardingCredentialFormView.swift */; }; F4E23711C352DB67C48DDEDA /* FireUIKitSkeleton.swift in Sources */ = {isa = PBXBuildFile; fileRef = F45FD2D6B300FDC58C2FD04A /* FireUIKitSkeleton.swift */; }; + F53E86700CE39C9DD948CFF6 /* fire_uniffi_diagnostics.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1800DA0F94ED3D7B3099DB89 /* fire_uniffi_diagnostics.swift */; }; F6B73F0BFAB8573C89C89CCA /* FireTextureAttributedText.swift in Sources */ = {isa = PBXBuildFile; fileRef = 852D9E719DC6FE610CC4F084 /* FireTextureAttributedText.swift */; }; F6C8A1554FC2C48FB67706A3 /* FireChatViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5D9CBC157BF5867CEBE3B65B /* FireChatViewController.swift */; }; F7F1533B87EEF235D54BA201 /* FireAppRoutePresentationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0AE9014C1B335916BCACBC54 /* FireAppRoutePresentationTests.swift */; }; @@ -308,6 +319,7 @@ 0C933069DE6C026030AAB6EF /* FireTests.xctest */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.cfbundle; path = FireTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 0D70983A36756650D4B734B7 /* FirePostCellNode+Body.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FirePostCellNode+Body.swift"; sourceTree = ""; }; 0DB69FD096A581A18D9D16C5 /* Fire-Local-Release.example.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Fire-Local-Release.example.xcconfig"; sourceTree = ""; }; + 0F09DBDDAC9BA75DCC865D23 /* fire_uniffi_types.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = fire_uniffi_types.swift; sourceTree = ""; }; 0F45C6AFED397DB19D9A361E /* FireMessageBusCoordinatorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireMessageBusCoordinatorTests.swift; sourceTree = ""; }; 10DDE042BE2C24CFD782C785 /* FireTopicDetailStore+Reactions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailStore+Reactions.swift"; sourceTree = ""; }; 1127D7C4622ADFEED430046E /* FireExportDiagnosticsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireExportDiagnosticsView.swift; sourceTree = ""; }; @@ -316,6 +328,7 @@ 1481ACDF04D249FF61B1D0DF /* FireDeveloperToolsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireDeveloperToolsView.swift; sourceTree = ""; }; 149C3D9916D55374B1B4A37C /* FireAppRouteControllerFactory.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAppRouteControllerFactory.swift; sourceTree = ""; }; 151CF08DEE9DBAE7D98495AC /* FireTopicPostStateFixtures.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicPostStateFixtures.swift; sourceTree = ""; }; + 1800DA0F94ED3D7B3099DB89 /* fire_uniffi_diagnostics.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = fire_uniffi_diagnostics.swift; sourceTree = ""; }; 1D0C004FB6FE17D6896FF17C /* FireTopicDetailCommentListSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailCommentListSnapshot.swift; sourceTree = ""; }; 1EDE93D07235A87438E6E563 /* FireRenderPresentation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireRenderPresentation.swift; sourceTree = ""; }; 1EF6B1D638EEA75C75B2B2D5 /* FirePostCellLayoutCalculatorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirePostCellLayoutCalculatorTests.swift; sourceTree = ""; }; @@ -327,6 +340,7 @@ 24186C615A12A722B2ABEE06 /* FireComponents.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireComponents.swift; sourceTree = ""; }; 242BD5DA9E84D24E217AFBBB /* FireNotificationPresentation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireNotificationPresentation.swift; sourceTree = ""; }; 24E7CCCA8B867D5E6B0CE198 /* FirePostCellLayoutCalculator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirePostCellLayoutCalculator.swift; sourceTree = ""; }; + 25741FA2801D3AD5A8DDD0C0 /* fire_uniffi_chat.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = fire_uniffi_chat.swift; sourceTree = ""; }; 25A9FA3A65196B334165E0C6 /* FireMotionUIKitTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireMotionUIKitTests.swift; sourceTree = ""; }; 25FD219C2BFB0727FD0D3DD2 /* FireSearchStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireSearchStore.swift; sourceTree = ""; }; 2641F70C8CEAE937D1D4A75D /* FireTopicDetailStore+Presence.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FireTopicDetailStore+Presence.swift"; sourceTree = ""; }; @@ -373,6 +387,7 @@ 46CF09F1CBAC6CFAA0E9128A /* FireAppRoute.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAppRoute.swift; sourceTree = ""; }; 480E9E260E7348B77576F392 /* FireInlineReactionPickerScrollNode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireInlineReactionPickerScrollNode.swift; sourceTree = ""; }; 48153CE6A692130B4F8D97C5 /* FireHomeScopeChromeViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireHomeScopeChromeViews.swift; sourceTree = ""; }; + 48A7EA25CD5ADF94676BE48E /* fire_uniffi_session.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = fire_uniffi_session.swift; sourceTree = ""; }; 48CAB0E38556929FC140E25D /* Fire.app */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.application; path = Fire.app; sourceTree = BUILT_PRODUCTS_DIR; }; 49784F572BD41F7D9F024F55 /* FirePostFlagSheet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirePostFlagSheet.swift; sourceTree = ""; }; 4B2A79D53BB06F4FE60BE258 /* FireBottomInputBarTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireBottomInputBarTests.swift; sourceTree = ""; }; @@ -446,6 +461,7 @@ 9B970247E0258DD4D4F34101 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; 9D354D83C07C326288699E3D /* FireAppearanceEnvironment.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAppearanceEnvironment.swift; sourceTree = ""; }; 9E0BF86E469C2F6F845BBC27 /* FireWidgetEntry.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireWidgetEntry.swift; sourceTree = ""; }; + 9F1F015314914FD74B56CC5D /* fire_uniffi_user.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = fire_uniffi_user.swift; sourceTree = ""; }; 9F51908C9A24B5866A517797 /* FireMotionEffects.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireMotionEffects.swift; sourceTree = ""; }; A0AFFF5DCC989B801C9DF88E /* Fire-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Fire-Debug.xcconfig"; sourceTree = ""; }; A156E14A65C530B5582956CC /* FireRichTextRenderer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireRichTextRenderer.swift; sourceTree = ""; }; @@ -454,6 +470,7 @@ A283C548CFC6BEDC0D406679 /* FireTopicDetailVisibilityCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailVisibilityCoordinator.swift; sourceTree = ""; }; A5264103A412DF3C9798D470 /* FireAPMModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAPMModels.swift; sourceTree = ""; }; A67A6C835A2196246871D5FD /* FireComposerValidationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireComposerValidationTests.swift; sourceTree = ""; }; + A680E7A822BDD20CE84C04EE /* fire_uniffi_ldc.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = fire_uniffi_ldc.swift; sourceTree = ""; }; AA736A1F443337C34A6E33D6 /* Fire.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Fire.entitlements; sourceTree = ""; }; ABA36C072D3004B0CFDF73D3 /* FireCloudflareChallengeCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireCloudflareChallengeCoordinator.swift; sourceTree = ""; }; AD777ED45F66FF150D5AD9C0 /* FireBottomInputBar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireBottomInputBar.swift; sourceTree = ""; }; @@ -484,6 +501,7 @@ C20BDF82CCD1BF22BB3C7729 /* FireAPMMainThreadStallMonitor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAPMMainThreadStallMonitor.swift; sourceTree = ""; }; C313FFDD8D569FA6D9B1C0E0 /* FireAuthCookieKeychainStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAuthCookieKeychainStore.swift; sourceTree = ""; }; C32FFB215F2C0CDDE5C1221C /* FireTopicOneboxNode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicOneboxNode.swift; sourceTree = ""; }; + C37B06D0B580C355652E1934 /* fire_uniffi_search.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = fire_uniffi_search.swift; sourceTree = ""; }; C3ECAD5FF1893C381DB94E34 /* FireSettingsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireSettingsViewController.swift; sourceTree = ""; }; C65C6A52FE7362DF04A8445B /* FireRichTextHeightConsistencyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireRichTextHeightConsistencyTests.swift; sourceTree = ""; }; C6DEF53357E681E40E482813 /* FireAPMResourceSampler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAPMResourceSampler.swift; sourceTree = ""; }; @@ -504,6 +522,7 @@ DC543177753C32906EE6BE24 /* FireHomeView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireHomeView.swift; sourceTree = ""; }; DCE4042C9DCEB3DD3BEC7892 /* FirePrivateMessagesView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirePrivateMessagesView.swift; sourceTree = ""; }; DDC30347DC7392AAA6A27435 /* FireTopicDetailControllerHost.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailControllerHost.swift; sourceTree = ""; }; + DDCE76B3F360C1C5631A950C /* fire_uniffi_topics.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = fire_uniffi_topics.swift; sourceTree = ""; }; DFBA718C5E89D3669A9C6D22 /* FireTopicDetailStoreTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailStoreTests.swift; sourceTree = ""; }; E083189F2BF692A04EB7CF23 /* FireAppServiceHost.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAppServiceHost.swift; sourceTree = ""; }; E0AA3F1257384BF109634D21 /* FireTheme.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTheme.swift; sourceTree = ""; }; @@ -512,6 +531,7 @@ E436AB70851CCBCFCD8B8D96 /* FireTopicDetailInteractionCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicDetailInteractionCoordinator.swift; sourceTree = ""; }; E4616E00DD2F43C18973E520 /* FireUIKitErrorBannerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireUIKitErrorBannerView.swift; sourceTree = ""; }; E4AF197F76705D49E465A05B /* FireDohSourceViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireDohSourceViewController.swift; sourceTree = ""; }; + E5B34317DAE5858951DCD928 /* fire_uniffi_messagebus.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = fire_uniffi_messagebus.swift; sourceTree = ""; }; E5FFB93F34563ABE34B99183 /* FireUIKitDesignLanguage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireUIKitDesignLanguage.swift; sourceTree = ""; }; E650ABD9C06621BC41908D59 /* FireContextMenus.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireContextMenus.swift; sourceTree = ""; }; E66E1B11B9D76557B4BB0603 /* FireTopicListMessageBusRefresh.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicListMessageBusRefresh.swift; sourceTree = ""; }; @@ -528,6 +548,7 @@ ECBDE8779B6F7E32204263F4 /* FireTopicPresentation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicPresentation.swift; sourceTree = ""; }; EDE93F98F58126B7BEDDB4F7 /* FireTopicTimingTrackerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireTopicTimingTrackerTests.swift; sourceTree = ""; }; EF66373F7EF72A887F722CF0 /* FireMotionUIKit.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireMotionUIKit.swift; sourceTree = ""; }; + EF98E1072E78DFC9F5057D67 /* fire_uniffi.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = fire_uniffi.swift; sourceTree = ""; }; EFE429D39ACE68653A226FE9 /* FireProfileActivityTimelineView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireProfileActivityTimelineView.swift; sourceTree = ""; }; F01E5248AEF9002E2919AC0F /* FireCfClearanceRefreshService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireCfClearanceRefreshService.swift; sourceTree = ""; }; F112BF5A6A226C1D21861F90 /* FireOnboardingCredentialFormView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireOnboardingCredentialFormView.swift; sourceTree = ""; }; @@ -543,6 +564,7 @@ FB21BB9232240035114A9653 /* FireProfileBadgeChip.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireProfileBadgeChip.swift; sourceTree = ""; }; FD5A94769988E39B8BEA7B56 /* libiconv.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libiconv.tbd; path = usr/lib/libiconv.tbd; sourceTree = SDKROOT; }; FF475D56C78AFC82413AED55 /* FireAccountStatusView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireAccountStatusView.swift; sourceTree = ""; }; + FF89DCFCD77D9F81CD8DB801 /* fire_uniffi_notifications.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = fire_uniffi_notifications.swift; sourceTree = ""; }; FFB6B1F10783D1D78B2D1F63 /* FireListSectionModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FireListSectionModel.swift; sourceTree = ""; }; /* End PBXFileReference section */ @@ -974,6 +996,7 @@ 73EB36381D2DB9DA74378162 /* App */, BD212BBA5E9DA62F41FF41F4 /* Configs */, 32338F9E71B0E67C5112C300 /* FireAppSession */, + F6A48714E0F87937027A25E4 /* FireUniFfi */, 7044DC07E4881033F1BC8F64 /* FireWidget */, 8FCD2C1B029D07F4C1B82746 /* Unit */, 9C9371C0E9747855874B64BD /* Widgets */, @@ -1212,6 +1235,25 @@ path = Core; sourceTree = ""; }; + F6A48714E0F87937027A25E4 /* FireUniFfi */ = { + isa = PBXGroup; + children = ( + 25741FA2801D3AD5A8DDD0C0 /* fire_uniffi_chat.swift */, + 1800DA0F94ED3D7B3099DB89 /* fire_uniffi_diagnostics.swift */, + A680E7A822BDD20CE84C04EE /* fire_uniffi_ldc.swift */, + E5B34317DAE5858951DCD928 /* fire_uniffi_messagebus.swift */, + FF89DCFCD77D9F81CD8DB801 /* fire_uniffi_notifications.swift */, + C37B06D0B580C355652E1934 /* fire_uniffi_search.swift */, + 48A7EA25CD5ADF94676BE48E /* fire_uniffi_session.swift */, + DDCE76B3F360C1C5631A950C /* fire_uniffi_topics.swift */, + 0F09DBDDAC9BA75DCC865D23 /* fire_uniffi_types.swift */, + 9F1F015314914FD74B56CC5D /* fire_uniffi_user.swift */, + EF98E1072E78DFC9F5057D67 /* fire_uniffi.swift */, + ); + name = FireUniFfi; + path = Generated/FireUniFfi; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -1633,6 +1675,17 @@ 0829CF9A9EE33EA119F94468 /* FireWidgetData.swift in Sources */, 7A7A14663C8D777827CA6768 /* FireWidgetSnapshotWriter.swift in Sources */, 7A1883792B3FD63EAEAA8336 /* SessionState+Helpers.swift in Sources */, + 4F762CD9E7B43DB0534791C8 /* fire_uniffi.swift in Sources */, + A04F6299B25D5CC6C7D21B14 /* fire_uniffi_chat.swift in Sources */, + F53E86700CE39C9DD948CFF6 /* fire_uniffi_diagnostics.swift in Sources */, + 79B77A4E828C4862BE1BAA53 /* fire_uniffi_ldc.swift in Sources */, + 974A21358F0BAA6942E6FDFC /* fire_uniffi_messagebus.swift in Sources */, + A37D27214981E5D36E7DFD2C /* fire_uniffi_notifications.swift in Sources */, + BD294B1545CC5167CAB3620E /* fire_uniffi_search.swift in Sources */, + 7C8E2507194A4B1C79F2BF4B /* fire_uniffi_session.swift in Sources */, + 26E51A13E796BFEF885FBD28 /* fire_uniffi_topics.swift in Sources */, + 800930BED241B0CF61E5FD0A /* fire_uniffi_types.swift in Sources */, + 3AFFAE192ADFE0FE4E054809 /* fire_uniffi_user.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; From 001a52b6dad420861f806dbcfa6c2e5ca38bc656 Mon Sep 17 00:00:00 2001 From: fannnzhang Date: Tue, 22 Sep 2026 21:21:04 +0800 Subject: [PATCH 04/11] fix(ios): use boundTopicDetailStore after private store access Profile and route hosts still read topicDetailStore after it became private, which broke the iOS Test CI compile. Co-authored-by: Cursor --- native/ios-app/App/Routing/FireAppRouteDestinationView.swift | 2 +- .../App/Views/Profile/FireFollowListViewController.swift | 2 +- .../App/Views/Profile/FireProfileActivityTimelineView.swift | 2 +- native/ios-app/App/Views/Profile/FireProfileView.swift | 2 +- native/ios-app/App/Views/Profile/FirePublicProfileView.swift | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/native/ios-app/App/Routing/FireAppRouteDestinationView.swift b/native/ios-app/App/Routing/FireAppRouteDestinationView.swift index 200f7789..d7c049d3 100644 --- a/native/ios-app/App/Routing/FireAppRouteDestinationView.swift +++ b/native/ios-app/App/Routing/FireAppRouteDestinationView.swift @@ -56,7 +56,7 @@ struct FirePublicProfileControllerHost: UIViewControllerRepresentable { ) { self.viewModel = viewModel self.username = username - self.topicDetailStore = viewModel.topicDetailStore ?? FireTopicDetailStore(appViewModel: viewModel) + self.topicDetailStore = viewModel.boundTopicDetailStore ?? FireTopicDetailStore(appViewModel: viewModel) self.topicRoutePresenter = topicRoutePresenter } diff --git a/native/ios-app/App/Views/Profile/FireFollowListViewController.swift b/native/ios-app/App/Views/Profile/FireFollowListViewController.swift index 71c8b592..0f63bf70 100644 --- a/native/ios-app/App/Views/Profile/FireFollowListViewController.swift +++ b/native/ios-app/App/Views/Profile/FireFollowListViewController.swift @@ -428,7 +428,7 @@ struct FireFollowListControllerHost: UIViewControllerRepresentable { self.viewModel = viewModel self.username = username self.kind = kind - self.topicDetailStore = viewModel.topicDetailStore ?? FireTopicDetailStore(appViewModel: viewModel) + self.topicDetailStore = viewModel.boundTopicDetailStore ?? FireTopicDetailStore(appViewModel: viewModel) } func makeUIViewController(context: Context) -> FireFollowListViewController { diff --git a/native/ios-app/App/Views/Profile/FireProfileActivityTimelineView.swift b/native/ios-app/App/Views/Profile/FireProfileActivityTimelineView.swift index 4b1b5dba..3132387d 100644 --- a/native/ios-app/App/Views/Profile/FireProfileActivityTimelineView.swift +++ b/native/ios-app/App/Views/Profile/FireProfileActivityTimelineView.swift @@ -17,7 +17,7 @@ struct FireProfileActivityTimelineView: View { ) { self.viewModel = viewModel self.profileViewModel = profileViewModel - self.topicDetailStore = topicDetailStore ?? viewModel.topicDetailStore ?? FireTopicDetailStore(appViewModel: viewModel) + self.topicDetailStore = topicDetailStore ?? viewModel.boundTopicDetailStore ?? FireTopicDetailStore(appViewModel: viewModel) } var body: some View { diff --git a/native/ios-app/App/Views/Profile/FireProfileView.swift b/native/ios-app/App/Views/Profile/FireProfileView.swift index a692a054..dbfc931a 100644 --- a/native/ios-app/App/Views/Profile/FireProfileView.swift +++ b/native/ios-app/App/Views/Profile/FireProfileView.swift @@ -636,7 +636,7 @@ struct FireProfileView: View { FireAppRouteControllerFactory.presentSecondaryRoute( route, viewModel: viewModel, - topicDetailStore: viewModel.topicDetailStore ?? FireTopicDetailStore(appViewModel: viewModel) + topicDetailStore: viewModel.boundTopicDetailStore ?? FireTopicDetailStore(appViewModel: viewModel) ) return } diff --git a/native/ios-app/App/Views/Profile/FirePublicProfileView.swift b/native/ios-app/App/Views/Profile/FirePublicProfileView.swift index bbd687ac..874b708e 100644 --- a/native/ios-app/App/Views/Profile/FirePublicProfileView.swift +++ b/native/ios-app/App/Views/Profile/FirePublicProfileView.swift @@ -467,7 +467,7 @@ struct FirePublicProfileView: View { FireAppRouteControllerFactory.presentSecondaryRoute( route, viewModel: viewModel, - topicDetailStore: viewModel.topicDetailStore ?? FireTopicDetailStore(appViewModel: viewModel) + topicDetailStore: viewModel.boundTopicDetailStore ?? FireTopicDetailStore(appViewModel: viewModel) ) return } From 1f760d60f95375675b8181c3743142600fb01d37 Mon Sep 17 00:00:00 2001 From: fannnzhang Date: Tue, 22 Sep 2026 21:32:50 +0800 Subject: [PATCH 05/11] ci: drop Windows from Rust Host Test matrix Fire targets iOS and Android only; the windows-latest host-test job was unused product coverage and wasted CI minutes. Co-authored-by: Cursor --- .github/workflows/ci.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 77bee3e8..9a24945e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -69,7 +69,6 @@ jobs: matrix: os: - ubuntu-24.04 - - windows-latest - macos-15 steps: From ba4eea943d5a09d794395d0468dc5d3890fe3e76 Mon Sep 17 00:00:00 2001 From: fannnzhang Date: Tue, 22 Sep 2026 21:49:48 +0800 Subject: [PATCH 06/11] fix(ios): unblock TopicDetailSession MainActor compile Mark topic-detail open/cancel/close as nonisolated on FireSessionStore so the MainActor store can open handles synchronously, and replace the four-UInt64 tuple with an Equatable revision fingerprint for Combine. Co-authored-by: Cursor --- .../2026-09-22-ios-topic-detail-session.md | 4 ++- .../FireTopicDetailViewController.swift | 35 +++++++++++-------- .../FireAppSession/FireSessionStore.swift | 8 +++-- 3 files changed, 29 insertions(+), 18 deletions(-) diff --git a/docs/architecture/2026-09-22-ios-topic-detail-session.md b/docs/architecture/2026-09-22-ios-topic-detail-session.md index 8502faac..a4092523 100644 --- a/docs/architecture/2026-09-22-ios-topic-detail-session.md +++ b/docs/architecture/2026-09-22-ios-topic-detail-session.md @@ -950,9 +950,11 @@ final class FireTopicDetailSnapshotSink: TopicDetailObserver, @unchecked Sendabl `apply`:若 `generation` 不旧于已应用值,替换 `snapshots[id]`;若 `homeRowPatch != nil`,调 `FireAppViewModel.applyHomeRowCountPatch`。不合并行。 +`FireSessionStore.openTopicDetail` / `cancelTopicDetailHttp` / `closeAllTopicDetailSessions` 标为 `nonisolated`:只碰 `core` UniFFI,供 `@MainActor` 的 `FireTopicDetailStore` 同步拿到 handle,不进 session actor 队列。 + `FireHomeFeedStore.applyHomeRowCountPatch` 替换 `patchTopicCounts`。同一 PR 删除 `patchedTopicRow` 与 `patchTopicCounts`。`FireTopicDetailModalRouter.presentBookmarkEditor` 的话题详情 `onReload` 不再调用 `loadTopicDetail`;保存和删除改走 store 的 create / update / delete bookmark。`presentTopicBookmarkEditor` / `presentPostBookmarkEditor` 同样改。 -VC `buildCurrentFeedState` 改为读 `snapshot.rows`、`phase`、`hasMore`、`collectionRevision`、`scrollTarget`。`buildCurrentInteractionState` 只保留三个 expanded 集合。`mutating` / reply-context loading 来自行字段。`canWriteInteractions`、`baseURLString`、`minimumReplyLength` 仍从 session / bootstrap 读。Combine 从多个 revision 字典改成 `$snapshots` 按 `collection` / `chrome` / `sidecar` / `interaction` 去重。本地展开仍走 `applyLocalInteractionSnapshot`,主线程,不经 Rust。 +VC `buildCurrentFeedState` 改为读 `snapshot.rows`、`phase`、`hasMore`、`collectionRevision`、`scrollTarget`。`buildCurrentInteractionState` 只保留三个 expanded 集合。`mutating` / reply-context loading 来自行字段。`canWriteInteractions`、`baseURLString`、`minimumReplyLength` 仍从 session / bootstrap 读。Combine 从多个 revision 字典改成 `$snapshots`,用 `FireTopicDetailRevisionFingerprint`(`Equatable`)按 `collection` / `chrome` / `sidecar` / `interaction` 去重。本地展开仍走 `applyLocalInteractionSnapshot`,主线程,不经 Rust。 `FireTopicDetailRuntimeConfiguration` 丢掉 `detail: TopicDetailState?` 与 `postLookup`。builder 用行 DTO,再把本地 chrome 折进 token。禁止把 `contentToken` 或 `inPlaceUpdateToken` 设成裸的 Rust checksum。管道 `apply` 的三档判断不改。 diff --git a/native/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController.swift b/native/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController.swift index ccaaf07a..f00c3d18 100644 --- a/native/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController.swift +++ b/native/ios-app/App/TopicDetail/Controller/FireTopicDetailViewController.swift @@ -6,6 +6,13 @@ import UniformTypeIdentifiers private let fireTopicDetailSnapshotBuildDiagnosticThresholdMs: Int64 = 50 private let fireTopicDetailSnapshotApplyDiagnosticThresholdMs: Int64 = 16 +private struct FireTopicDetailRevisionFingerprint: Equatable { + let collection: UInt64 + let chrome: UInt64 + let sidecar: UInt64 + let interaction: UInt64 +} + @MainActor final class FireTopicDetailViewController: UIViewController, UIGestureRecognizerDelegate { let viewModel: FireAppViewModel @@ -836,27 +843,27 @@ final class FireTopicDetailViewController: UIViewController, UIGestureRecognizer func subscribeToStoreRevisions() { let topicId = row.topic.id topicDetailStore.$snapshots - .map { snapshots -> (UInt64, UInt64, UInt64, UInt64) in + .map { snapshots -> FireTopicDetailRevisionFingerprint in let snapshot = snapshots[topicId] - return ( - snapshot?.collectionRevision ?? 0, - snapshot?.chromeRevision ?? 0, - snapshot?.sidecarRevision ?? 0, - snapshot?.interactionRevision ?? 0 + return FireTopicDetailRevisionFingerprint( + collection: snapshot?.collectionRevision ?? 0, + chrome: snapshot?.chromeRevision ?? 0, + sidecar: snapshot?.sidecarRevision ?? 0, + interaction: snapshot?.interactionRevision ?? 0 ) } .removeDuplicates() .receive(on: RunLoop.main) .sink { [weak self] revisions in guard let self else { return } - let collectionChanged = revisions.0 != self.lastAppliedCollectionRevision - let chromeChanged = revisions.1 != self.lastAppliedChromeRevision - let sidecarChanged = revisions.2 != self.lastAppliedSidecarRevision - let interactionChanged = revisions.3 != self.lastAppliedInteractionRevision - self.lastAppliedCollectionRevision = revisions.0 - self.lastAppliedChromeRevision = revisions.1 - self.lastAppliedSidecarRevision = revisions.2 - self.lastAppliedInteractionRevision = revisions.3 + let collectionChanged = revisions.collection != self.lastAppliedCollectionRevision + let chromeChanged = revisions.chrome != self.lastAppliedChromeRevision + let sidecarChanged = revisions.sidecar != self.lastAppliedSidecarRevision + let interactionChanged = revisions.interaction != self.lastAppliedInteractionRevision + self.lastAppliedCollectionRevision = revisions.collection + self.lastAppliedChromeRevision = revisions.chrome + self.lastAppliedSidecarRevision = revisions.sidecar + self.lastAppliedInteractionRevision = revisions.interaction if chromeChanged { self.buildAndApplyChromeState() diff --git a/native/ios-app/Sources/FireAppSession/FireSessionStore.swift b/native/ios-app/Sources/FireAppSession/FireSessionStore.swift index 73c0dfb7..ff3ec6d9 100644 --- a/native/ios-app/Sources/FireAppSession/FireSessionStore.swift +++ b/native/ios-app/Sources/FireAppSession/FireSessionStore.swift @@ -117,15 +117,17 @@ public actor FireSessionStore { try core.session().completeReadPathLogin(generation: generation, succeeded: succeeded) } - public func cancelTopicDetailHttp() { + /// Topic-detail session open/cancel/close only touch UniFFI/`core` and must stay + /// callable from `@MainActor` hosts without hopping onto the session actor. + public nonisolated func cancelTopicDetailHttp() { try? core.topics().cancelTopicDetailHttp() } - public func closeAllTopicDetailSessions() { + public nonisolated func closeAllTopicDetailSessions() { try? core.topics().closeAllTopicDetailSessions() } - public func openTopicDetail( + public nonisolated func openTopicDetail( request: TopicDetailOpenRequestState, observer: TopicDetailObserver ) throws -> TopicDetailSessionHandle { From bc8784530794a1c88e5767ccc9d52be65aeedab2 Mon Sep 17 00:00:00 2001 From: fannnzhang Date: Tue, 22 Sep 2026 22:04:47 +0800 Subject: [PATCH 07/11] fix(ios): align topic-detail hosts with session store API Use camelCase topicId/postId labels, read vote/flag state from UI snapshots, and accept TopicDetailTypingUserState in the assembler. Co-authored-by: Cursor --- ...ireTopicDetailInteractionCoordinator.swift | 12 ++++++------ .../FireTopicDetailModalRouter.swift | 19 +++++++++++++------ .../FireTopicDetailSnapshotAssembler.swift | 2 +- 3 files changed, 20 insertions(+), 13 deletions(-) diff --git a/native/ios-app/App/TopicDetail/Controller/FireTopicDetailInteractionCoordinator.swift b/native/ios-app/App/TopicDetail/Controller/FireTopicDetailInteractionCoordinator.swift index 49873f18..638c72e9 100644 --- a/native/ios-app/App/TopicDetail/Controller/FireTopicDetailInteractionCoordinator.swift +++ b/native/ios-app/App/TopicDetail/Controller/FireTopicDetailInteractionCoordinator.swift @@ -197,8 +197,8 @@ extension FireTopicDetailViewController { Task { @MainActor in do { try await topicDetailStore.deletePost( - topicID: topic.id, - postID: context.postID + topicId: topic.id, + postId: context.postID ) modalRouter.presentNotice(message: "已删除 #\(context.postNumber)。") } catch { @@ -212,8 +212,8 @@ extension FireTopicDetailViewController { Task { @MainActor in do { try await topicDetailStore.recoverPost( - topicID: topic.id, - postID: context.postID + topicId: topic.id, + postId: context.postID ) modalRouter.presentNotice(message: "已恢复 #\(context.postNumber)。") } catch { @@ -223,11 +223,11 @@ extension FireTopicDetailViewController { } func toggleTopicVote() async { - guard let detail else { return } + let userVoted = detailSnapshot?.chrome.userVoted ?? false do { _ = try await viewModel.topicInteraction.voteTopic( topicID: topic.id, - voted: !detail.userVoted, + voted: !userVoted, recoveryOriginURL: topicCloudflareRecoveryURL ) } catch { diff --git a/native/ios-app/App/TopicDetail/Controller/FireTopicDetailModalRouter.swift b/native/ios-app/App/TopicDetail/Controller/FireTopicDetailModalRouter.swift index 7292635f..9e18f4d0 100644 --- a/native/ios-app/App/TopicDetail/Controller/FireTopicDetailModalRouter.swift +++ b/native/ios-app/App/TopicDetail/Controller/FireTopicDetailModalRouter.swift @@ -327,16 +327,18 @@ private struct FireTopicDetailFlagSheetHost: View { let context: FirePostManagementContext let onSubmitted: @MainActor (String) -> Void + @State private var isLoadingOptions = false + var body: some View { FirePostFlagSheet( context: context, - options: FirePostFlagOption.options(from: store.postActionTypes), - isLoadingOptions: store.isLoadingPostActionTypes + options: FirePostFlagOption.options(from: store.snapshot(for: topicID)?.flagTypes ?? []), + isLoadingOptions: isLoadingOptions ) { option, message in try await store.flagPost( - topicID: topicID, - postID: context.postID, - flagTypeID: option.id, + topicId: topicID, + postId: context.postID, + flagTypeId: option.id, message: message ) await MainActor.run { @@ -344,7 +346,12 @@ private struct FireTopicDetailFlagSheetHost: View { } } .task { - await store.loadPostActionTypesIfNeeded() + guard (store.snapshot(for: topicID)?.flagTypes ?? []).isEmpty else { + return + } + isLoadingOptions = true + defer { isLoadingOptions = false } + try? await store.ensureFlagTypes(topicId: topicID) } } } diff --git a/native/ios-app/App/TopicDetail/State/FireTopicDetailSnapshotAssembler.swift b/native/ios-app/App/TopicDetail/State/FireTopicDetailSnapshotAssembler.swift index 24046beb..4a62d4e5 100644 --- a/native/ios-app/App/TopicDetail/State/FireTopicDetailSnapshotAssembler.swift +++ b/native/ios-app/App/TopicDetail/State/FireTopicDetailSnapshotAssembler.swift @@ -130,7 +130,7 @@ struct FireTopicDetailSnapshotAssembler: Sendable { ].joined(separator: "\u{1F}") } - private func typingSummary(from users: [TopicPresenceUserState]) -> String? { + private func typingSummary(from users: [TopicDetailTypingUserState]) -> String? { guard !users.isEmpty else { return nil } let names = users.prefix(3).map(\.username) let leading = names.joined(separator: "、") From 890f82af9255cac3ebaa88b2e8f825154391c67b Mon Sep 17 00:00:00 2001 From: fannnzhang Date: Tue, 22 Sep 2026 22:22:31 +0800 Subject: [PATCH 08/11] fix(ios): restore topic retention queries and session await usage Derive owned/mutating post state from UI snapshots, and fix short-circuit await plus actor-isolated completeReadPathLogin in applySession. Co-authored-by: Cursor --- .../ios-app/App/Stores/FireTopicDetailStore.swift | 10 ++++++++++ .../ios-app/App/ViewModels/FireAppViewModel.swift | 14 ++++++++++---- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/native/ios-app/App/Stores/FireTopicDetailStore.swift b/native/ios-app/App/Stores/FireTopicDetailStore.swift index 795d33e6..a8205923 100644 --- a/native/ios-app/App/Stores/FireTopicDetailStore.swift +++ b/native/ios-app/App/Stores/FireTopicDetailStore.swift @@ -19,6 +19,16 @@ final class FireTopicDetailStore: ObservableObject { snapshots[topicId] } + func ownedTopicIDs() -> Set { + Set(ownersByTopic.keys) + } + + func isMutatingPost(postId: UInt64) -> Bool { + snapshots.values.contains { snapshot in + snapshot.rows.contains { $0.postId == postId && $0.isMutating } + } + } + func open( topicId: UInt64, ownerToken: String, diff --git a/native/ios-app/App/ViewModels/FireAppViewModel.swift b/native/ios-app/App/ViewModels/FireAppViewModel.swift index 875742f3..b159e03e 100644 --- a/native/ios-app/App/ViewModels/FireAppViewModel.swift +++ b/native/ios-app/App/ViewModels/FireAppViewModel.swift @@ -857,8 +857,9 @@ final class FireAppViewModel: ObservableObject { } func retainedTopicDetailIDs(visibleTopicIDs: Set) -> Set { - topicDetailStore?.retainedTopicDetailIDs(visibleTopicIDs: visibleTopicIDs) - ?? visibleTopicIDs + // Owner refcount is the retention source of truth; keep any still-visible + // list rows so hosts can avoid premature eviction while scrolling. + (topicDetailStore?.ownedTopicIDs() ?? []).union(visibleTopicIDs) } // MARK: - Topic detail MessageBus subscription @@ -1365,9 +1366,14 @@ final class FireAppViewModel: ObservableObject { lastReadPathLoginGeneration = request.generation let operation = request.operation let recovered = await attemptHostCookieResyncRecovery(operation: operation) - let succeeded = recovered || await attemptMidSessionHeadlessReauth(operation: operation) + let succeeded: Bool + if recovered { + succeeded = true + } else { + succeeded = await attemptMidSessionHeadlessReauth(operation: operation) + } if let sessionStore = currentSessionStore() { - try? sessionStore.completeReadPathLogin( + try? await sessionStore.completeReadPathLogin( generation: request.generation, succeeded: succeeded ) From af35a95fc68e5da7f3d8986c988768d4e527db65 Mon Sep 17 00:00:00 2001 From: fannnzhang Date: Tue, 22 Sep 2026 22:41:14 +0800 Subject: [PATCH 09/11] fix(ios): return filtered availableReplyRows in feed model The non-snapshot branch was missing an explicit return, which failed the Xcode 27 Swift compile in iOS Test. Co-authored-by: Cursor --- .../App/TopicDetail/Feed/FireTopicDetailFeedModels.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/native/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedModels.swift b/native/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedModels.swift index 06a6ecf0..545c31a7 100644 --- a/native/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedModels.swift +++ b/native/ios-app/App/TopicDetail/Feed/FireTopicDetailFeedModels.swift @@ -475,7 +475,7 @@ struct FireTopicDetailRuntimeConfiguration: @unchecked Sendable { if snapshot != nil { return replyRows.filter { resolvedPostLookup[$0.entry.postId] != nil } } - replyRows.filter { + return replyRows.filter { postLookup[$0.entry.postId] != nil && renderState?.contentByPostID[$0.entry.postId] != nil } From 12174874c999b784f180b004fa094df295ee6d0a Mon Sep 17 00:00:00 2001 From: fannnzhang Date: Tue, 22 Sep 2026 22:55:24 +0800 Subject: [PATCH 10/11] fix(ios): return TopicPostState from UI row projection The projection helper had a local binding before constructing TopicPostState, so Swift required an explicit return. Co-authored-by: Cursor --- .../ios-app/App/TopicDetail/Support/FireTopicPresentation.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/native/ios-app/App/TopicDetail/Support/FireTopicPresentation.swift b/native/ios-app/App/TopicDetail/Support/FireTopicPresentation.swift index c9042ed3..091fcea2 100644 --- a/native/ios-app/App/TopicDetail/Support/FireTopicPresentation.swift +++ b/native/ios-app/App/TopicDetail/Support/FireTopicPresentation.swift @@ -1220,7 +1220,7 @@ enum FireTopicDetailUiProjection { static func post(from row: TopicDetailUiRowState) -> TopicPostState { let author = row.author - TopicPostState( + return TopicPostState( id: row.postId, username: author.username, name: author.name, From f07e6fad43c625566ebed2e6a9b40c67d1c6b4d3 Mon Sep 17 00:00:00 2001 From: fannnzhang Date: Tue, 22 Sep 2026 23:12:09 +0800 Subject: [PATCH 11/11] fix(ios): return layout content token fallback branch postLayoutContentToken omitted return on the non-snapshot path, which failed the Swift compile under Xcode 27. Co-authored-by: Cursor --- .../Feed/FireTopicDetailRuntimeSnapshotBuilder.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/native/ios-app/App/TopicDetail/Feed/FireTopicDetailRuntimeSnapshotBuilder.swift b/native/ios-app/App/TopicDetail/Feed/FireTopicDetailRuntimeSnapshotBuilder.swift index f8e3884d..70cd25ea 100644 --- a/native/ios-app/App/TopicDetail/Feed/FireTopicDetailRuntimeSnapshotBuilder.swift +++ b/native/ios-app/App/TopicDetail/Feed/FireTopicDetailRuntimeSnapshotBuilder.swift @@ -292,7 +292,7 @@ extension FireTopicDetailRuntimeConfiguration { String(textExpansionState.isCollapsible), ].joined(separator: "\u{1F}") } - [ + return [ String(post.id), FirePostAuthorMetadataDisplay.contentToken(for: post), renderContent?.signature.token ?? "pending",