constitution · epochs · watch · epoch 3

comparison

c_5e9a63e9d276 (tommy-mor) vs c_06fce70179bc (tommy-mor)

download prompt · raw event · cmp_08fbcb87e23c45

council reasoning

~anthropic/claude-sonnet-latest · winner B · 6:4 · permalink

Side B implements a real functional improvement (SSE-based async entity fetch with proper job result tracking, rate-limit handling, and updated JS/client integration plus adjusted integration test), delivering concrete new user-facing behavior. Side A is a large but purely mechanical type-renaming/relocation refactor (moving string helpers into newtypes) with no behavior change and even removes some test coverage duplicated elsewhere, offering less lasting functional value despite its size.

~x-ai/grok-latest · winner A · 2:1 · permalink

A permanently centralizes path canonicalization and room-aware hrefs into slug-types (GardenItemUrl/ForumThreadUrl/TildeOntologyPath) and types the API/RPC surface, replacing ad-hoc string helpers with a shared identity model. B’s SSE fetch pipeline and Reddit oneshot completion are real UX/architecture gains, but they are localized to one import flow and mix in logging/churn, so they add less cross-cutting lasting value than A’s path core.

openai/gpt-chat-latest · winner A · 4:1 · permalink

Side A performs a substantial architectural refactor by moving path canonicalization and URL construction into a shared `types::paths` module, replacing ad hoc string helpers with strongly typed `GardenItemUrl`, `ForumThreadUrl`, and `TildeOntologyPath` throughout the API and shared types. This centralizes path identity, reduces duplication, and makes JSON/RPC interfaces more type-safe, while preserving behavior via migrated tests; Side B adds useful SSE-based Reddit fetch streaming and UI updates, but it is a more localized feature with additional dependencies rather than a cross-cutting improvement to core project design.

sides

A — c_5e9a63e9d276 (tommy-mor)

message

[a888d56c] refactor: centralize path identity in slug-types

Move canonicalization and CanonicalItemUrl into types::paths with
GardenItemUrl, ForumThreadUrl, and TildeOntologyPath for JSON hrefs.
Server canonical_path and path_types re-export slug-types; RPC and
validation build hrefs via those types instead of string helpers.

Made-with: Cursor

diff preview

diff --git a/server/src/api/helpers.rs b/server/src/api/helpers.rs
index 9b71491e9f9efc44a2a4beba09be8f64bd2ff2ee..03b3e77911ccd662bec8635345dafe2593cf242e 100644
--- a/server/src/api/helpers.rs
+++ b/server/src/api/helpers.rs
@@ -4,12 +4,12 @@ use axum::{
     Json,
 };
 use sha2::{Digest, Sha256};
+use slug_types::paths::{CanonicalItemUrl, GardenItemUrl};
 use slug_types::*;
 use std::collections::HashMap;
 
 use crate::{
     canonical_path::canonicalize_item,
-    path_types::CanonicalItemUrl,
     ranking::connected_components_from_voted_pairs,
 };
 
@@ -30,64 +30,6 @@ pub fn now_ms() -> i64 {
     t.as_millis() as i64
 }
 
-/// Serialize a canonical item for JSON: absolute URLs stay as-is; bare paths get a `/` prefix.
-pub fn item_path_for_api(item: &str) -> String {
-    if item.starts_with("http://") || item.starts_with("https://") {
-        item.to_string()
-    } else {
-        format!("/{}", item)
-    }
-}
-
-/// Same as [`item_path_for_api`], but for private rooms ontology items are prefixed with
-/// `/r/{short}/{slug}` so the URL matches the web app (`/r/…/~/…` routes).
-pub fn item_path_for_api_in_room(item: &str, room_wire: &str) -> String {
-    let room = room_wire.trim();
-    if room.is_empty() || room == "public" {
-        return item_path_for_api(item);
-    }
-    let Some((short, slug)) = room.split_once('/') else {
-        return item_path_for_api(item);
-    };
-    if short.is_empty() || slug.is_empty() {
-        return item_path_for_api(item);
-    }
-    let Some(c) = CanonicalItemUrl::parse(item) else {
-        return item_path_for_api(item);
-    };
-    let root = CanonicalItemUrl::ontology_root();
-    let item_norm = c.as_str().trim_end_matches('/');
-    let root_norm = root.as_str().trim_end_matches('/');
-    if let Some(tail) = c.tilde_tail() {
-        return if tail.is_empty() {
-            format!("https://slug.social/r/{short}/{slug}/~")
-        } else {
-            format!("https://slug.social/r/{short}/{slug}/~/{}", tail)
-        };
-    }
-    if item_norm == root_norm {
-        return format!("https://slug.social/r/{short}/{slug}/~");
-    }
-    item_path_for_api(item)
-}
-
-/// Absolute thread URL for forum JSON (`/t/…` vs `/r/…/t/…`).
-pub fn forum_thread_web_url(room_wire: &str, thread_tag: &str) -> String {
-    let room = room_wire.trim();
-    let tag = thread_tag.trim().trim_start_matches('#');
-    if room.is_empty() || room == "public" {
-        format!("https://slug.social/t/{tag}")
-    } else if let Some((short, slug)) = room.split_once('/') {
-        if short.is_empty() || slug.is_empty() {
-            format!("https://slug.social/t/{tag}")
-        } else {
-            format!("https://slug.social/r/{short}/{slug}/t/{tag}")
-        }
-    } else {
-        format!("https://slug.social/t/{tag}")
-    }
-}
-
 /// Resolve an item path as a first-class canonical path.
 pub fn resolve_item(item: &str) -> Result<String, String> {
     let canonical = canonicalize_item(item);
@@ -109,14 +51,12 @@ pub fn parse_parent_specs(parent: Option<&String>) -> Vec<String> {
 }
 
 /// Apply offset+limit pagination to the flattened component rankings.
-/// Items are flattened in component order (largest component first), then unranked last.
-/// Returns (components, unranked_items) after the window.
 pub fn paginate_rankings(
     components: Vec<RankComponent>,
-    unranked_items: Vec<String>,
+    unranked_items: Vec<GardenItemUrl>,
     offset: usize,
     limit: Option<usize>,
-) -> (Vec<RankComponent>, Vec<String>) {
+) -> (Vec<RankComponent>, Vec<GardenItemUrl>) {
     let mut remaining_skip = offset;
     let mut remaining_take = limit.unwrap_or(usize::MAX);
     let mut out_components: Vec<RankComponent> = Vec::new();
@@ -141,7 +81,7 @@ pub fn paginate_rankings(
         });
     }
 
-    let out_unranked: Vec<String> = if remaining_take > 0 {
+    let out_unranked: Vec<GardenItemUrl> = if remaining_take > 0 {
         unranked_items
             .into_iter()
             .skip(remaining_skip)
@@ -183,11 +123,9 @@ pub fn is_pair_voted(group: &crate::reducer::GroupState, a: &str, b: &str) -> bo
     group.voted_pairs.contains(&(i, j))
 }
 
-/// Compute graph connectivity stats for a set of items within the ranking group.
 pub fn compute_connectivity_stats(group: &crate::reducer::GroupState, pool: &[String]) -> ConnectivityStats {
     let n = pool.len();
 
-    // Map pool items to global indices (items not yet in the group get no index)
     let global_idxs: Vec<Option<usize>> = pool
         .iter()
         .map(|it| {
@@ -197,7 +135,6 @@ pub fn compute_connectivity_stats(group: &crate::reducer::GroupState, pool: &[St
         .collect();
     let present: Vec<usize> = global_idxs.iter().filter_map(|x| *x).collect();
 
-    // Build local index mapping for items that exist in the ranking group
     let global_to_local: HashMap<usize, usize> = present
         .iter()
         .enumerate()
@@ -213,7 +150,6 @@ pub fn compute_connectivity_stats(group: &crate::reducer::GroupState, pool: &[St
         }),
     );
 
-    // Items not in the ranking group at all are also isolates
     let items_not_in_group = global_idxs.iter().filter(|x| x.is_none()).count();
 
     let num_components = comps.len() + isolates.len() + items_not_in_group;
@@ -237,52 +173,3 @@ pub fn vote_touches_path(a: &str, b: &str, parent_canon: &str) -> bool {
     let under = |item: &str| item == parent_canon || item.starts_with(&format!("{}/", parent_canon));
     under(a) || under(b)
 }
-
-#[cfg(test)]
-mod wire_url_tests {
-    use super::{forum_thread_web_url, item_path_for_api_in_room};
-
-    #[test]
-    fn public_room_unchanged() {
-        let u = "https://slug.social/~/a/b";
-        assert_eq!(item_path_for_api_in_room(u, "public"), u);
-    }
-
-    #[test]
-    fn private_room_prefixes_ontology() {
-        assert_eq!(
-            item_path_for_api_in_room("https://slug.social/~/topic/x", "9ab12cd/my-room"),
-            "https://slug.social/r/9ab12cd/my-room/~/topic/x"
-        );
-    }
-
-    #[test]
-    fn private_room_ontology_root() {
-        assert_eq!(
-            item_path_for_api_in_room("https://slug.social/~", "9ab12cd/my-room"),
-            "https://slug.social/r/9ab12cd/my-room/~"
-        );
-        assert_eq!(
-            item_path_for_api_in_room("https://slug.social/~/", "9ab12cd/my-room"),
-            "https://slug.social/r/9ab12cd/my-room/~"
-        );
-    }
-
-    #[test]
-    fn external_url_untouched_in_private_room() {
-        let u = "https://example.com/z";
-        assert_eq!(item_path_for_api_in_room(u, "9ab12cd/my-room"), u);
-    }
-
-    #[test]
-    fn forum_web_public_vs_room() {
-        assert_eq!(
-            forum_thread_web_url("public", "debate"),
-            "https://slug.social/t/debate"
-        );
-        assert_eq!(
-            forum_thread_web_url("9ab12cd/my-room", "#debate"),
-            "https://slug.social/r/9ab12cd/my-room/t/debate"
-        );
-    }
-}
diff --git a/server/src/api/mod.rs b/server/src/api/mod.rs
index 042aa248305f9362a3be78f9eea2a5abf6ba707a..cf22cb0129366c3aed031bc86f3197a4321cb806 100644
--- a/server/src/api/mod.rs
+++ b/server/src/api/mod.rs
@@ -24,8 +24,7 @@ pub use auth::{
 
 pub use helpers::{
     api_error, compute_connectivity_stats, is_pair_voted, now_ms, paginate_rankings,
-    parse_parent_specs, pick_random_distinct, sha256_hex, resolve_item, vote_touches_path,
-    item_path_for_api,
+    parse_parent_specs, pick_random_distinct, resolve_item, sha256_hex, vote_touches_path,
 };
 
 pub use rpc::handle_rpc_batch;
diff --git a/server/src/api/rpc.rs b/server/src/api/rpc.rs
index 5b91f5836625eedbb1cd9423168046e3fb576c17..5f7d50188f1381267402f2e57e671234ef5db2fd 100644
--- a/server/src/api/rpc.rs
+++ b/server/src/api/rpc.rs
@@ -8,6 +8,7 @@ use axum::{
     Json,
 };
 use rand::seq::SliceRandom;
+use slug_types::paths::{ForumThreadUrl, GardenItemUrl, TildeOntologyPath};
 use slug_types::*;
 
 use crate::{
@@ -27,9 +28,8 @@ use crate::{
 
 use super::auth::verify_bearer_principal;
 use super::helpers::{
-    compute_connectivity_stats, forum_thread_web_url, is_pair_voted, item_path_for_api,
-    item_path_for_api_in_room, now_ms, paginate_rankings, parse_parent_specs, pick_random_distinct,
-    resolve_item, vote_touches_path,
+    compute_connectivity_stats, is_pair_voted, now_ms, paginate_rankings, parse_parent_specs,
+    pick_random_distinct, resolve_item, vote_touches_path,
 };
 use super::validate::{normalize_room_and_thread, validate_ingest_document};
 
@@ -184,7 +184,7 @@ fn compute_scope_rank_changes(
         };
         if changed {
             changes.push(RankChange {
-                item: item_path_for_api_in_room(&item, room_wire),
+                item: GardenItemUrl::from_storage_str(&item, room_wire),
                 before: b,
                 after: a,
             });
@@ -206,7 +206,7 @@ fn compute_scope_rank_changes(
         parent: if parent.is_empty() {
             "/".to_string()
         } else {
-            item_path_for_api_in_room(parent, room_wire)
+            GardenItemUrl::from_storage_str(parent, room_wire).into_inner()
         },
         changes,
     })
@@ -302,7 +302,7 @@ fn build_rank_response_for_content(
                     .ranked
                     .into_iter()
                     .map(|r| RankRow {
-                        item: item_path_for_api_in_room(r.item.as_str(), room_wire),
+                        item: GardenItemUrl::from_stored(&r.item, room_wire),
                         percent: if want_percent {
                             Some((r.score / max_score) * 100.0)
                         } else {
@@ -315,10 +315,10 @@ fn build_rank_response_for_content(
         })
         .collect();
 
-    let prefixed_unranked: Vec<String> = rankings
+    let prefixed_unranked: Vec<GardenItemUrl> = rankings
         .unranked_items
         .into_iter()
-        .map(|s| item_path_for_api_in_room(s.as_str(), room_wire))
+        .map(|s| GardenItemUrl::from_stored(&s, room_wire))
         .collect();
 
     let (components, unranked_items) = if offset > 0 || limit.is_some() {
@@ -537,13 +537,13 @@ async fn rpc_post(
         (
             "npx slugsocial public garden pair".to_string(),
             "npx slugsocial public garden rank".to_string(),
-            forum_thread_web_url("public", &thread_id),
+            ForumThreadUrl::from_room_tag("public", &thread_id),
         )
     } else {
         (
             format!("npx slugsocial private {room_key} garden pair"),
             format!("npx slugsocial private {room_key} garden rank"),
-            forum_thread_web_url(&room_key, &thread_id),
+            ForumThreadUrl::from_room_tag(&room_key, &thread_id),
         )
     };
 
@@ -664,7 +664,7 @@ async fn rpc_check(
                         .ranked
                         .into_iter()
                         .map(|r| RankRow {
-                            item: item_path_for_api_in_room(r.item.as_str(), &room_key),
+                            item: GardenItemUrl::from_stored(&r.item, &room_key),
                             score: r.score,
                             percent: None,
                         })
@@ -672,12 +672,12 @@ async fn rpc_check(
                 })
                 .collect();
             CheckScopeRanking {
-                parent: item_path_for_api_in_room(parent.as_str(), &room_key),
+                parent: GardenItemUrl::from_stored(parent, &room_key).into_inner(),
                 components,
                 unranked_items: scoped
                     .unranked_items
                     .into_iter()
-                    .map(|it| item_path_for_api_in_room(it.as_str(), &room_key))
+                    .map(|it| GardenItemUrl::from_stored(&it, &room_key))
                     .collect(),
             }
         })
@@ -687,13 +687,13 @@ async fn rpc_check(
         vec![
             "npx slugsocial public forum post <TAG> --delegate <uuid:rig:

… preview truncated; 46,249 characters omitted

download full diff A

B — c_06fce70179bc (tommy-mor)

message

[6d04afc2] refactor

diff preview

diff --git a/Cargo.lock b/Cargo.lock
index 2cea973082716e761ef6f5dd5886acc08ff9aac0..8c43fb75c472b102e6e1d3b837dce3355be898f2 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -17,6 +17,28 @@ version = "1.0.102"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
 
+[[package]]
+name = "async-stream"
+version = "0.3.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476"
+dependencies = [
+ "async-stream-impl",
+ "futures-core",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "async-stream-impl"
+version = "0.3.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
 [[package]]
 name = "async-trait"
 version = "0.1.89"
@@ -1242,9 +1264,11 @@ dependencies = [
 name = "sorter2-server"
 version = "0.0.1"
 dependencies = [
+ "async-stream",
  "axum",
  "axum-extra",
  "dotenvy",
+ "futures-util",
  "maud",
  "reqwest",
  "serde",
diff --git a/server/Cargo.toml b/server/Cargo.toml
index bd600138b613bd0f546bdec217a5334cdcb20aa5..c940acb687fb141d21760a3d6656172013cf6f41 100644
--- a/server/Cargo.toml
+++ b/server/Cargo.toml
@@ -18,6 +18,8 @@ tracing = "0.1"
 tracing-subscriber = { version = "0.3", features = ["env-filter"] }
 reqwest = { version = "0.12", features = ["json"] }
 dotenvy = "0.15"
+async-stream = "0.3"
+futures-util = { version = "0.3", default-features = false, features = ["std"] }
 
 [dev-dependencies]
 reqwest = { version = "0.12", features = ["json"] }
diff --git a/server/src/api/ui_html.rs b/server/src/api/ui_html.rs
index b33a84e8bb5e817b26592868d88090e6d664d950..7af6527d03c483f33f3469ce6766c01a554c5fe3 100644
--- a/server/src/api/ui_html.rs
+++ b/server/src/api/ui_html.rs
@@ -6,7 +6,8 @@ use axum::{
 use std::collections::HashMap;
 
 use crate::{
-    html::{entity_section, input_panel, js_string_literal, ranking_panel, JsBuilder},
+    fetch,
+    html::{input_panel, js_string_literal, ranking_panel, JsBuilder},
     parser::parse_reddit_url,
     path_types::ItemId,
     reddit::ensure_partial_tree,
@@ -89,18 +90,8 @@ pub async fn post_ui_html(
         },
         HtmlUiAction::FetchEntity { item } => {
             let id = parse_item_param(&item);
-            if id.is_root() {
-                return ui_js_warn("nothing to fetch for the root").into_response();
-            }
-            state.queue_entity_fetch(id.clone());
-            let tree = state.tree.read().await;
-            let empty = crate::reducer::NodeState::default();
-            let node = tree.get(&id).unwrap_or(&empty);
-            let panel = entity_section(&id, node, true);
-            JsBuilder::new()
-                .morph_selector("#entity-section", panel)
-                .into_response()
-        },
+            fetch::fetch_entity_stream(state, id).into_response()
+        }
     }
 }
 
diff --git a/server/src/fetch/html.rs b/server/src/fetch/html.rs
new file mode 100644
index 0000000000000000000000000000000000000000..63634508496e224c38b9ec0308b7a6086462f925
--- /dev/null
+++ b/server/src/fetch/html.rs
@@ -0,0 +1,67 @@
+//! Markup for entity import / “Fetch from Reddit” (`POST /ui`, SSE response).
+
+use maud::{html, Markup};
+
+use crate::{
+    form_template::template_json_compact,
+    path_types::ItemId,
+    reddit::is_fetchable,
+    reducer::NodeState,
+    ui_action::UI_RPC_FIELD,
+};
+
+fn entity_panel(node: &NodeState) -> Markup {
+    html! {
+        @if let Some(data) = &node.data {
+            div id="entity-panel" class="entity-card" {
+                h2 { (data.title) }
+                @if let Some(author) = &data.author {
+                    p class="muted small" { "by " (author) }
+                }
+                @if let Some(body) = &data.body_html {
+                    div class="entity-body" { (maud::PreEscaped(body)) }
+                }
+            }
+        }
+    }
+}
+
+/// Reddit/API import — `POST /ui` with `fetch_entity` returns an SSE stream.
+pub fn fetch_entity_panel(item: &ItemId, has_data: bool, fetching: bool) -> Markup {
+    if !is_fetchable(item) {
+        return html! {};
+    }
+    let label = if fetching {
+        "Fetching…"
+    } else if has_data {
+        "Fetch more"
+    } else {
+        "Fetch from Reddit"
+    };
+    let rpc = template_json_compact(&serde_json::json!({
+        "action": "fetch_entity",
+        "item": item.as_str(),
+    }))
+    .expect("fetch_entity rpc template");
+    html! {
+        form method="post" action="/ui" id="fetch-entity-form" class="fetch-entity-form" {
+            input type="hidden" name=(UI_RPC_FIELD) value=(rpc);
+            @if fetching {
+                button type="submit" class="btn-secondary" disabled { (label) }
+            } @else {
+                button type="submit" class="btn-secondary" { (label) }
+            }
+        }
+    }
+}
+
+/// Entity card + fetch control (target `#entity-section` for Idiomorph / SSE).
+pub fn entity_section(item: &ItemId, node: &NodeState, fetching: bool) -> Markup {
+    let has_data = node.data.is_some();
+    html! {
+        section id="entity-section" class="demo-panel" {
+            (entity_panel(node))
+            (fetch_entity_panel(item, has_data, fetching))
+        }
+    }
+}
diff --git a/server/src/fetch/mod.rs b/server/src/fetch/mod.rs
new file mode 100644
index 0000000000000000000000000000000000000000..2290f9d3a0f1cbf1806c6339f82a4515c11cc3d3
--- /dev/null
+++ b/server/src/fetch/mod.rs
@@ -0,0 +1,115 @@
+//! Entity import over `POST /ui` as SSE (Reddit worker in [`crate::reddit`]).
+
+pub mod html;
+
+use std::convert::Infallible;
+use std::time::Duration;
+
+use async_stream::stream;
+use axum::response::sse::{Event, KeepAlive, Sse};
+use futures_util::Stream;
+use serde::Serialize;
+use tokio::sync::oneshot;
+
+use crate::{
+    path_types::ItemId,
+    reddit::FetchJobResult,
+    reducer::NodeState,
+    state::AppState,
+};
+
+pub fn now_ms() -> i64 {
+    let t = std::time::SystemTime::now()
+        .duration_since(std::time::UNIX_EPOCH)
+        .unwrap_or_default();
+    t.as_millis() as i64
+}
+
+#[derive(Serialize)]
+struct SseMorphPayload {
+    selector: &'static str,
+    html: String,
+}
+
+fn morph_complete_event(html: maud::Markup) -> Event {
+    let payload = SseMorphPayload {
+        selector: "#entity-section",
+        html: html.into_string(),
+    };
+    let data = serde_json::to_string(&payload).unwrap_or_else(|_| "{}".into());
+    Event::default().event("complete").data(data)
+}
+
+/// Stream `fetching` → `complete` / `error` for [`crate::ui_action::HtmlUiAction::FetchEntity`].
+pub fn fetch_entity_stream(
+    state: AppState,
+    id: ItemId,
+) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
+    tracing::debug!(item = %id, "fetch entity stream opened");
+
+    let stream = stream! {
+        if id.is_root() {
+            yield Ok(Event::default().event("error").data("{\"message\":\"nothing to fetch for the root\"}"));
+            return;
+        }
+
+        if !crate::reddit::is_fetchable(&id) {
+            tracing::debug!(item = %id, "fetch stream: not fetchable");
+            yield Ok(Event::default().event("error").data("{\"message\":\"this page cannot be fetched from Reddit\"}"));
+            return;
+        }
+
+        let fetching_html = {
+            let tree = state.tree.read().await;
+            let empty = NodeState::default();
+            let node = tree.get(&id).unwrap_or(&empty);
+            html::entity_section(&id, node, true).into_string()
+        };
+        let fetching_payload = serde_json::json!({
+            "selector": "#entity-section",
+            "html": fetching_html,
+        });
+        yield Ok(Event::default().event("fetching").data(fetching_payload.to_string()));
+
+        let (tx, rx) = oneshot::channel();
+        state.reddit.request_fetch(id.clone(), true, Some(tx));
+        tracing::debug!(item = %id, "fetch stream: queued reddit job");
+
+        let result = match rx.await {
+            Ok(r) => r,
+            Err(_) => {
+                tracing::warn!(item = %id, "fetch stream: worker dropped oneshot");
+                FetchJobResult::Failed("reddit worker stopped".into())
+            }
+        };
+
+        tracing::debug!(item = %id, ?result, "fetch stream: job finished");
+
+        match result {
+            FetchJobResult::Imported | FetchJobResult::NotFound => {
+                let tree = state.tree.read().await;
+                let empty = NodeState::default();
+                let node = tree.get(&id).unwrap_or(&empty);
+                yield Ok(morph_complete_event(html::entity_section(&id, node, false)));
+            }
+            FetchJobResult::SkippedCached | FetchJobResult::SkippedDuplicate => {
+                let tree = state.tree.read().await;
+                let empty = NodeState::default();
+                let node = tree.get(&id).unwrap_or(&empty);
+                yield Ok(morph_complete_event(html::entity_section(&id, node, false)));
+            }
+            FetchJobResult::RateLimited { reset_secs } => {
+                yield Ok(Event::default().event("error").data(
+                    serde_json::json!({"message": format!("Reddit rate limit — retry in {reset_secs}s")}).to_string(),
+                ));
+            }
+            FetchJobResult::Failed(msg) => {
+                yield Ok(Event::default().event("error").data(
+                    serde_json::json!({"message": msg}).to_string(),
+                ));
+            }
+        }
+    };
+
+    Sse::new(stream).keep_alive(KeepAlive::new().interval(Duration::from_secs(15)))
+}
diff --git a/server/src/html/mod.rs b/server/src/html/mod.rs
index db5b4c7f06b0be64603981166835cde268234f67..9314a7556306ddab969b896dbf4126b542a46722 100644
--- a/server/src/html/mod.rs
+++ b/server/src/html/mod.rs
@@ -7,10 +7,10 @@ use axum::{
 use maud::{html, Markup, DOCTYPE};
 
 use crate::{
+    fetch::html::entity_section,
     form_template::template_json_compact,
     path_types::ItemId,
     ranking::{top_bottom, RankedItem},
-    reddit::is_fetchable,
     reducer::{GroupState, NodeState},
     state::AppState,
     ui_action::UI_RPC_FIELD,
@@ -149,62 +149,6 @@ pub fn breadcrumb_path(item: &ItemId) -> Markup {
     }
 }
 
-fn entity_panel(node: &NodeState) -> Markup {
-    html! {
-        @if let Some(data) = &node.data {
-            div id="entity-panel" class="entity-card" {
-                h2 { (data.title) }
-                @if let Some(author) = &data.author {
-                    p class="muted small" { "by " (author) }
-                }
-                @if let Some(body) = &data.body_html {
-                    div class="entity-body" { (maud::PreEscaped(body)) }
-                }
-            }
-        }
-    }
-}
-
-/// Reddit/API import control — only shown on fetchable pages; never auto-fires.
-pub fn fetch_entity_panel(item: &ItemId, has_data: bool, fetching: bool) -> Markup {
-    if !is_fetchable(item) {
-        return html! {};
-    }
-    let label = if fetching {
-        "Fetching…"
-    } else if has_data {
-        "Fetch more"
-    } else {
-        "Fetch from Reddit"
-    };
-    let rpc = template_json_compact(&serde_json::json!({
-        "action": "fetch_entity",
-        "item": item.as_str(),
-    }))
-    .expect("fetch_entity rpc template");
-    html! {
-        form method="post" action="/ui" id="fetch-entity-form" class="fetch-entity-form" {
-            input type="hidden" name=(UI_RPC_FIELD) value=(rpc);
-            @if fetching {
-                button type="submit" class="btn-secondary" disabled { (label) }
-            } @else {
-                button type="submit" class="btn-secondary" { (label) }
-            }
-        }
-    }
-}
-
-/// Entity 

… preview truncated; 22,618 characters omitted

download full diff B

Hardlinks — judgments / attempts / prompt

prompt download

judgments

attempts

Prompt text is loaded only by the download route.