Side A fixes a real security bug (fail-open voting fallback to anon) with a fail-closed rewrite, adds Secure cookie support, gates mock OAuth behind an env flag, hardens open-redirect sanitization, and adds unit tests plus nav UI improvements—concrete, security-relevant lasting value. Side B is a larger refactor (new pair.rs module, vote.rs rewrite, ItemId::from_storage normalization) that is useful but is mostly internal restructuring/feature polish without addressing a correctness or security defect, and is labeled just 'refactor' with less durable architectural necessity than A's fixes.
constitution · epochs · watch · epoch 3
c_94135a1c4c58 (tommy-mor) vs c_af08bd851e49 (tommy-mor)
download prompt · raw event · cmp_7a749e9994b461
council reasoning
B adds the core /vote compare surface, bridge-aware pair selection in pair.rs, ItemId::from_storage canonicalization, and in-place morph after votes—foundational product/ranking design with tests. A is real lasting security (fail-closed resolve_vote_actor, mock-OAuth gate, Secure cookies, open-redirect hardening) plus nav alias polish, but it hardens an existing path rather than delivering the main voting/ranking capability.
Side A introduces substantive security and correctness improvements: voting now fails closed instead of silently falling back to an anonymous actor, OAuth mocking is gated behind an explicit environment flag, Secure cookie handling is centralized, open-redirect sanitization is strengthened, and these behaviors are covered with new tests. Side B adds useful functionality around a pairwise voting UI, pair selection logic, and ID normalization, but much of the patch is feature work and refactoring rather than the broad, lasting hardening of core authentication and session handling delivered by Side A.
sides
A — c_94135a1c4c58 (tommy-mor)
message
[880eb778] Harden auth: fail-closed votes, mock OAuth gate, Secure cookies. Also show the current alias in the top nav and pin durable by rev. Co-authored-by: Cursor <cursoragent@cursor.com>
diff preview
diff --git a/AGENTS.md b/AGENTS.md
index babb889d6fbfb1fa7176c9e6b7544ae17b61dd2e..6e0fd8ebb65d665c9c1438e3275971d62b98fd95 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -10,11 +10,11 @@ Single Rust web app **`sorter2-server`**: pairwise voting, rank-centrality ranki
- **Bootstrap script**: `./scripts/cursor-env-install.sh` (also run via `.cursor/environment.json` on Cloud Agent boot) installs Playwright Chromium, Babashka, bbin, `clj-paren-repair`, and warms the RocksDB build.
- **Rust 1.88+** is required (`rust-toolchain.toml`). The Cloud Dockerfile and `cursor-env-install.sh` install **rustup** 1.88.0 first so `cargo` works while Playwright/Clojure bootstrap continues. Do not rely on `/usr/local/cargo` (often missing or stale).
-- **RocksDB / `durable`**: Ubuntu’s default `c++` is often **clang** without libc++ headers. Set **`CXX=g++`** and **`RUSTFLAGS="-C linker=g++"`** (or `CC=gcc`) before `cargo build` / `cargo test` — both are set in the bootstrap script and `.cursor/environment.json`.
+- **RocksDB / `durable`**: `durable` is an external git dependency (`tommy-mor/durable`, pinned by rev in `server/Cargo.toml`). Ubuntu’s default `c++` is often **clang** without libc++ headers. Set **`CXX=g++`** and **`RUSTFLAGS="-C linker=g++"`** (or `CC=gcc`) before `cargo build` / `cargo test` — both are set in the bootstrap script and `.cursor/environment.json`.
- **System packages** for builds: `build-essential`, `g++`, `clang`, `libclang-dev`, `pkg-config`, `libssl-dev`, `openjdk-21-jre-headless` (for `reqwest` / OpenSSL, `librocksdb-sys`, `zstd-sys` / bindgen, and **bbin** / Clojure JVM). The bootstrap sets **`JAVA_HOME`** when Java is present.
- **Clojure CLI 1.12.0.1530** (used in CI): install from https://clojure.org/guides/install_clojure — needed for `./scripts/clj-test.sh` / Kaocha tests.
- **Babashka / bbin / clj-paren-repair**: installed by `cursor-env-install.sh` into `~/.local/bin` (bb tasks in `bb.edn`, delimiter repair for Clojure edits).
-- **Playwright** (Spel browser tests in `test/vote_compare.clj`): Chromium via `clojure -M -e "(com.microsoft.playwright.CLI/main ...)"` — run once after clone or use the bootstrap script.
+- **Playwright** (Spel browser tests in `test/vote_compare.clj` / `test/auth_login.clj`): Chromium via `clojure -M -e "(com.microsoft.playwright.CLI/main ...)"` — run once after clone or use the bootstrap script.
### Commands (see also `TEST.sh`)
@@ -34,13 +34,17 @@ Environment variables (defaults in `server/src/state.rs`):
- `PORT` — default `8080`
- `SORTER2_DATA_DIR` — default `./data` (created on startup)
- `SORTER2_EVENT_LOG` — default `{data_dir}/events.jsonl`
+- `SORTER2_BASE_URL` — public origin (also drives Secure cookies when `https://`)
+- `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET` — GitHub OAuth (optional; login disabled if unset)
+- `SORTER2_ALLOW_MOCK_OAUTH=1` — allow `mock_user` on `/auth/github` (tests only)
Health check: `GET /healthz` → `ok`.
-Core UI flow: `POST /ui` with form field `__rpc__` (JSON). Example vote:
+Core UI flow: `POST /ui` with form field `__rpc__` (JSON). Votes require a session cookie (sign in via `/login`). Example vote:
```bash
curl -sf -X POST http://127.0.0.1:8080/ui \
+ --cookie "sorter2_session=..." \
--data-urlencode '__rpc__={"action":"record_vote","a":"alpha","b":"beta","ratio_left":2,"ratio_right":1}'
```
diff --git a/Cargo.lock b/Cargo.lock
index aa02997ad85777195f135bfd9456bcee0fc9a590..1f8690f3e486d099577a32c2ece48caf57ea7160 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -414,7 +414,7 @@ dependencies = [
[[package]]
name = "durable"
version = "0.2.0"
-source = "git+https://github.com/tommy-mor/durable.git?branch=main#a6c14eaa809693140eea0c22b07ef24d8e74adaf"
+source = "git+https://github.com/tommy-mor/durable.git?rev=a6c14eaa809693140eea0c22b07ef24d8e74adaf#a6c14eaa809693140eea0c22b07ef24d8e74adaf"
dependencies = [
"ciborium",
"durable-derive",
@@ -426,7 +426,7 @@ dependencies = [
[[package]]
name = "durable-derive"
version = "0.2.0"
-source = "git+https://github.com/tommy-mor/durable.git?branch=main#a6c14eaa809693140eea0c22b07ef24d8e74adaf"
+source = "git+https://github.com/tommy-mor/durable.git?rev=a6c14eaa809693140eea0c22b07ef24d8e74adaf#a6c14eaa809693140eea0c22b07ef24d8e74adaf"
dependencies = [
"proc-macro2",
"quote",
diff --git a/server/Cargo.toml b/server/Cargo.toml
index dfa39beddecfa37dcdeaa602cb30f4b547528fbb..bd88687fb0ba47d68f2c08eb5e11d0e08b7c4398 100644
--- a/server/Cargo.toml
+++ b/server/Cargo.toml
@@ -25,7 +25,7 @@ futures-util = { version = "0.3", default-features = false, features = ["std"] }
rand = "0.8"
urlencoding = "2"
url = "2"
-durable = { git = "https://github.com/tommy-mor/durable.git", branch = "main" }
+durable = { git = "https://github.com/tommy-mor/durable.git", rev = "a6c14eaa809693140eea0c22b07ef24d8e74adaf" }
[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 b86581b1f337650564274254d840e8a75b49524d..9da62ffbed07eb28729aa3160bf33b07ce0d7945 100644
--- a/server/src/api/ui_html.rs
+++ b/server/src/api/ui_html.rs
@@ -71,10 +71,16 @@ pub async fn post_ui_html(
return resp;
}
let parent = parent_from_scope(&scope);
- let actor = resolve_vote_actor(
+ let actor = match resolve_vote_actor(
state.projection_store.db(),
session_id_from_jar(&jar).as_deref(),
- );
+ ) {
+ Ok(actor) => actor,
+ Err(_) => {
+ return vote_auth_redirect(&state, &jar)
+ .unwrap_or_else(|| login_redirect_js().into_response());
+ }
+ };
if let Err(e) = state
.record_vote(&parent, &a, &b, ratio_left, ratio_right, &actor)
.await
diff --git a/server/src/auth/config.rs b/server/src/auth/config.rs
index a1f042c655bf3e5234eeb87a7d889f64592807fb..a5976af9a52ea207b35ae87bd1fe927c47a477ca 100644
--- a/server/src/auth/config.rs
+++ b/server/src/auth/config.rs
@@ -1,9 +1,42 @@
pub const AUTH_RETURN_COOKIE: &str = "sorter2_auth_return";
+/// Allow `mock_user` on `/auth/github` (test harness only).
+pub fn mock_oauth_allowed() -> bool {
+ matches!(
+ std::env::var("SORTER2_ALLOW_MOCK_OAUTH").as_deref(),
+ Ok("1") | Ok("true") | Ok("TRUE")
+ )
+}
+
+/// Set the Secure flag on auth cookies when serving over HTTPS.
+pub fn cookies_secure() -> bool {
+ std::env::var("SORTER2_BASE_URL")
+ .map(|u| u.starts_with("https://"))
+ .unwrap_or(false)
+}
+
pub fn sanitize_return_to(raw: &str) -> String {
let s = raw.trim();
- if s.is_empty() || !s.starts_with('/') || s.starts_with("//") {
+ if s.is_empty() || !s.starts_with('/') || s.starts_with("//") || s.starts_with("/\\") {
+ return "/".to_string();
+ }
+ // Reject scheme-relative and protocol-smuggling forms.
+ if s.contains("://") || s.contains('\\') {
return "/".to_string();
}
s.to_string()
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn sanitize_return_to_blocks_open_redirects() {
+ assert_eq!(sanitize_return_to(""), "/");
+ assert_eq!(sanitize_return_to("//evil.com"), "/");
+ assert_eq!(sanitize_return_to("/\\evil.com"), "/");
+ assert_eq!(sanitize_return_to("https://evil.com"), "/");
+ assert_eq!(sanitize_return_to("/vote?parent=x"), "/vote?parent=x");
+ }
+}
diff --git a/server/src/auth/mod.rs b/server/src/auth/mod.rs
index 5ed535ba199fa736f0048c32623b14c3b1e5de2d..d4a85ef52c15dc35148e4c743f0d646cbbdb056d 100644
--- a/server/src/auth/mod.rs
+++ b/server/src/auth/mod.rs
@@ -26,7 +26,7 @@ use crate::{
ui_action::UI_RPC_FIELD,
};
-pub use session::{resolve_vote_actor, session_id_from_jar, VoteActor};
+pub use session::{nav_pseudonym, resolve_vote_actor, session_id_from_jar, VoteActor};
pub fn base_url_from_env(port: u16) -> String {
std::env::var("SORTER2_BASE_URL")
@@ -168,6 +168,10 @@ pub async fn login_page(
"login · sorter2",
login_body(session.as_ref(), &aliases, &providers),
state.views.get_views("/login"),
+ session
+ .as_ref()
+ .filter(|s| !s.pseudonym.trim().is_empty())
+ .map(|s| s.pseudonym.as_str()),
);
(jar, Html(markup.into_string())).into_response()
}
@@ -222,6 +226,7 @@ pub async fn alias_page(
"choose alias · sorter2",
body,
state.views.get_views("/login/alias"),
+ None,
)
.into_string(),
)
@@ -237,7 +242,12 @@ pub async fn github_start(
.ok_or(StatusCode::SERVICE_UNAVAILABLE)?;
let return_to = return_from_query_or_jar(&jar, query.return_to.as_deref());
let state_token = session::new_oauth_state();
- let url = oauth::authorize_url(&cfg, &state_token, query.mock_user.as_deref());
+ let mock_user = if config::mock_oauth_allowed() {
+ query.mock_user.as_deref()
+ } else {
+ None
+ };
+ let url = oauth::authorize_url(&cfg, &state_token, mock_user);
let jar = jar
.add(session::oauth_state_cookie_value(&state_token))
.add(session::auth_return_cookie_value(&return_to));
diff --git a/server/src/auth/session.rs b/server/src/auth/session.rs
index 09659240b9455c6fca12db5652e1d31cf8c2acfc..41df030ded3abcafc0ab3887ab769adf103f9aa0 100644
--- a/server/src/auth/session.rs
+++ b/server/src/auth/session.rs
@@ -5,7 +5,7 @@ use durable::{Db, Durability};
use rand::Rng;
use crate::{
- auth::config::AUTH_RETURN_COOKIE,
+ auth::config::{self, AUTH_RETURN_COOKIE},
fetch::now_ms,
identity::{DEFAULT_ACTOR_UUID, DEFAULT_PSEUDONYM},
storage_dto::{SessionDataV1, SESSION_DATA_VERSION},
@@ -37,6 +37,7 @@ pub struct VoteActor {
}
impl VoteActor {
+ /// Test / bench helper: seed votes as the default pseudonym without a session.
pub fn anon() -> Self {
Self {
pseudonym: DEFAULT_PSEUDONYM.to_string(),
@@ -70,20 +71,51 @@ fn hex_encode(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
-pub fn resolve_vote_actor(db: &Db, session_id: Option<&str>) -> VoteActor {
- let Some(session_id) = session_id else {
- return VoteActor::anon();
- };
- let Ok(Some(session)) = load_session(db, session_id) else {
- return VoteActor::anon();
- };
- if session.expires_at <= now_ms() {
- return VoteActor::anon();
+fn build_cookie(name: &'static str, value: String) -> Cookie<'static> {
+ let mut builder = Cookie::build((name, value))
+ .http_only(true)
+ .same_site(SameSite::Lax)
+ .path("/");
+ if config::cookies_secure() {
+ builder = builder.secure(true);
+ }
+ builder.build()
+}
+
+fn clear_cookie(name: &'static str) -> Cookie<'static> {
+ let mut builder = Cookie::build((name, ""))
+ .http_only(true)
+ .same_site(SameSite::Lax)
+ .path("/")
+ .removal();
+ if config::cookies_secure() {
+ builder = builder.secure(true);
+ }
+ builder.build()
+}
+
+/// Resolve the vote actor from a live session. Fail-closed: never falls back to anon.
+pub fn resolve_vote_actor(db: &Db, session_id: Option<&str>) -> Result<VoteActor, &'static str> {
+ let session_id = session_id.ok_or("sign in to vote")?;
+ let session = load_valid_session(db, session_id).ok_or("session expired")?;
+ if !session_has_pseudonym(&session) {
+ return Err("choose an alias first");
}
let trust_weight = user_trust_weight(db, &session.uuid).unwrap_or(1.0);
- VoteActor {
+ Ok(VoteActor {
pseudonym: session.current_pseudonym,
trust_weight,
+ })
+}
+
+/// Display name for the top nav, if any session is active.
+pub fn nav_pseudonym(db: &Db, jar: &CookieJar) -> Option<String> {
+ let sessio
… preview truncated; 10,040 characters omittedB — c_af08bd851e49 (tommy-mor)
message
[2bc302c3] refactor
diff preview
diff --git a/server/src/api/ui_html.rs b/server/src/api/ui_html.rs
index 06001212820101e0cc953d3687dea64f85e60787..d2f9769108def7ca2c5857aec8b4319426188a66 100644
--- a/server/src/api/ui_html.rs
+++ b/server/src/api/ui_html.rs
@@ -47,7 +47,7 @@ pub async fn post_ui_html(
ratio_left,
ratio_right,
scope,
- next,
+ vote_compare,
} => {
let parent = parent_from_scope(&scope);
if let Err(e) = state
@@ -57,14 +57,12 @@ pub async fn post_ui_html(
return ui_js_warn(&e).into_response();
}
let tree = state.tree.read().await;
- if !next.trim().is_empty() {
+ if vote_compare {
+ let left = parse_item_param(&a);
+ let right = parse_item_param(&b);
+ let morph = crate::html::vote::vote_recorded_morph(&tree, &parent, &left, &right);
drop(tree);
- return JsBuilder::new()
- .raw(&format!(
- "window.location.href={};",
- js_string_literal(next.trim())
- ))
- .into_response();
+ return morph.into_response();
}
let empty = crate::reducer::NodeState::default();
let node = tree.get(&parent).unwrap_or(&empty);
@@ -137,7 +135,7 @@ mod tests {
ratio_left: 3,
ratio_right: 1,
scope: String::new(),
- next: String::new(),
+ vote_compare: false,
}
);
}
diff --git a/server/src/html/mod.rs b/server/src/html/mod.rs
index 61cdbc094819ddedb755572c59456ec0d6617619..cd578a5fea46a9a1d49e238d08a80c2caf18708d 100644
--- a/server/src/html/mod.rs
+++ b/server/src/html/mod.rs
@@ -65,6 +65,15 @@ impl JsBuilder {
self
}
+ pub(crate) fn morph_inner_selector(mut self, selector: &str, markup: Markup) -> Self {
+ let html = js_string_literal(&markup.into_string());
+ self.snippets.push(format!(
+ "var __el = document.querySelector({sel}); if (__el) {{ Idiomorph.morph(__el, {html}, {{ morphStyle: 'innerHTML' }}); }}",
+ sel = js_string_literal(selector),
+ ));
+ self
+ }
+
pub(crate) fn raw(mut self, js: &str) -> Self {
if !js.is_empty() {
self.snippets.push(js.to_string());
diff --git a/server/src/html/vote.rs b/server/src/html/vote.rs
new file mode 100644
index 0000000000000000000000000000000000000000..89ed621ad861214e147add2062224fc4137ff8ad
--- /dev/null
+++ b/server/src/html/vote.rs
@@ -0,0 +1,306 @@
+//! Pairwise vote UI — `/vote?parent=` with optional `left` / `right`.
+
+use axum::{
+ extract::{Query, State},
+ response::{Html, IntoResponse},
+};
+use maud::{html, Markup};
+use serde::Deserialize;
+
+use crate::{
+ form_template::template_json_compact,
+ html::JsBuilder,
+ pair::{children_of, resolve_pair, suggest_next_pair_in_pool},
+ path_types::ItemId,
+ reducer::{GlobalTree, GroupState, NodeState, VoteData},
+ state::{parse_item_param, AppState},
+ ui_action::UI_RPC_FIELD,
+};
+
+use super::{breadcrumb_path, item_href, layout};
+
+#[derive(Debug, Deserialize)]
+pub struct VoteQuery {
+ pub parent: String,
+ #[serde(default)]
+ pub left: Option<String>,
+ #[serde(default)]
+ pub right: Option<String>,
+}
+
+pub fn vote_href(parent: &ItemId) -> String {
+ format!(
+ "/vote?parent={}",
+ urlencoding::encode(parent.as_str())
+ )
+}
+
+fn vote_compare_href(parent: &ItemId, left: &ItemId, right: &ItemId) -> String {
+ format!(
+ "/vote?parent={}&left={}&right={}",
+ urlencoding::encode(parent.as_str()),
+ urlencoding::encode(left.as_str()),
+ urlencoding::encode(right.as_str()),
+ )
+}
+
+fn display_label(id: &ItemId) -> String {
+ id.segments()
+ .last()
+ .map_or("item".into(), |v| v.to_string())
+}
+
+fn child_title(tree: &GlobalTree, id: &ItemId) -> String {
+ tree.get(id)
+ .and_then(|n| n.data.as_ref())
+ .map(|d| d.title.clone())
+ .unwrap_or_else(|| display_label(id))
+}
+
+fn ratio_pct(ratio_left: i32, ratio_right: i32) -> f64 {
+ let l = ratio_left.max(0) as f64;
+ let r = ratio_right.max(0) as f64;
+ let sum = l + r;
+ if sum <= 0.0 {
+ 50.0
+ } else {
+ (l / sum) * 100.0
+ }
+}
+
+fn ratios_for_page(v: &VoteData, page_left: &ItemId, page_right: &ItemId) -> (i32, i32) {
+ match (v.a.as_str(), v.b.as_str()) {
+ (a, b) if a == page_left.as_str() && b == page_right.as_str() => {
+ (v.ratio_left, v.ratio_right)
+ }
+ (a, b) if a == page_right.as_str() && b == page_left.as_str() => {
+ (v.ratio_right, v.ratio_left)
+ }
+ _ => (v.ratio_left, v.ratio_right),
+ }
+}
+
+fn edge_votes(group: &GroupState, left: &ItemId, right: &ItemId) -> Vec<VoteData> {
+ group
+ .recent_votes
+ .iter()
+ .filter(|v| {
+ (v.a.as_str() == left.as_str() && v.b.as_str() == right.as_str())
+ || (v.a.as_str() == right.as_str() && v.b.as_str() == left.as_str())
+ })
+ .cloned()
+ .collect()
+}
+
+fn vote_edge_history(tree: &GlobalTree, group: &GroupState, left: &ItemId, right: &ItemId) -> Markup {
+ let mut votes = edge_votes(group, left, right);
+ votes.sort_by(|a, b| b.ts.cmp(&a.ts));
+ let legend_left = child_title(tree, left);
+ let legend_right = child_title(tree, right);
+ html! {
+ @if votes.is_empty() {
+ p class="muted vote-edge-empty" { "no votes on this pair yet" }
+ } @else {
+ h3 class="vote-edge-history-title" {
+ "votes on this pair"
+ span class="vote-edge-history-axis muted" { " · " (legend_left) " : " (legend_right) }
+ }
+ ul class="vote-edge-history" {
+ @for v in &votes {
+ @let (r_left, r_right) = ratios_for_page(v, left, right);
+ @let pct = ratio_pct(r_left, r_right);
+ li class="vote-edge-history-row" {
+ div class="vote-edge-meta" {
+ span class="vote-edge-ratio" { (format!("{}:{}", r_left, r_right)) }
+ }
+ div class="ratio-bar vote-edge-bar" aria-hidden="true" {
+ div class="ratio-left" style={(format!("width: {:.3}%;", pct))} {}
+ div class="ratio-right" style={(format!("width: {:.3}%;", 100.0 - pct))} {}
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+fn vote_back_nav(parent: &ItemId) -> Markup {
+ html! {
+ div class="vote-compare-nav" {
+ a class="vote-compare-back muted" href=(item_href(parent)) { "← back to " (display_label(parent)) }
+ }
+ }
+}
+
+fn vote_compare_actions(parent: &ItemId, next: Option<&(ItemId, ItemId)>) -> Markup {
+ let next_href = next.map(|(l, r)| vote_compare_href(parent, l, r));
+ html! {
+ div id="vote-compare-actions" class="vote-compare-actions" {
+ button type="submit" class="btn-primary" data-testid="vote-post" { "post vote" }
+ @if let Some(href) = &next_href {
+ a class="btn-secondary vote-compare-next" data-testid="vote-next-pair" href=(href) { "next pair" }
+ } @else {
+ span class="btn-secondary vote-compare-next is-disabled" { "no next pair" }
+ }
+ }
+ }
+}
+
+/// After recording a vote on the compare page: refresh edge history and next-pair link.
+pub(crate) fn vote_recorded_morph(
+ tree: &GlobalTree,
+ parent: &ItemId,
+ left: &ItemId,
+ right: &ItemId,
+) -> JsBuilder {
+ let pool = children_of(tree, parent);
+ let empty = NodeState::default();
+ let group = tree
+ .get(parent)
+ .unwrap_or(&empty)
+ .local_ranking
+ .clone();
+ let edge_history = vote_edge_history(tree, &group, left, right);
+ let next_pair = suggest_next(&group, left, right, &pool);
+ let actions = vote_compare_actions(parent, next_pair.as_ref());
+ JsBuilder::new()
+ .morph_inner_selector("#vote-edge-history-region", edge_history)
+ .morph_selector("#vote-compare-actions", actions)
+}
+
+fn vote_compare_item_card(tree: &GlobalTree, item: &ItemId, side_class: &str) -> Markup {
+ let href = item_href(item);
+ let title = child_title(tree, item);
+ html! {
+ div class=(format!("vote-compare-side {side_class}")) {
+ a class=(format!("vote-compare-item {side_class}")) href=(href) {
+ @if let Some(row) = crate::render::reddit::child_row_markup(tree, item, &href) {
+ (row)
+ } @else {
+ strong { (title) }
+ }
+ }
+ @if let Some(node) = tree.get(item) {
+ @if crate::render::reddit::is_reddit_post(item) {
+ @if let Some(data) = &node.data {
+ @if let Some(src) = data.image_url.as_ref().or(data.thumb_url.as_ref()) {
+ figure class="vote-compare-figure" {
+ img class="vote-compare-image" src=(src) alt="" loading="lazy";
+ }
+ }
+ @if let Some(author) = &data.author {
+ p class="muted small" { "by " (author) }
+ }
+ }
+ } @else if let Some(data) = &node.data {
+ @if let Some(body) = &data.body_html {
+ div class="vote-compare-item-body" {
+ (maud::PreEscaped(body))
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+
+fn suggest_next(group: &GroupState, left: &ItemId, right: &ItemId, pool: &[ItemId]) -> Option<(ItemId, ItemId)> {
+ suggest_next_pair_in_pool(group, pool, Some((left, right)))
+}
+
+pub async fn vote_page(
+ State(state): State<AppState>,
+ Query(q): Query<VoteQuery>,
+) -> impl IntoResponse {
+ let parent = parse_item_param(&q.parent);
+ let left_param = q.left.as_deref().map(parse_item_param);
+ let right_param = q.right.as_deref().map(parse_item_param);
+
+ let tree = state.tree.read().await;
+ let empty = NodeState::default();
+ let parent_node = tree.get(&parent).unwrap_or(&empty);
+
+ let (left, right) = match resolve_pair(
+ &tree,
+ &parent,
+ left_param.as_ref(),
+ right_param.as_ref(),
+ ) {
+ Ok(p) => p,
+ Err(e) => {
+ let (msg, status) = e.status_message();
+ return (status, msg).into_response();
+ }
+ };
+
+ let pool = children_of(&tree, &parent);
+ let group = &parent_node.local_ranking;
+ let next_pair = suggest_next(group, &left, &right, &pool);
+ let edge_history = vote_edge_history(&tree, group, &left, &right);
+
+ let rpc_json = template_json_compact(&serde_json::json!({
+ "action": "record_vote",
+ "a": left.as_str(),
+ "b": right.as_str(),
+ "ratio_left": {"$form:i32": "ratio_left"},
+ "ratio_right": {"$form:i32": "ratio_right"},
+ "scope": parent.as_str(),
+ "vote_compare": true,
+ }))
+ .expect("vote rpc json");
+
+ let title = format!(
+ "vote — {} vs {}",
+ child_title(&tree, &left),
+ child_title(&tree, &right)
+ );
+
+ let body = html! {
+ section class="vote-compare-shell" {
+ h1 { "compare" }
+ (breadcrumb_path(&parent))
+ p class="muted vote-compare-scope" {
+ "ranking children of "
+ a href=(item_href(&par
… preview truncated; 32,381 characters omittedHardlinks — judgments / attempts / prompt
judgments
attempts
Prompt text is loaded only by the download route.