You are a constitutional council ranking individual git commits for ownership allocation. Compare these two commits. Decide which contributed more lasting value to the project. Judge substance, not spectacle: - Prefer correct, lasting design and real bugfixes over churn, formatting, renames, or generated noise. - Prefer clarity and necessity over sheer line count. A small precise change can beat a large diffuse one. - Do not favor a side merely because its patch is longer or noisier. - Weight what the change does for the project, not the contributor's name. Return ONLY a JSON object: {"winner": "A" or "B", "ratio": "N:M", "explanation": "..."} The explanation must cite concrete differences in the patches (1-3 sentences). Side A — contributor: tommy-mor Side A — commit message: [6bda2635] Use title-first items and explanation-first votes (#135) * Require block-first sorter DSL statements Co-authored-by: tommy * Use title-first items with explanation-first votes Co-authored-by: tommy * Update garden vote test DSL fixtures Co-authored-by: tommy * Update browser vote DSL payloads Co-authored-by: tommy --------- Co-authored-by: Cursor Agent Side A — unified diff (full patch): diff --git a/cli/DSL.txt b/cli/DSL.txt index 18f69ef25f01583fddf9fc90e077bb2c3fa72bb6..c9b12bf0edaf73ad252f0a202b7fe61e311df50a 100644 --- a/cli/DSL.txt +++ b/cli/DSL.txt @@ -18,9 +18,20 @@ Blank lines are preserved to maintain paragraph structure. ~/item/a {itembody} ~/python { A high-level scripting language } -~/item/a > ~/python { Item A is better because of X. } -~/python 3:1 ~/go { Python's ecosystem is much richer than Go's. } -https://example.com/lang = ~/go { They are equally good in this context. } +{ +Item A is better because of X. +} +~/item/a > ~/python + +{ +Python's ecosystem is much richer than Go's. +} +~/python 3:1 ~/go + +{ +They are equally good in this context. +} +https://example.com/lang = ~/go ``` SYNTAX RULES @@ -35,7 +46,7 @@ Starts a thread. Tag allows alphanumeric, `-`, `_`, and `/`. Subtitle max 100 ch ~/ { description } ``` Defines an ontology item (garden layer). Paths can be nested (e.g. `~/languages/python`). -A leading `/` alone is **not** allowed in the DSL — use `~/` only. Descriptions (bodies) are wrapped in `{}`. Can be adjacent (e.g. `~/arrived{ready}`). +A leading `/` alone is **not** allowed in the DSL — use `~/` only. Descriptions (bodies) are wrapped in `{}` and follow the item path. ```sorter https://example.com/item { description } @@ -46,7 +57,10 @@ Canonicalization rules for URLs: - `~/` and `https://slug.social/~/` map to the same local item path. ```sorter - { required explanation } +{ +required explanation +} + ``` Compares two items. The explanation is REQUIRED. Comparisons: @@ -65,7 +79,8 @@ When writing bodies or explanations, you can use braces `{}` and code blocks wit 3. Single braces: { ... } ```sorter -~/code { Here is a block: ```def foo(): return {"a": 1}``` } +{ Here is a block: ```def foo(): return {"a": 1}``` } +~/code ``` STYLE diff --git a/cli/GUIDE.sorter b/cli/GUIDE.sorter index 7ea1c2649cb4a323b46f0bf389025079a9c9ab43..86accba72ecea547215d947fb6552e0ead25687c 100644 --- a/cli/GUIDE.sorter +++ b/cli/GUIDE.sorter @@ -83,7 +83,8 @@ Item definitions (attaches a description to an item): ~/thread/item { description } Comparisons: - ~/thread/item-a 3:1 ~/thread/item-b { reasoning } + { reasoning } + ~/thread/item-a 3:1 ~/thread/item-b Ratio formats: 3:1 left is 3x better than right @@ -95,8 +96,7 @@ Shorthand: < means 1:2 (right is better) = means 1:1 (equal) -Bodies can attach without whitespace: - ~/thread/item{Description here} +Item bodies follow the item path. Vote explanations come first; the comparison is the verdict line. } You can write any prose in your posts. These won't be part of the garden but only the thread. @@ -165,7 +165,8 @@ npx slugsocial public forum post languages --delegate '7a3b9c2d-1234-5678-90ab-c ~/languages/python { A high-level language focused on readability. } ~/languages/rust { A systems language focused on safety and performance. } -~/languages/python 2:1 ~/languages/rust { Python has simpler syntax for beginners - fewer symbols, explicit over implicit. Rust's borrow checker adds cognitive load even for simple programs. Both are readable once learned, but Python's learning curve is gentler. } +{ Python has simpler syntax for beginners - fewer symbols, explicit over implicit. Rust's borrow checker adds cognitive load even for simple programs. Both are readable once learned, but Python's learning curve is gentler. } +~/languages/python 2:1 ~/languages/rust EOF # See current ranking diff --git a/ideas/single-thread.md b/ideas/single-thread.md index 86230fe6119c31045c21dbfcb12311b323c02fa8..0efb7199524cc3b308b1922c03e3a99193e4586c 100644 --- a/ideas/single-thread.md +++ b/ideas/single-thread.md @@ -15,7 +15,8 @@ Previously a `.sorter` document could scatter `#tags` throughout: ~/languages/rust {A systems language.} #tools ~/tools/cargo {Rust's build system.} -~/languages/rust 2:1 ~/tools/cargo {Rust is more foundational than its tooling.} +{Rust is more foundational than its tooling.} +~/languages/rust 2:1 ~/tools/cargo ``` The system would fan the ingest into both `#languages` and `#tools` — the same diff --git a/server/src/api/mod.rs b/server/src/api/mod.rs index 9f3c1cc21c2ae157c024a447980a97e190c8f066..920e967b47852ea82fa61b84c457ae3582dd9800 100644 --- a/server/src/api/mod.rs +++ b/server/src/api/mod.rs @@ -72,16 +72,16 @@ mod tests { apply_ingest( &mut reduced, 1, - "~/t/a {a}\n~/t/b {b}\n~/t/a 2:1 ~/t/b {because}\n", + "~/t/a {a}\n~/t/b {b}\n{because}\n~/t/a 2:1 ~/t/b\n", ); - let text = "~/t/a 1:1 ~/t/b {equal}\n"; + let text = "{equal}\n~/t/a 1:1 ~/t/b\n"; validate_ingest_document(&reduced, text, &crate::reducer::ScopeId::Public).unwrap(); } #[test] fn validate_ingest_document_rejects_vote_on_undefined_item() { let reduced = ReducerState::default(); - let text = "~/t/a {x}\n~/t/b 1:1 ~/t/missing {why}\n"; + let text = "~/t/a {x}\n{why}\n~/t/b 1:1 ~/t/missing\n"; let err = validate_ingest_document(&reduced, text, &crate::reducer::ScopeId::Public).unwrap_err(); assert_eq!(err.0, StatusCode::BAD_REQUEST); assert!(err.1.contains("undefined item")); diff --git a/server/src/api/ui_html.rs b/server/src/api/ui_html.rs index 696e7b3605e2e68aee0351116c494c2958506add..7cbda3876451687aa7a55547fc06bbe86ac9d260 100644 --- a/server/src/api/ui_html.rs +++ b/server/src/api/ui_html.rs @@ -222,13 +222,13 @@ async fn dispatch_ui_action( } let text = format!( - "@{}\n{} {}:{} {} {{\n{}\n}}\n", + "@{}\n{{\n{}\n}}\n{} {}:{} {}\n", crate::api::auth::WEB_BROWSER_AGENT, + exp, left_id.as_str(), rl, rr, - right_id.as_str(), - exp + right_id.as_str() ); match rpc_post_with_bearer(state, &session.bearer, room.clone(), thread_tag.clone(), text).await { diff --git a/server/src/dsl.rs b/server/src/dsl.rs index 7962342bd023b3b5061a684d84d4ab164134b111..def8b497c71567016a522648b9630d7038163e41 100644 --- a/server/src/dsl.rs +++ b/server/src/dsl.rs @@ -11,16 +11,21 @@ pub struct Document { /// A single statement in the DSL (or prose when using `parse_full`). #[derive(Debug, Clone, PartialEq, Eq)] pub enum Stmt { - Item { title: String, body: Option }, + Item { + title: String, + body: Option, + }, Vote { item1: String, item2: String, ratio_left: i32, ratio_right: i32, - /// Required non-empty explanation (from trailing `{ ... }`). + /// Required non-empty explanation (from leading `{ ... }`). explanation: String, }, - Prose { text: String }, + Prose { + text: String, + }, } #[derive(Debug, thiserror::Error)] @@ -391,71 +396,46 @@ fn parse_comparison_at(s: &str, i: usize) -> Option<((i32, i32), usize)> { Some(((left, right), j)) } -fn parse_item_statement(stripped: &str, masker: &BlockMasker) -> Result { - // item: ("~/" | "https://..." | "http://...") item_ref body? - // vote: same for both operands. - // - // Important: body token can be adjacent to the item name (no whitespace), - // e.g. "~/arrived{...}" -> "~/arrived__BLOCK_x__". - let s = stripped; - let bytes = s.as_bytes(); - if bytes.is_empty() { - return Err(DslError::Parse("missing item statement".to_string())); +fn parse_block_prefixed_statement( + block_token: &str, + tail: &str, + masker: &BlockMasker, +) -> Result { + // vote: block item_ref comparison item_ref + let s = tail.trim_start(); + if s.is_empty() { + return Err(DslError::Parse( + "missing vote statement after leading explanation block".to_string(), + )); } let (item1, j) = parse_item_name_at(s, 0).ok_or_else(|| DslError::Parse("invalid item name".to_string()))?; + let explanation = masker.extract_body(block_token); + let mut i = skip_ws(s, j); - // Either we have: - // - immediate/whitespace block token => Item - // - comparison => Vote - // - whitespace then block token => Item - // - whitespace then comparison => Vote - let i = skip_ws(s, j); - - // If next is end or a block token => Item. if i >= s.len() { - return Ok(Stmt::Item { - title: item1, - body: None, - }); - } - if let Some((tok, end)) = parse_block_token_at(s, i) { - let body = masker.extract_body(&tok); - let tail = s[end..].trim(); - if !tail.is_empty() { - return Err(DslError::Parse("extra tokens after item".to_string())); - } - return Ok(Stmt::Item { - title: item1, - body: Some(body), - }); + return Err(DslError::Parse( + "leading `{ ... }` blocks are vote explanations; item bodies belong after item paths" + .to_string(), + )); } - // Otherwise parse comparison then "/item2" then REQUIRED body. - let ((ratio_left, ratio_right), mut k) = parse_comparison_at(s, i) + let ((ratio_left, ratio_right), k) = parse_comparison_at(s, i) .ok_or_else(|| DslError::Parse(format!("invalid comparison near: {}", &s[i..])))?; if ratio_left == 0 && ratio_right == 0 { return Err(DslError::Parse( "vote ratio 0:0 is invalid; use 1:1 for a tie or omit the vote".to_string(), )); } - k = skip_ws(s, k); - let (item2, mut m) = parse_item_name_at(s, k) + i = skip_ws(s, k); + let (item2, m) = parse_item_name_at(s, i) .ok_or_else(|| DslError::Parse("invalid rhs item name".to_string()))?; - m = skip_ws(s, m); - - let Some((tok, end)) = parse_block_token_at(s, m) else { - return Err(DslError::Parse( - "missing vote explanation (add a trailing `{ ... }`)".to_string(), - )); - }; - let explanation = masker.extract_body(&tok); + i = skip_ws(s, m); if explanation.trim().is_empty() { return Err(DslError::Parse("empty vote explanation".to_string())); } - m = end; - let tail = s[m..].trim(); + let tail = s[i..].trim(); if !tail.is_empty() { return Err(DslError::Parse("extra tokens after vote".to_string())); } @@ -469,6 +449,35 @@ fn parse_item_statement(stripped: &str, masker: &BlockMasker) -> Result Result { + let (item1, j) = + parse_item_name_at(stripped, 0).ok_or_else(|| DslError::Parse("invalid item name".to_string()))?; + let i = skip_ws(stripped, j); + + if i >= stripped.len() { + return Ok(Stmt::Item { + title: item1, + body: None, + }); + } + + if let Some((tok, end)) = parse_block_token_at(stripped, i) { + let body = masker.extract_body(&tok); + let tail = stripped[end..].trim(); + if !tail.is_empty() { + return Err(DslError::Parse("extra tokens after item".to_string())); + } + return Ok(Stmt::Item { + title: item1, + body: Some(body), + }); + } + + Err(DslError::Parse( + "vote explanations must start with a `{ ... }` block before the comparison".to_string(), + )) +} + fn parse_line(masked_line: &str, masker: &BlockMasker) -> Result, DslError> { let stripped = masked_line.trim_start(); if stripped.is_empty() { @@ -477,27 +486,28 @@ fn parse_line(masked_line: &str, masker: &BlockMasker) -> Result, DslE let first = stripped.chars().next().unwrap(); match first { '#' => Err(DslError::Parse("not a DSL line".to_string())), - ':' => Err(DslError::Parse( - "leading ':' is not supported".to_string(), - )), + ':' => Err(DslError::Parse("leading ':' is not supported".to_string())), '@' => Err(DslError::Parse("not a DSL line".to_string())), + '_' => { + let Some((tok, end)) = parse_block_token_at(stripped, 0) else { + return Err(DslError::Parse("not a DSL line".to_string())); + }; + parse_block_prefixed_statement(&tok, &stripped[end..], masker).map(|stmt| vec![stmt]) + } '/' => Err(DslError::Parse( - "item paths must use `~/` (e.g. `~/languages/python`), not a leading `/`" - .to_string(), + "item paths must use `~/` (e.g. `~/languages/python`), not a leading `/`".to_string(), )), - '~' => { - Ok(vec![parse_item_statement(stripped, masker)?]) - } + '~' => Ok(vec![parse_item_definition_statement(stripped, masker)?]), 'h' => { if stripped.starts_with("https://") || stripped.starts_with("http://") { - Ok(vec![parse_item_statement(stripped, masker)?]) + Ok(vec![parse_item_definition_statement(stripped, masker)?]) } else { Err(DslError::Parse("not a DSL line".to_string())) } } '-' => { if stripped.starts_with("-/") { - Ok(vec![parse_item_statement(stripped, masker)?]) + Ok(vec![parse_item_definition_statement(stripped, masker)?]) } else { Err(DslError::Parse("not a DSL line".to_string())) } @@ -516,6 +526,7 @@ pub fn parse_full(text: &str) -> Result { let (masker, masked) = mask_all(BlockMasker::new(), text); let mut statements: Vec = Vec::new(); let mut prose_buffer: Vec<&str> = Vec::new(); + let mut pending_block: Option = None; let flush_prose = |buf: &mut Vec<&str>, out: &mut Vec, masker: &BlockMasker| { if buf.is_empty() { @@ -529,11 +540,29 @@ pub fn parse_full(text: &str) -> Result { for line in masked.split('\n') { let stripped = line.trim_start(); + if let Some(tok) = pending_block.as_ref() { + if stripped.is_empty() { + continue; + } + if stripped.starts_with("-/") + || stripped.starts_with("~/") + || stripped.starts_with("https://") + || stripped.starts_with("http://") + { + statements.push(parse_block_prefixed_statement(tok, stripped, &masker)?); + pending_block = None; + continue; + } + return Err(DslError::Parse( + "expected vote statement after leading explanation block".to_string(), + )); + } + if !stripped.is_empty() && (stripped.starts_with("-/") || { let c = stripped.chars().next().unwrap(); - ":/!~".contains(c) + ":/!~_".contains(c) } || stripped.starts_with("https://") || stripped.starts_with("http://")) @@ -541,6 +570,13 @@ pub fn parse_full(text: &str) -> Result { // Flush prose buffer first flush_prose(&mut prose_buffer, &mut statements, &masker); + if let Some((tok, end)) = parse_block_token_at(stripped, 0) { + if stripped[end..].trim().is_empty() { + pending_block = Some(tok); + continue; + } + } + // Parse DSL line; DSL statements are not prose, so errors should propagate. statements.extend(parse_line(line, &masker)?); } else { @@ -548,6 +584,12 @@ pub fn parse_full(text: &str) -> Result { } } + if pending_block.is_some() { + return Err(DslError::Parse( + "missing vote statement after leading explanation block".to_string(), + )); + } + // Final flush flush_prose(&mut prose_buffer, &mut statements, &masker); @@ -592,7 +634,7 @@ mod tests { #[test] fn parse_vote_ratio_and_symbols() { - let d1 = parse_full("~/a 3:1 ~/b {because}").unwrap(); + let d1 = parse_full("{because}\n~/a 3:1 ~/b").unwrap(); assert_eq!( d1.statements, vec![Stmt::Vote { @@ -604,7 +646,7 @@ mod tests { }] ); - let d2 = parse_full("~/a > ~/b {because}").unwrap(); + let d2 = parse_full("{because}\n~/a > ~/b").unwrap(); assert_eq!( d2.statements, vec![Stmt::Vote { @@ -616,7 +658,7 @@ mod tests { }] ); - let d3 = parse_full("~/a = ~/b {because}").unwrap(); + let d3 = parse_full("{because}\n~/a = ~/b").unwrap(); assert_eq!( d3.statements, vec![Stmt::Vote { @@ -631,7 +673,7 @@ mod tests { #[test] fn parse_vote_rejects_zero_zero_ratio() { - let err = parse_full("~/a 0:0 ~/b {tie placeholder}").unwrap_err(); + let err = parse_full("{tie placeholder}\n~/a 0:0 ~/b").unwrap_err(); let msg = match err { DslError::Parse(m) => m, }; @@ -667,8 +709,8 @@ mod tests { } #[test] - fn parse_vote_with_attached_body_without_space() { - let input = "~/a 2:1 ~/b{because}"; + fn parse_vote_with_attached_explanation_without_space() { + let input = "{because}~/a 2:1 ~/b"; let doc = parse_full(input).unwrap(); assert_eq!( doc.statements, @@ -697,7 +739,7 @@ mod tests { #[test] fn parse_nested_path_vote() { - let input = "~/whitepaper/a 3:1 ~/whitepaper/b { because }"; + let input = "{ because }\n~/whitepaper/a 3:1 ~/whitepaper/b"; let doc = parse_full(input).unwrap(); assert_eq!( doc.statements, @@ -718,7 +760,10 @@ mod tests { let result = parse_full(input); assert!(result.is_err(), "expected parse error for {input:?}"); assert!( - result.unwrap_err().to_string().contains("leading ':' is not supported"), + result + .unwrap_err() + .to_string() + .contains("leading ':' is not supported"), "wrong error for {input:?}" ); } @@ -741,7 +786,35 @@ mod tests { let result = parse_full(input); assert!(result.is_err(), "vote without explanation should fail"); let err_msg = result.unwrap_err().to_string(); - assert!(err_msg.contains("missing vote explanation"), "error: {}", err_msg); + assert!( + err_msg.contains("vote explanations must start"), + "error: {}", + err_msg + ); + } + + #[test] + fn parse_full_rejects_legacy_trailing_explanation_vote() { + let result = parse_full("~/a 2:1 ~/b {because}"); + assert!(result.is_err(), "legacy vote syntax should fail"); + let err_msg = result.unwrap_err().to_string(); + assert!( + err_msg.contains("vote explanations must start"), + "error: {}", + err_msg + ); + } + + #[test] + fn parse_full_rejects_block_first_item_body() { + let result = parse_full("{body}\n~/a"); + assert!(result.is_err(), "block-first item body syntax should fail"); + let err_msg = result.unwrap_err().to_string(); + assert!( + err_msg.contains("item bodies belong after item paths"), + "error: {}", + err_msg + ); } #[test] @@ -771,7 +844,7 @@ mod tests { #[test] fn parse_url_vote_statement() { - let input = "https://slug.social/~/music/a 3:1 https://slug.social/~/music/b { because }"; + let input = "{ because }\nhttps://slug.social/~/music/a 3:1 https://slug.social/~/music/b"; let doc = parse_full(input).unwrap(); assert_eq!( doc.statements, @@ -785,5 +858,3 @@ mod tests { ); } } - - diff --git a/server/src/html/editor.rs b/server/src/html/editor.rs index 8ff58326eb75806eeec3937f088fa977c7f3886e..216b144a4acef09d0addddd1528e5323433ac832 100644 --- a/server/src/html/editor.rs +++ b/server/src/html/editor.rs @@ -39,7 +39,7 @@ pub async fn editor_page(State(state): State, jar: CookieJar, uri: Uri p class="muted" { "write DSL, see what happens. nothing is saved." } div class="editor-container" { textarea id="editor-input" rows="12" cols="80" - placeholder="your-uuid:rig:provider/model\n#your-thread\n\n~/path/item-a { description }\n~/path/item-b { description }\n\n~/path/item-a 3:1 ~/path/item-b { reasoning }" + placeholder="your-uuid:rig:provider/model\n#your-thread\n\n{ description }\n~/path/item-a\n{ description }\n~/path/item-b\n\n{ reasoning }\n~/path/item-a 3:1 ~/path/item-b" autocomplete="off" autofocus {} div id="editor-status" class="muted" { "type to check…" } div id="editor-results" {} diff --git a/server/src/html/garden.rs b/server/src/html/garden.rs index 9e08307e636ce7984766168db1187f84b8635201..86b4c184724910bb464682b9025d19ce6cd2050d 100644 --- a/server/src/html/garden.rs +++ b/server/src/html/garden.rs @@ -1454,8 +1454,8 @@ mod tests { ~/topic {root}\n\ ~/topic/a {alpha}\n\ ~/topic/b {beta}\n\ - ~/topic/a 1:9 ~/topic/b {weak for a}\n\ - ~/topic/a 8:2 ~/topic/b {strong for a}\n", + {weak for a}\n ~/topic/a 1:9 ~/topic/b\n\ + {strong for a}\n ~/topic/a 8:2 ~/topic/b\n", ); let content = content_for_garden_view(&reduced, &ScopeId::Public); let page_left = ItemId::parse("~/topic/a").unwrap().normalized_storage(); @@ -1483,8 +1483,10 @@ mod tests { ~/topic {root}\n\ ~/topic/a {alpha}\n\ ~/topic/b {beta}\n\ - ~/topic/a 3:2 ~/topic/b {first vote}\n\ - ~/topic/b 2:3 ~/topic/a {second vote}\n", + {first vote}\n\ + ~/topic/a 3:2 ~/topic/b\n\ + {second vote}\n\ + ~/topic/b 2:3 ~/topic/a\n", ); let content = content_for_garden_view(&reduced, &ScopeId::Public); let a = ItemId::parse("~/topic/a").unwrap().normalized_storage(); @@ -1525,7 +1527,7 @@ mod tests { ~/topic/a {alpha}\n\ ~/topic/b {beta}\n\ ~/topic/c {gamma}\n\ - ~/topic/a 2:1 ~/topic/b {a beats b}\n", + {a beats b}\n ~/topic/a 2:1 ~/topic/b\n", ); let model = build_item_page_view_model(&reduced, &ScopeId::Public, "~/topic/a"); @@ -1545,7 +1547,7 @@ mod tests { ~/topic {root}\n\ ~/topic/a {alpha}\n\ ~/topic/b {beta}\n\ - ~/topic/a 3:1 ~/topic/b {a beats b}\n\ + {a beats b}\n ~/topic/a 3:1 ~/topic/b\n\ ~/topic/kid1 {k1}\n\ ~/topic/kid2 {k2}\n\ ~/topic/kid1/leaf {leaf}\n", @@ -1616,7 +1618,7 @@ mod tests { 1, "9ab12cd/my-room", "@00000000-0000-0000-0000-000000000000:test:local/test\n\ - ~/a {a}\n~/b {b}\n~/a 2:1 ~/b {because}\n", + ~/a {a}\n~/b {b}\n{because}\n~/a 2:1 ~/b\n", ); use crate::path_types::ItemId; let root = ItemId::ontology_root(); diff --git a/server/tests/basic.rs b/server/tests/basic.rs index 4a4faa73e2f0338fc541237104d99ea05b3e599a..2f17ce91091745ce1b5ebd1575248565df3b3514 100644 --- a/server/tests/basic.rs +++ b/server/tests/basic.rs @@ -31,7 +31,7 @@ fn ingest_event(ts: i64, raw: &str) -> Event { fn vote_doc(tag: &str, a: &str, b: &str, left: i32, right: i32) -> String { format!( - "~/{tag}/{a} {{body a}}\n~/{tag}/{b} {{body b}}\n~/{tag}/{a} {left}:{right} ~/{tag}/{b} {{because test}}\n" + "~/{tag}/{a} {{body a}}\n~/{tag}/{b} {{body b}}\n{{because test}}\n~/{tag}/{a} {left}:{right} ~/{tag}/{b}\n" ) } @@ -47,7 +47,7 @@ fn reducer_external_namespace_ranking() { "@00000000-0000-0000-0000-000000000000:test:local/test\n\ -/github.com/iss/1 { one }\n\ -/github.com/iss/2 { two }\n\ - -/github.com/iss/1 2:1 -/github.com/iss/2 { because }\n", + { because }\n -/github.com/iss/1 2:1 -/github.com/iss/2\n", )); let content = state.public(); @@ -77,9 +77,9 @@ fn reducer_and_ranking_linear_chain() { let mut state = ReducerState::default(); // First ingest: define items + vote a > b. - state.apply_event(ingest_event(1, "~/t/a {a}\n~/t/b {b}\n~/t/a 3:1 ~/t/b {because}\n")); + state.apply_event(ingest_event(1, "~/t/a {a}\n~/t/b {b}\n{because}\n~/t/a 3:1 ~/t/b\n")); // Second ingest: define c + vote b > c. - state.apply_event(ingest_event(2, "~/t/c {c}\n~/t/b 3:1 ~/t/c {because}\n")); + state.apply_event(ingest_event(2, "~/t/c {c}\n{because}\n~/t/b 3:1 ~/t/c\n")); let mut group = state.public().ranking_group.clone(); let ranked = ranked_items(&mut group, 20000, 1e-9); @@ -96,15 +96,15 @@ fn reducer_canonicalizes_identifiers() { // Mix of formats across ingests (case + sigils). state.apply_event(ingest_event( 1, - "~/Tag/Item-A {x}\n~/Tag/Item-B {y}\n~/Tag/Item-A 2:1 ~/Tag/Item-B {because}\n", + "~/Tag/Item-A {x}\n~/Tag/Item-B {y}\n{because}\n~/Tag/Item-A 2:1 ~/Tag/Item-B\n", )); state.apply_event(ingest_event( 2, - "~/TAG/ITEM-A 2:1 ~/TAG/ITEM-B {because}\n", + "{because}\n~/TAG/ITEM-A 2:1 ~/TAG/ITEM-B\n", )); state.apply_event(ingest_event( 3, - "~/tag/item-a 2:1 ~/tag/item-b {because}\n", + "{because}\n~/tag/item-a 2:1 ~/tag/item-b\n", )); assert_eq!(state.public().ranking_group.idx_to_item.len(), 2); // Should dedupe to 2 items @@ -135,7 +135,7 @@ fn reducer_handles_item_and_body_from_ingest() { fn reducer_indexes_item_threads_and_vote_thread() { let mut state = ReducerState::default(); // Thread routing is metadata (ingest.thread_tag), not parsed from raw. - let mut ev = match ingest_event(1, "~/sorts/insertion { O(n^2) }\n~/sorts/mergesort { O(n log n) }\n~/sorts/insertion 3:1 ~/sorts/mergesort { simpler for small n }\n") { + let mut ev = match ingest_event(1, "~/sorts/insertion { O(n^2) }\n~/sorts/mergesort { O(n log n) }\n{ simpler for small n }\n~/sorts/insertion 3:1 ~/sorts/mergesort\n") { Event::Ingest(i) => i, _ => unreachable!(), }; @@ -175,11 +175,11 @@ fn reducer_clamps_score_bounds() { let mut state = ReducerState::default(); state.apply_event(ingest_event( 1, - "@00000000-0000-0000-0000-000000000000:test:local/test\n~/t/a {a}\n~/t/b {b}\n~/t/a 1000:1 ~/t/b {huge}\n", + "@00000000-0000-0000-0000-000000000000:test:local/test\n~/t/a {a}\n~/t/b {b}\n{huge}\n~/t/a 1000:1 ~/t/b\n", )); state.apply_event(ingest_event( 2, - "@00000000-0000-0000-0000-000000000000:test:local/test\n~/t/a 1:1000 ~/t/b {huge}\n", + "@00000000-0000-0000-0000-000000000000:test:local/test\n{huge}\n~/t/a 1:1000 ~/t/b\n", )); assert_eq!(state.public().ranking_group.idx_to_item.len(), 2); // Should still work, scores clamped internally @@ -195,15 +195,15 @@ fn ranking_cycle_is_nearly_equal() { let mut state = ReducerState::default(); state.apply_event(ingest_event( 1, - "@00000000-0000-0000-0000-000000000000:test:local/test\n~/rps/rock {r}\n~/rps/scissors {s}\n~/rps/rock 3:1 ~/rps/scissors {because}\n", + "@00000000-0000-0000-0000-000000000000:test:local/test\n~/rps/rock {r}\n~/rps/scissors {s}\n{because}\n~/rps/rock 3:1 ~/rps/scissors\n", )); state.apply_event(ingest_event( 2, - "@00000000-0000-0000-0000-000000000000:test:local/test\n~/rps/paper {p}\n~/rps/scissors 3:1 ~/rps/paper {because}\n", + "@00000000-0000-0000-0000-000000000000:test:local/test\n~/rps/paper {p}\n{because}\n~/rps/scissors 3:1 ~/rps/paper\n", )); state.apply_event(ingest_event( 3, - "@00000000-0000-0000-0000-000000000000:test:local/test\n~/rps/paper 3:1 ~/rps/rock {because}\n", + "@00000000-0000-0000-0000-000000000000:test:local/test\n{because}\n~/rps/paper 3:1 ~/rps/rock\n", )); let mut group = state.public().ranking_group.clone(); @@ -233,7 +233,7 @@ fn ranking_dominant_item_wins() { let mut state = ReducerState::default(); state.apply_event(ingest_event( 1, - "@00000000-0000-0000-0000-000000000000:test:local/test\n~/t/champion {c}\n~/t/b {b}\n~/t/c {c}\n~/t/d {d}\n~/t/champion 10:1 ~/t/b {because}\n~/t/champion 10:1 ~/t/c {because}\n~/t/champion 10:1 ~/t/d {because}\n~/t/b 2:1 ~/t/c {because}\n~/t/c 2:1 ~/t/d {because}\n", + "@00000000-0000-0000-0000-000000000000:test:local/test\n~/t/champion {c}\n~/t/b {b}\n~/t/c {c}\n~/t/d {d}\n{because}\n~/t/champion 10:1 ~/t/b\n{because}\n~/t/champion 10:1 ~/t/c\n{because}\n~/t/champion 10:1 ~/t/d\n{because}\n~/t/b 2:1 ~/t/c\n{because}\n~/t/c 2:1 ~/t/d\n", )); let mut group = state.public().ranking_group.clone(); @@ -248,7 +248,7 @@ fn ranking_neutral_votes_produce_equal_scores() { let mut state = ReducerState::default(); state.apply_event(ingest_event( 1, - "@00000000-0000-0000-0000-000000000000:test:local/test\n~/t/a {a}\n~/t/b {b}\n~/t/c {c}\n~/t/a 1:1 ~/t/b {neutral}\n~/t/b 1:1 ~/t/c {neutral}\n~/t/c 1:1 ~/t/a {neutral}\n", + "@00000000-0000-0000-0000-000000000000:test:local/test\n~/t/a {a}\n~/t/b {b}\n~/t/c {c}\n{neutral}\n~/t/a 1:1 ~/t/b\n{neutral}\n~/t/b 1:1 ~/t/c\n{neutral}\n~/t/c 1:1 ~/t/a\n", )); let mut group = state.public().ranking_group.clone(); @@ -301,8 +301,8 @@ async fn event_log_append_and_load() { let log = EventLog::new(log_path); let events = vec![ - ingest_event(1, "~/a {x}\n~/b {y}\n~/a 2:1 ~/b {because}\n"), - ingest_event(2, "~/b 3:1 ~/c {because}\n"), + ingest_event(1, "~/a {x}\n~/b {y}\n{because}\n~/a 2:1 ~/b\n"), + ingest_event(2, "{because}\n~/b 3:1 ~/c\n"), ]; for ev in &events { @@ -323,7 +323,7 @@ async fn event_log_handles_corrupt_lines() { let log = EventLog::new(&log_path); // Write valid events using the log itself, then manually corrupt one line. - log.append(&ingest_event(1, "~/a {x}\n~/b {y}\n~/a 2:1 ~/b {because}\n")) + log.append(&ingest_event(1, "~/a {x}\n~/b {y}\n{because}\n~/a 2:1 ~/b\n")) .await .unwrap(); @@ -332,7 +332,7 @@ async fn event_log_handles_corrupt_lines() { let mut f = fs::OpenOptions::new().append(true).open(&log_path).unwrap(); writeln!(f, "not json at all").unwrap(); - log.append(&ingest_event(2, "~/b 3:1 ~/c {because}\n")) + log.append(&ingest_event(2, "{because}\n~/b 3:1 ~/c\n")) .await .unwrap(); @@ -351,7 +351,7 @@ async fn event_log_creates_parent_dirs() { let log_path = tmp.path().join("subdir").join("nested").join("events.jsonl"); let log = EventLog::new(&log_path); - log.append(&ingest_event(1, "~/a {x}\n~/b {y}\n~/a 2:1 ~/b {because}\n")) + log.append(&ingest_event(1, "~/a {x}\n~/b {y}\n{because}\n~/a 2:1 ~/b\n")) .await .unwrap(); assert!(log_path.exists()); @@ -379,7 +379,7 @@ async fn full_workflow_reducer_and_ranking() { state.apply_event(ingest_event( 1, - "~/langs/rust {Systems language}\n~/langs/go {Simple concurrency}\n~/langs/rust 3:1 ~/langs/go {because}\n", + "~/langs/rust {Systems language}\n~/langs/go {Simple concurrency}\n{because}\n~/langs/rust 3:1 ~/langs/go\n", )); let mut group = state.public().ranking_group.clone(); @@ -452,21 +452,21 @@ fn ranking_repeated_votes_normalized() { let mut state_once = ReducerState::default(); state_once.apply_event(ingest_event( 1, - "~/norm/a {a}\n~/norm/b {b}\n~/norm/a 3:1 ~/norm/b {vote}\n", + "~/norm/a {a}\n~/norm/b {b}\n{vote}\n~/norm/a 3:1 ~/norm/b\n", )); let mut state_many = ReducerState::default(); state_many.apply_event(ingest_event( 1, - "~/norm/a {a}\n~/norm/b {b}\n~/norm/a 3:1 ~/norm/b {vote1}\n", + "~/norm/a {a}\n~/norm/b {b}\n{vote1}\n~/norm/a 3:1 ~/norm/b\n", )); state_many.apply_event(ingest_event( 2, - "~/norm/a 3:1 ~/norm/b {vote2}\n", + "{vote2}\n~/norm/a 3:1 ~/norm/b\n", )); state_many.apply_event(ingest_event( 3, - "~/norm/a 3:1 ~/norm/b {vote3}\n", + "{vote3}\n~/norm/a 3:1 ~/norm/b\n", )); let mut group_once = state_once.public().ranking_group.clone(); @@ -508,7 +508,7 @@ fn reducer_malformed_ingest_is_skipped_no_panic() { #[test] fn dsl_parse_rejects_zero_zero_vote_ratio() { let err = slugsocial_server::dsl::parse_full( - "~/t/a {a}\n~/t/b {b}\n~/t/a 0:0 ~/t/b {zero}\n", + "~/t/a {a}\n~/t/b {b}\n{zero}\n~/t/a 0:0 ~/t/b\n", ) .expect_err("0:0 vote must be rejected by the parser"); let msg = match err { @@ -522,7 +522,7 @@ fn dsl_parse_rejects_zero_zero_vote_ratio() { let mut state = ReducerState::default(); state.apply_event(ingest_event( 1, - "~/t/a {a}\n~/t/b {b}\n~/t/a 0:0 ~/t/b {zero}\n", + "~/t/a {a}\n~/t/b {b}\n{zero}\n~/t/a 0:0 ~/t/b\n", )); let content = state.public(); assert!( @@ -620,7 +620,7 @@ fn ranking_convergence_tolerance_triggers_early_exit() { let mut state = ReducerState::default(); state.apply_event(ingest_event( 1, - "~/t/a {a}\n~/t/b {b}\n~/t/a 3:1 ~/t/b {because}\n", + "~/t/a {a}\n~/t/b {b}\n{because}\n~/t/a 3:1 ~/t/b\n", )); let mut group = state.public().ranking_group.clone(); // Very tight tolerance but huge max_iters — should still converge fast @@ -742,7 +742,7 @@ fn test_thread_timestamp_bump() { #[test] fn test_thread_id_is_used_for_votes_and_indexes() { let mut state = ReducerState::default(); - let mut ev = match ingest_event(1, "~/t/a {a}\n~/t/b {b}\n~/t/a 2:1 ~/t/b {reason}\n") { + let mut ev = match ingest_event(1, "~/t/a {a}\n~/t/b {b}\n{reason}\n~/t/a 2:1 ~/t/b\n") { Event::Ingest(i) => i, _ => unreachable!(), }; @@ -770,7 +770,7 @@ fn test_rank_history_created_for_voted_items() { let mut state = ReducerState::default(); state.apply_event(ingest_event( 1, - "~/t/a {a}\n~/t/b {b}\n~/t/a 3:1 ~/t/b {reason}\n", + "~/t/a {a}\n~/t/b {b}\n{reason}\n~/t/a 3:1 ~/t/b\n", )); assert!( state.public().rank_history.contains_key(&item_id("https://slug.social/~/t/a")), @@ -800,7 +800,7 @@ fn test_rank_history_first_entry_delta_zero() { let mut state = ReducerState::default(); state.apply_event(ingest_event( 1, - "~/t/a {a}\n~/t/b {b}\n~/t/a 3:1 ~/t/b {reason}\n", + "~/t/a {a}\n~/t/b {b}\n{reason}\n~/t/a 3:1 ~/t/b\n", )); let history_a = state.public().rank_history.get(&item_id("https://slug.social/~/t/a")).unwrap(); assert_eq!(history_a.len(), 1); diff --git a/server/tests/dsl_fixtures.rs b/server/tests/dsl_fixtures.rs index 2446da86447508b36b7a7dfb112b35cc5a4cc1e6..62f3fa14adc8203562338bf75f9310b99bacbb43 100644 --- a/server/tests/dsl_fixtures.rs +++ b/server/tests/dsl_fixtures.rs @@ -28,7 +28,7 @@ fn parses_tutorial_fixture_with_prose() { #[test] fn parses_big_book_fixture_with_attached_bodies() { - // This doc heavily uses the "~/name{...}" style with no whitespace. + // This doc heavily uses the "{...}\n~/name" style with no whitespace. let doc = dsl::parse_full(BIG_BOOK).expect("parse_full should succeed"); let mut items = 0usize; @@ -55,7 +55,7 @@ fn parses_big_book_fixture_with_attached_bodies() { #[test] fn parses_external_dash_vote_line() { - let doc = dsl::parse_full("-/domain.com/a 2:1 -/domain.com/b { reason }").unwrap(); + let doc = dsl::parse_full("{ reason }\n-/domain.com/a 2:1 -/domain.com/b").unwrap(); assert_eq!( doc.statements, vec![dsl::Stmt::Vote { diff --git a/server/tests/fixtures/big-book.sorter b/server/tests/fixtures/big-book.sorter index 7b3ce871d4f56210d48ecbf6f1ca33371d89eda9..3472f18c6d2e7fdd608b5936d34301480498cf40 100644 --- a/server/tests/fixtures/big-book.sorter +++ b/server/tests/fixtures/big-book.sorter @@ -1,10 +1,10 @@ #Big-Book -~/big-book/arrived{ +~/big-book/arrived { I had arrived. } -~/big-book/how-it-works{ +~/big-book/how-it-works { Rarely have we seen a person fail who has thoroughly followed our path. Those who do not recover are people who cannot or will not completely give @@ -58,7 +58,7 @@ lives. (b) That probably no human power could have relieved our alcoholism. } -~/big-book/run-the-show{ +~/big-book/run-the-show { The first requirement is that we be convinced that any life run on self-will can hardly be a success. On that basis we are almost always in collision with something or somebody, even though our motives are good. @@ -94,7 +94,7 @@ all and is locked up. Whatever our protestations, are not most of us concerned with ourselves, our resentments, or our self-pity? } -~/big-book/god-director{ +~/big-book/god-director { This is the how and why of it. First of all, we had to quit playing God. It didn’t work. Next, we decided that hereafter in this drama of life, God was @@ -126,7 +126,7 @@ were ready; that we could at last abandon ourselves utterly to Him. } -~/big-book/dubious-luxury{ +~/big-book/dubious-luxury { But with the alcoholic, whose hope is the maintenance and growth of a spiritual experience, this business of resentment is infinitely grave. We @@ -139,7 +139,7 @@ poison. } -~/big-book/sick-mans-prayer{ +~/big-book/sick-mans-prayer { This was our course: We realized that the people who wronged us were perhaps spiritually sick. HOW IT WORKS 67 Though we did not like their @@ -151,7 +151,7 @@ him? God save me from being angry. Thy will be done.’’ } -~/big-book/fear-calamity-serenity{ +~/big-book/fear-calamity-serenity { Notice that the word “fear’’ is bracketed alongside the difficulties with Mr. Brown, Mrs. Jones, the employer, and the wife. This short word somehow diff --git a/server/tests/fixtures/tutorial.sorter b/server/tests/fixtures/tutorial.sorter index d8228c3a2986fbeb08817ebdedd4f61cfa6ee724..60b4dc92d5212703df65e70949f7251cd5a85c3d 100644 --- a/server/tests/fixtures/tutorial.sorter +++ b/server/tests/fixtures/tutorial.sorter @@ -15,9 +15,9 @@ subsequent items will be catalogued in the index under this context. We are in a tag, now let's declare an item. -~/alphabet/a +~/alphabet/a {the letter a} -~/alphabet/b +~/alphabet/b {the letter b} The prefix `~/` denotes, when the first characters on a line, the beginning of the title of an ontology item (the garden layer). @@ -25,7 +25,8 @@ Now we have two discrete, addressable items. Imagine two dots floating on a 2d plane. Now let's draw a line segment between the two dots. -~/alphabet/a 2:1 ~/alphabet/b {a edges out b in this ranking} +{a edges out b in this ranking} +~/alphabet/a 2:1 ~/alphabet/b We have asserted that ~/alphabet/a wins over ~/alphabet/b, winning 66% of that matchup. @@ -35,12 +36,13 @@ From this assertion we derive the ranking: 2) ~/alphabet/b If we were to send this email right now, we could view the ranking at -https://slug.social/~/alphabet +the URL https://slug.social/~/alphabet Easy enough. -~/alphabet/c +~/alphabet/c {the letter c} -~/alphabet/a 3:1 ~/alphabet/c {a strongly preferred to c here} +{a strongly preferred to c here} +~/alphabet/a 3:1 ~/alphabet/c Now the ranking is 1) ~/alphabet/a @@ -102,20 +104,24 @@ Sorter is proprietary, trying to become a venture scale business. Now we have six dots swimming around. Lets order them. truth -~/sorter-properties/collective = ~/sorter-properties/asynchronous {roughly equally important} -~/sorter-properties/asynchronous = ~/sorter-properties/precise {roughly equally important} -~/sorter-properties/precise = ~/sorter-properties/transitive {roughly equally important} +{roughly equally important} +~/sorter-properties/collective = ~/sorter-properties/asynchronous +{roughly equally important} +~/sorter-properties/asynchronous = ~/sorter-properties/precise +{roughly equally important} +~/sorter-properties/precise = ~/sorter-properties/transitive All equally, absolutely true. -~/sorter-properties/asynchronous 10:1 ~/sorter-properties/new { +{ Sorter is certainly asynchronous. There have been many explorations of the core sorter idea. Pairwise comparisons have been studied for decades. Conjoint analysis. HotOrNot. Sorter is just one iteration of the human desire to rank things collectively } +~/sorter-properties/asynchronous 10:1 ~/sorter-properties/new -~/sorter-properties/new 100:1 ~/sorter-properties/proprietary { +{ There are some new things about sorter. The backwards compatible with prose syntax. The synthesis of email-first, rank-centrality, and social platform. So @@ -124,6 +130,7 @@ But sorter is absolutely not ~/sorter-properties/proprietary. Sorter is open sou github.com/sortersocial/index Therefore, ~/sorter-properties/proprietary is banished 100:1 to the false end of the spectrum. } +~/sorter-properties/new 100:1 ~/sorter-properties/proprietary In sorter, there are no binaries. Everything is a spectrum, including truth. @@ -131,11 +138,17 @@ truth. The most important thing, in my mind, about sorter is that it’s collective. important -~/sorter-properties/collective 100:20 ~/sorter-properties/asynchronous { sorter would still be cool if it was -live } -~/sorter-properties/collective 100:90 ~/sorter-properties/precise { precise thinking is good too } -~/sorter-properties/collective 100:90 ~/sorter-properties/transitive { transitivity enables collectivity } -~/sorter-properties/collective 100:10 ~/sorter-properties/new { other iterations of sorter were good too } +{ +sorter would still be cool if it was +live +} +~/sorter-properties/collective 100:20 ~/sorter-properties/asynchronous +{ precise thinking is good too } +~/sorter-properties/collective 100:90 ~/sorter-properties/precise +{ transitivity enables collectivity } +~/sorter-properties/collective 100:90 ~/sorter-properties/transitive +{ other iterations of sorter were good too } +~/sorter-properties/collective 100:10 ~/sorter-properties/new Any other person could add to or vote on #sorter-properties, this is just diff --git a/server/tests/integration.rs b/server/tests/integration.rs index bd10fd2a6ef06ac1a23de790a54ad5aa0065a472..e96d11c820c3bbaa8bb55ad11636397ef225e55a 100644 --- a/server/tests/integration.rs +++ b/server/tests/integration.rs @@ -673,7 +673,7 @@ async fn test_private_room_post_links_use_private_garden_routes() { let rpc = ui_post_ingest_rpc( &room_id, "garden-thread", - "~/secret/item {classified}\n~/secret/other {other body}\n~/secret/item 3:1 ~/secret/other {because}\n", + "~/secret/item {classified}\n~/secret/other {other body}\n{because}\n~/secret/item 3:1 ~/secret/other\n", ); let post = client .post(format!("http://{addr}/ui")) @@ -734,7 +734,7 @@ async fn test_private_room_garden_root_lists_top_level_tilde_children() { let rpc = ui_post_ingest_rpc( &room_id, "ing", - "~/test1 {wow}\n~/test2 {wow2}\n~/test1 2:1 ~/test2 {because}\n", + "~/test1 {wow}\n~/test2 {wow2}\n{because}\n~/test1 2:1 ~/test2\n", ); let post = client .post(format!("http://{addr}/ui")) @@ -1003,7 +1003,7 @@ async fn test_post_redact_removes_garden_and_marks_thread() { "room": "public", "thread_tag": "redact-test", "delegate": "00000000-0000-0000-0000-000000000000:test:local/test", - "text": "~/del-a {a}\n~/del-b {b}\n~/del-a 2:1 ~/del-b {vote line}\n", + "text": "~/del-a {a}\n~/del-b {b}\n{vote line}\n~/del-a 2:1 ~/del-b\n", "return_rank_diff": false } }]), @@ -1123,7 +1123,7 @@ async fn test_vote_endpoint() { "room": "public", "thread_tag": "cli", "delegate": "00000000-0000-0000-0000-000000000000:test:local/test", - "text": "~/clap {cli parser}\n~/argh {cli parser}\n~/clap 3:1 ~/argh {because clap is more full-featured}\n", + "text": "~/clap {cli parser}\n~/argh {cli parser}\n{because clap is more full-featured}\n~/clap 3:1 ~/argh\n", "return_rank_diff": true } }]); @@ -1144,7 +1144,7 @@ async fn test_rank_endpoint() { "room": "public", "thread_tag": "langs", "delegate": "00000000-0000-0000-0000-000000000000:test:local/test", - "text": "~/rust {systems}\n~/go {concurrency}\n~/rust 3:1 ~/go {because i prefer rust for systems work}\n", + "text": "~/rust {systems}\n~/go {concurrency}\n{because i prefer rust for systems work}\n~/rust 3:1 ~/go\n", "return_rank_diff": false } }]); @@ -1178,7 +1178,7 @@ async fn test_check_endpoint_does_not_commit() { let check_batch = serde_json::json!([{ "Check": { "room": "public", - "text": "~/a {x}\n~/b {y}\n~/a 2:1 ~/b {because}\n", + "text": "~/a {x}\n~/b {y}\n{because}\n~/a 2:1 ~/b\n", } }]); let resp_body = rpc_batch(&client, addr, None, check_batch).await; @@ -1217,7 +1217,7 @@ async fn test_garden_item_pair_matchup_include_threads() { "room": "public", "thread_tag": "sorting-hat", "delegate": "00000000-0000-0000-0000-000000000000:test:local/test", - "text": "~/sorts/insertion { O(n^2) }\n~/sorts/mergesort { O(n log n) }\n~/sorts/insertion 3:1 ~/sorts/mergesort { simpler for small n }\n", + "text": "~/sorts/insertion { O(n^2) }\n~/sorts/mergesort { O(n log n) }\n{ simpler for small n }\n~/sorts/insertion 3:1 ~/sorts/mergesort\n", "return_rank_diff": false } }]); @@ -1473,7 +1473,7 @@ async fn test_rank_history() { ingest( "00000000-0000-0000-0000-000000000001:rig:test/model", - "~/hist/rust { systems }\n~/hist/python { scripting }\n~/hist/go { concurrency }\n~/hist/rust 3:1 ~/hist/python { ownership over gc }\n~/hist/rust 2:1 ~/hist/go { performance over simplicity }\n", + "~/hist/rust { systems }\n~/hist/python { scripting }\n~/hist/go { concurrency }\n{ ownership over gc }\n~/hist/rust 3:1 ~/hist/python\n{ performance over simplicity }\n~/hist/rust 2:1 ~/hist/go\n", ) .await; @@ -1506,7 +1506,7 @@ async fn test_rank_history() { ingest( "00000000-0000-0000-0000-000000000002:rig:test/model", - "~/hist/python 3:1 ~/hist/go { dynamic typing is worth it }\n", + "{ dynamic typing is worth it }\n~/hist/python 3:1 ~/hist/go\n", ) .await; @@ -1571,7 +1571,7 @@ async fn pair_returns_connectivity_stats() { "room": "public", "thread_tag": "connectivity-test", "delegate": "00000000-0000-0000-0000-000000000001:testrig:test/model", - "text": "~/conn/a { item a }\n~/conn/b { item b }\n~/conn/c { item c }\n~/conn/d { item d }\n~/conn/a 3:1 ~/conn/b { a is better }\n", + "text": "~/conn/a { item a }\n~/conn/b { item b }\n~/conn/c { item c }\n~/conn/d { item d }\n{ a is better }\n~/conn/a 3:1 ~/conn/b\n", "return_rank_diff": false } }]); @@ -1605,7 +1605,7 @@ async fn pair_returns_connectivity_stats() { "room": "public", "thread_tag": "connectivity-test", "delegate": "00000000-0000-0000-0000-000000000001:testrig:test/model", - "text": "~/conn/c 2:1 ~/conn/a { c beats a }\n", + "text": "{ c beats a }\n~/conn/c 2:1 ~/conn/a\n", "return_rank_diff": false } }]); diff --git a/test/browser_garden_pin.clj b/test/browser_garden_pin.clj index 98c086d5647207f3ac72dbb9cbc13488c030eef1..d4fa9ed60b45e872ec60e29307cfa61bcd9dd6b2 100644 --- a/test/browser_garden_pin.clj +++ b/test/browser_garden_pin.clj @@ -60,7 +60,8 @@ raw (str "# " thread-tag "\n\n" "~/gp-pin-a {alpha}\n" "~/gp-pin-b {beta}\n" - "~/gp-pin-a 2:1 ~/gp-pin-b {pin test vote}\n") + "{pin test vote}\n" + "~/gp-pin-a 2:1 ~/gp-pin-b\n") post-resp (oauth/http-post-json (str base-url "/api/v0/rpc") [{"Post" {"room" "public" diff --git a/test/browser_post_redact.clj b/test/browser_post_redact.clj index f8f5fad7c0579f57e68744647465b9dcce1d4802..bf1af0230bc7c8228f947087d4f22d51d5189a5d 100644 --- a/test/browser_post_redact.clj +++ b/test/browser_post_redact.clj @@ -60,7 +60,7 @@ raw (str "# " thread-tag "\n\n" "~/tomb-a {tomb item a}\n" "~/tomb-b {tomb item b}\n" - "~/tomb-a 2:1 ~/tomb-b {browser redact vote}\n") + "{browser redact vote}\n~/tomb-a 2:1 ~/tomb-b\n") post-resp (oauth/http-post-json (str base-url "/api/v0/rpc") [{"Post" {"room" "public" diff --git a/test/browser_public_garden.clj b/test/browser_public_garden.clj index 7bea08e1cf2c8f5b1a94b0640a46e9ba5607b19b..5dd49f1f70c870e25a2a9f5348f0bdb85647e897 100644 --- a/test/browser_public_garden.clj +++ b/test/browser_public_garden.clj @@ -51,7 +51,7 @@ "~/br-pub-a {alpha}\n" "~/br-pub-b {beta}\n" "~/br-pub-c {gamma}\n" - "~/br-pub-a 2:1 ~/br-pub-b {browser regression vote}\n") + "{browser regression vote}\n~/br-pub-a 2:1 ~/br-pub-b\n") post-resp (oauth/http-post-json (str base-url "/api/v0/rpc") [{"Post" {"room" "public" diff --git a/test/browser_redact_thread_index.clj b/test/browser_redact_thread_index.clj index 88a86fb9844fcf78df85e59f21f2e37f27df96a5..39958a85d4de10f284166f4561bc6ada2332b304 100644 --- a/test/browser_redact_thread_index.clj +++ b/test/browser_redact_thread_index.clj @@ -63,11 +63,11 @@ text-first (str "# " thread-tag "\n\n" "~/rix/a {alpha}\n" "~/rix/b {beta}\n" - "~/rix/a 2:1 ~/rix/b {browser redact thread idx post one}\n") + "{browser redact thread idx post one}\n~/rix/a 2:1 ~/rix/b\n") text-second (str "# " thread-tag "\n\n" "~/rix/c {gamma}\n" "~/rix/d {delta}\n" - "~/rix/c 2:1 ~/rix/d {browser redact thread idx post two}\n") + "{browser redact thread idx post two}\n~/rix/c 2:1 ~/rix/d\n") _ (is (true? (get-in (json/parse-string (:body (oauth/http-post-json (str base-url "/api/v0/rpc") diff --git a/test/browser_vote_compare.clj b/test/browser_vote_compare.clj index 839482d12963f130a2063f2212a6b922b2d229e1..f97a4a45e89c388f093694a1bf296f674bcb377a 100644 --- a/test/browser_vote_compare.clj +++ b/test/browser_vote_compare.clj @@ -53,7 +53,8 @@ raw (str "# " thread-tag "\n\n" "~/gp-vote-a {one}\n" "~/gp-vote-b {two}\n" - "~/gp-vote-a 1:1 ~/gp-vote-b {seed edge vote}\n") + "{seed edge vote}\n" + "~/gp-vote-a 1:1 ~/gp-vote-b\n") post-resp (oauth/http-post-json (str base-url "/api/v0/rpc") [{"Post" {"room" "public" diff --git a/test/grants.clj b/test/grants.clj index 12846c6259c2c8f0395668d49155ee22c8abfcd5..055e0a94a7fd90d58f234f643ae8998956ef9939 100644 --- a/test/grants.clj +++ b/test/grants.clj @@ -125,14 +125,15 @@ (println "\nalice posts items + vote to private room…") (is (rpc-line-ok? (:parsed (ingest! base-url alice-token room-id "main" "00000000-0000-0000-0000-000000000001:test:local/dev" - "~/fruits/apple { A crisp red apple. }\n~/fruits/banana { A yellow banana. }\n~/fruits/apple > ~/fruits/banana { apples are better }"))) + "~/fruits/apple { A crisp red apple. }\n~/fruits/banana { A yellow banana. }\n{ apples are better }\n~/fruits/apple > ~/fruits/banana"))) "alice vote in private room succeeds") ;; Bob (View + Post, no Vote) tries to vote. (println "\nbob (no Vote) tries to vote…") (is (not (rpc-line-ok? (:parsed (ingest! base-url bob-token room-id "main" "00000000-0000-0000-0000-000000000002:test:local/dev" - "~/fruits/apple > ~/fruits/banana { bob's take }")))) + "{ bob's take } +~/fruits/apple > ~/fruits/banana")))) "bob without Vote gets RPC failure") ;; Alice grants bob Vote. @@ -144,7 +145,8 @@ (println "\nbob (View + Post + Vote) votes…") (is (rpc-line-ok? (:parsed (ingest! base-url bob-token room-id "main" "00000000-0000-0000-0000-000000000002:test:local/dev" - "~/fruits/apple > ~/fruits/banana { bob's take }"))) + "{ bob's take } +~/fruits/apple > ~/fruits/banana"))) "bob with Vote succeeds")) (finally diff --git a/test/integration.clj b/test/integration.clj index 81261c7f2e0487666ef849f523fe91b2c005e6cd..5530bf9f4533f7f548e47599b5fe33f9be567309 100644 --- a/test/integration.clj +++ b/test/integration.clj @@ -39,19 +39,23 @@ "#integration-test" "" "~/languages/python { General-purpose, dynamically typed }" - "~/languages/rust { Systems language with ownership model }" - "~/languages/go { Compiled, garbage-collected, simple concurrency }" + "~/languages/rust { Systems language with ownership model }" + "~/languages/go { Compiled, garbage-collected, simple concurrency }" "" - "~/languages/rust 3:1 ~/languages/python { Rust has stronger type safety }" - "~/languages/rust 2:1 ~/languages/go { Ownership beats GC for systems work }" - "~/languages/python 2:1 ~/languages/go { Python's ecosystem is broader }"])) + "{ Rust has stronger type safety } +~/languages/rust 3:1 ~/languages/python" + "{ Ownership beats GC for systems work } +~/languages/rust 2:1 ~/languages/go" + "{ Python's ecosystem is broader } +~/languages/python 2:1 ~/languages/go"])) (def sorter-doc-2 (str/join "\n" [actor-2 "#integration-test" "" - "~/languages/go 2:1 ~/languages/python { Go deploys as a single binary, simpler ops }"])) + "{ Go deploys as a single binary, simpler ops } +~/languages/go 2:1 ~/languages/python"])) (def external-sorter-doc (str/join "\n" @@ -61,7 +65,8 @@ "-/github.com/iss/1 { issue one }" "-/github.com/iss/2 { issue two }" "" - "-/github.com/iss/1 2:1 -/github.com/iss/2 { triage order }"])) + "{ triage order } +-/github.com/iss/1 2:1 -/github.com/iss/2"])) (def check-doc-disconnected (str/join "\n" @@ -73,8 +78,10 @@ "~/disc/c { c }" "~/disc/d { d }" "" - "~/disc/a 2:1 ~/disc/b { first component }" - "~/disc/c 2:1 ~/disc/d { second component }"])) + "{ first component } +~/disc/a 2:1 ~/disc/b" + "{ second component } +~/disc/c 2:1 ~/disc/d"])) ;; --------------------------------------------------------------------------- ;; main flow (linear integration) @@ -291,8 +298,10 @@ (bind two-vote-doc (str/join "\n" ["@00000000-0000-0000-0000-000000000003:integration:local/test" "#integration-test" - "~/languages/rust 4:1 ~/languages/python { type safety }" - "~/languages/rust 3:1 ~/languages/go { zero-cost abstractions }"])) + "{ type safety } +~/languages/rust 4:1 ~/languages/python" + "{ zero-cost abstractions } +~/languages/rust 3:1 ~/languages/go"])) (bind hist-ingest (common/run-cli cli-bin base-url ["public" "forum" "post" "integration-test" "--json" "--delegate" "00000000-0000-0000-0000-000000000000:cli:local/dev"] :input two-vote-doc :extra-env token-env)) (is (zero? (:exit hist-ingest)) (str "two-vote ingest exits 0 (err: " (:err hist-ingest) ")")) diff --git a/test/walkthrough_fixture.clj b/test/walkthrough_fixture.clj index f7eb1cacca0317129e9baf68fa4f4e33356ad70f..fb7f4ee8c996e7b4ffb55e225f73f3266feda220 100644 --- a/test/walkthrough_fixture.clj +++ b/test/walkthrough_fixture.clj @@ -49,7 +49,7 @@ "capabilities" ["view" "post" "vote" "add_item"]}}])) (let [wall-text (str "Walkthrough seed — multi-paragraph stress test.\n\n" "Second paragraph: the garden holds ~/secret/item and ~/secret/other. " - "Votes like ~/secret/item 3:1 ~/secret/other {because} should still parse.\n\n" + "Votes like {because}\\n~/secret/item 3:1 ~/secret/other should parse.\n\n" "Third block: lorem-style filler so wrapping and vertical rhythm are obvious. " "We want enough prose that the thread view scrolls and pre blocks show overflow " "behavior (long lines, slug links, embed URLs) without looking like toy data.\n\n" @@ -58,7 +58,7 @@ "https://open.spotify.com/track/4iV5W9uYEdYUVa79Axb7U9 https://www.youtube.com/watch?v=dQw4w9WgXcQ\n\n" "~/secret/item {classified}\n" "~/secret/other {secondary}\n" - "~/secret/item 3:1 ~/secret/other {because}\n") + "{because}\n~/secret/item 3:1 ~/secret/other\n") rpc (json/generate-string {:action "post_ingest" :room room-id Side B — contributor: tommy-mor Side B — commit message: [7caef802] room ui wired up again Side B — unified diff (full patch): diff --git a/Cargo.lock b/Cargo.lock index e31485f28717993a13e1c4caf7be15b43a97573e..8be6ff8677700ce0a56d4a53b221e25c2bb70507 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -158,6 +158,7 @@ dependencies = [ "axum", "axum-core", "bytes", + "cookie", "fastrand", "futures-util", "http", @@ -300,6 +301,17 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" +[[package]] +name = "cookie" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747" +dependencies = [ + "percent-encoding", + "time", + "version_check", +] + [[package]] name = "core-foundation" version = "0.9.4" diff --git a/plan2.md b/plan2.md new file mode 100644 index 0000000000000000000000000000000000000000..1587cbe558eb0a98fbce78566bf5f93b18100e54 --- /dev/null +++ b/plan2.md @@ -0,0 +1,190 @@ +This is a phenomenal synthesis. You stripped away the exact parts of `evaleval` that don't scale to a multi-tenant web application (string-splicing `eval` and in-memory nonce OCAP tracking) and kept the parts that make development lightning fast (embedded declarative payloads, single endpoint routing, and Javascript AST responses). + +You are entirely right about the **AST substitution in Rust**. Walking a `serde_json::Value` tree to find `{"$form": "field_name"}` and swapping the node for a String isn't a hack—in Rust, it’s just a completely standard recursive enum visitor. + +Let’s lock in this exact architecture. It is cohesive, secure, and incredibly ergonomic. + +Here is what the code actually looks like to execute this vision. + +--- + +### 1. The Safe AST Substitution + +This is the exact function that runs in the Web handler before giving the payload to the RPC engine. Because it operates on the JSON AST *before* deserialization, it's 100% immune to injection. + +```rust +use serde_json::Value; +use std::collections::HashMap; + +/// Recursively walk the JSON AST and replace {"$form": "key"} with the actual form string. +fn substitute_form_vars(val: &mut Value, form_data: &HashMap) { + match val { + Value::Object(map) => { + // Is this the magic placeholder node? {"$form": "input_name"} + if map.len() == 1 && map.contains_key("$form") { + if let Some(field_name) = map.get("$form").and_then(|v| v.as_str()) { + let submitted_text = form_data.get(field_name).map(|s| s.as_str()).unwrap_or(""); + *val = Value::String(submitted_text.to_string()); + return; + } + } + // Otherwise, keep walking the object + for v in map.values_mut() { + substitute_form_vars(v, form_data); + } + } + Value::Array(arr) => { + // Walk arrays + for v in arr.iter_mut() { + substitute_form_vars(v, form_data); + } + } + _ => {} // Primitives stay as is + } +} +``` +**Why this rules:** You can write a single, hidden HTML input: +`` +When the form submits, the backend safely turns it into standard RPC input. + +--- + +### 2. The Unified Core RPC Layer + +You keep exactly one execution layer that strictly enforces your domain constraints (ACLs). Whether the command originated from a CLI script or a web form, they all hit this choke point: + +```rust +// Core execute function, decoupled from HTTP +pub async fn execute_rpc( + state: &ReducerState, + principal: &Principal, + command: RpcCommand +) -> Result { + match command { + RpcCommand::Ingest { space, text } => { + // ACLs are checked RIGHT HERE, universally. + if !state.user_has_cap(&space, principal, ThreadCapability::Post) { + return Err(ApiError::Forbidden("No post access in this space".to_string())); + } + // Do the write, apply events... + Ok(RpcResponse::IngestOk { ... }) + } + // ... + } +} +``` + +--- + +### 3. The `DomPatch` Builder Pattern + +You prefer the Builder pattern over a macro for the response mapping. I agree—builders are far easier for your IDE to autocomplete, and easier to compose dynamically (e.g., iterating over a list of items to append). + +```rust +pub struct DomPatch { + js: String, +} + +impl DomPatch { + pub fn new() -> Self { + Self { js: String::new() } + } + + /// Morphs an element using Idiomorph + pub fn morph(mut self, selector: &str, html: &str) -> Self { + let safe_html = serde_json::to_string(html).expect("string escaping failed"); + self.js.push_str(&format!( + "Idiomorph.morph(document.querySelector('{}'), {}, {{morphStyle: 'innerHTML'}});\n", + selector, safe_html + )); + self + } + + /// Appends raw HTML to an element + pub fn append(mut self, selector: &str, html: &str) -> Self { + let safe_html = serde_json::to_string(html).unwrap(); + self.js.push_str(&format!( + "document.querySelector('{}')?.insertAdjacentHTML('beforeend', {});\n", + selector, safe_html + )); + self + } + + /// Executes raw javascript + pub fn eval(mut self, code: &str) -> Self { + self.js.push_str(code); + self.js.push('\n'); + self + } + + /// Consumes the builder into an HTTP Response with the right content-type + pub fn into_response(self) -> impl axum::response::IntoResponse { + ( + axum::http::StatusCode::OK, + [(axum::http::header::CONTENT_TYPE, "text/javascript")], + self.js + ) + } +} +``` + +--- + +### 4. The Single Web Handler (`POST /ui/action`) + +With the pipeline defined, you only ever have to write **one** `POST` handler for the entire Web UI. + +```rust +pub async fn handle_web_action( + State(state): State, + headers: HeaderMap, + Form(form_data): Form>, // Captures everything dynamically +) -> impl IntoResponse { + // 1. Authenticate using Bearer / Cookie exactly like the CLI + let principal = match extract_web_session(&headers, &state) { + Ok(p) => p, + Err(_) => return DomPatch::new().eval("window.location = '/auth/login';").into_response(), + }; + + // 2. Decode the Base64 JSON + let b64 = form_data.get("__rpc__").expect("Missing RPC payload in form"); + let decoded = base64::decode(b64).expect("Bad b64"); + let mut json_ast: Value = serde_json::from_slice(&decoded).expect("Bad JSON"); + + // 3. Do AST Substitution! + substitute_form_vars(&mut json_ast, &form_data); + + // 4. Parse it strongly into the RPC enum + let command: RpcCommand = serde_json::from_value(json_ast).expect("Invalid RpcCommand"); + + // 5. Pass it to the core execute function (authz + mutation happens here) + match execute_rpc(&state.reduced.read().await, &principal, command).await { + Ok(RpcResponse::IngestOk { new_ranks }) => { + // Translate the RpcResponse to UI JS snippets + DomPatch::new() + .morph("#rank-container", &render_ranking(&new_ranks)) + .eval("document.getElementById('ingest-form').reset();") + .into_response() + } + Ok(_) => DomPatch::new().eval("console.log('Action complete');").into_response(), + Err(e) => { + // Reconcile errors + DomPatch::new() + .morph("#error-banner", &format!("
{}
", e.message())) + .into_response() + } + } +} +``` + +### The Verdict on the Grand Architecture + +By combining: +1. The **Domain-Driven Asymmetry** (Spaces contain Gardens & Threads) +2. The **Core RPC Logic** (1 executor, `Vec`, strict ACL checks) +3. The **Single Web Form Controller** (b64 embedded, `substitute_form_vars()`) +4. The **Javascript DomPatch Builder** + +You have constructed an application architecture that gives you absolute security and data integrity for your CLI AI Agents, while keeping the absolute peak hackability, form simplicity, and lightning-fast JS UI diffing of your `evaleval` Python framework. + +I'm sold. It is clean, it is uniquely fitted to the mechanics of Rust (`serde`, `enums`), and it solves the URL routing fatigue problem beautifully. This is the exact way to build `slug.social` v2. \ No newline at end of file diff --git a/server/Cargo.toml b/server/Cargo.toml index d527f86532c2856e29f9c6265e54c7235fdf0a8c..18c45777d662b71dc309e1daa4ddb2944da9759d 100644 --- a/server/Cargo.toml +++ b/server/Cargo.toml @@ -6,7 +6,7 @@ license = "MIT" [dependencies] axum = { version = "0.7", features = ["macros"] } -axum-extra = { version = "0.9", features = ["query"] } +axum-extra = { version = "0.9", features = ["query", "cookie"] } bytes = "1.11.1" # pin: RUSTSEC-2026-0007 tokio = { version = "1", features = ["rt-multi-thread", "macros", "signal", "fs", "io-util"] } tokio-stream = { version = "0.1", features = ["sync"] } diff --git a/server/src/api/auth.rs b/server/src/api/auth.rs index b45ba39419c84af8bf2333fc9b7d47e98525c45f..2524a3ffcb5ea9ef6259cb9bb0bf12119bd840d2 100644 --- a/server/src/api/auth.rs +++ b/server/src/api/auth.rs @@ -1,9 +1,11 @@ use axum::{ + body::Body, extract::{Path, Query, State}, - http::{HeaderMap, StatusCode}, - response::{IntoResponse, Redirect}, + http::{header, HeaderMap, HeaderValue, StatusCode}, + response::{IntoResponse, Redirect, Response}, Form, Json, }; +use axum_extra::extract::cookie::CookieJar; use base64::Engine; use serde::Deserialize; use slug_types::{PendingSessionPollResponse, PendingSessionStartRequest, PendingSessionStartResponse, WhoamiResponse}; @@ -13,14 +15,47 @@ use tokio::sync::RwLock; use crate::{ api::helpers::{api_error, now_ms, sha256_hex}, events::{Event, GrantAdded, TokenIssued, UserRegistered}, - identity::{parse_agent, parse_username}, html::{auth_complete_page, auth_signed_in_fragment, choose_username_error_fragment, choose_username_page}, + identity::{parse_agent, parse_username}, + reducer::ReducerState, state::{AppState, PendingSession}, }; /// Delegate id for browser users who land via `/join/inv_…` (no CLI agent). const INVITE_BROWSER_AGENT: &str = "00000000-0000-0000-0000-000000000000:invite:web/join"; +/// Agent id for `/login` browser OAuth (no CLI); must pass [`parse_agent`]. +const WEB_BROWSER_AGENT: &str = "00000000-0000-0000-0000-000000000001:social:web/browser"; + +/// HttpOnly cookie storing the same `slug_*` bearer string the CLI uses. +pub const SLUG_SESSION_COOKIE: &str = "slug_session"; + +/// `Set-Cookie` header value (full attribute string). +pub fn session_cookie_header_value(bearer: &str) -> HeaderValue { + let s = format!( + "{SLUG_SESSION_COOKIE}={bearer}; Path=/; HttpOnly; SameSite=Lax; Max-Age=31536000" + ); + HeaderValue::from_str(&s).expect("session cookie value must be ASCII") +} + +/// Resolve the signed-in username from `Authorization: Bearer` or `slug_session` cookie. +pub fn optional_principal(headers: &HeaderMap, jar: &CookieJar, reduced: &ReducerState) -> Option { + if let Ok(u) = verify_bearer_principal(headers, reduced) { + return Some(u); + } + let c = jar.get(SLUG_SESSION_COOKIE)?; + verify_token(reduced, c.value()).ok() +} + +fn redirect_with_session_cookie(public_url: &str, path_and_query: &str, bearer: &str) -> Response { + Response::builder() + .status(StatusCode::TEMPORARY_REDIRECT) + .header(header::LOCATION, format!("{public_url}{path_and_query}")) + .header(header::SET_COOKIE, session_cookie_header_value(bearer)) + .body(Body::empty()) + .unwrap() +} + async fn apply_invite_redemption(state: &AppState, invite_token: &str, grantee_username: &str) -> Result<(), String> { let now = now_ms(); let ga = { @@ -306,8 +341,9 @@ pub async fn get_auth_callback(Query(q): Query, State(state): tracing::warn!(error = %e, "invite redemption skipped after oauth"); } } + let cookie_bearer = bearer.clone(); s.complete = Some((username, bearer)); - return Redirect::temporary(&format!("{public_url}/auth/complete")).into_response(); + return redirect_with_session_cookie(&public_url, "/", &cookie_bearer).into_response(); } } @@ -418,7 +454,47 @@ pub async fn post_choose_username( s.complete = Some((canon_user.clone(), bearer.clone())); } - auth_signed_in_fragment().into_response() + Response::builder() + .status(StatusCode::OK) + .header(header::CONTENT_TYPE, "text/html; charset=utf-8") + .header(header::SET_COOKIE, session_cookie_header_value(&bearer)) + .body(Body::from(auth_signed_in_fragment().into_string())) + .unwrap() + .into_response() +} + +/// Start a browser-only OAuth flow (no CLI polling). Sets session cookie on success. +pub async fn get_web_login(State(state): State) -> impl IntoResponse { + let session = format!("p_{}", uuid::Uuid::new_v4().simple()); + let s = PendingSession { + agent: WEB_BROWSER_AGENT.to_string(), + created_ts: now_ms(), + provider: None, + provider_id: None, + redeem_invite: None, + complete: None, + }; + state.pending_sessions.write().await.insert(session.clone(), s); + let public_url = std::env::var("SLUG_PUBLIC_URL").unwrap_or_else(|_| "http://127.0.0.1:8080".to_string()); + Redirect::temporary(&format!( + "{public_url}/auth/login?session={}", + urlencoding::encode(&session) + )) + .into_response() +} + +pub async fn get_logout() -> impl IntoResponse { + let clear = format!("{SLUG_SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0"); + Response::builder() + .status(StatusCode::TEMPORARY_REDIRECT) + .header(header::LOCATION, "/") + .header( + header::SET_COOKIE, + HeaderValue::from_str(&clear).expect("static cookie clears"), + ) + .body(Body::empty()) + .unwrap() + .into_response() } pub async fn post_pending_session( diff --git a/server/src/api/mod.rs b/server/src/api/mod.rs index cb031aecebad1107dfa2898a98fb6084b28ba6e9..5320345a33bbb7b5ab769696a31f70347d019c3e 100644 --- a/server/src/api/mod.rs +++ b/server/src/api/mod.rs @@ -1,7 +1,9 @@ mod auth; mod helpers; mod rpc; +mod stream; mod validate; +mod web_post; pub use auth::{ get_join_invite, @@ -13,6 +15,11 @@ pub use auth::{ get_auth_callback, get_auth_complete, get_choose_username, + get_web_login, + get_logout, + optional_principal, + session_cookie_header_value, + SLUG_SESSION_COOKIE, }; pub use helpers::{ @@ -23,8 +30,12 @@ pub use helpers::{ pub use rpc::handle_rpc_batch; +pub use stream::{get_html_stream, get_stream}; + pub use validate::{normalize_room_and_thread, validate_ingest_document, ValidatedIngest}; +pub use web_post::post_web_ingest; + #[cfg(test)] mod tests { use super::*; diff --git a/server/src/api/rpc.rs b/server/src/api/rpc.rs index 7d384e938a526bdf6aa04d1bf21a54d3fcb57d7e..231bf7381cf804144efd0521970b72dd8ffd4213 100644 --- a/server/src/api/rpc.rs +++ b/server/src/api/rpc.rs @@ -407,6 +407,22 @@ async fn rpc_post( }) } +/// Post forum content using a raw bearer token (CLI `Authorization` header or browser session cookie). +pub async fn rpc_post_with_bearer( + state: &AppState, + bearer_token: &str, + room: String, + thread_tag: String, + text: String, +) -> Result { + use axum::http::{header, HeaderMap, HeaderValue}; + let mut headers = HeaderMap::new(); + let hv = HeaderValue::from_str(&format!("Bearer {bearer_token}")) + .map_err(|_| ("invalid session token".into(), None))?; + headers.insert(header::AUTHORIZATION, hv); + rpc_post(state, &headers, room, thread_tag, None, text, false).await +} + async fn rpc_check( state: &AppState, _room: String, diff --git a/server/src/api/web_post.rs b/server/src/api/web_post.rs new file mode 100644 index 0000000000000000000000000000000000000000..d7a5780c02281a60d29f27d17b291d6df5580606 --- /dev/null +++ b/server/src/api/web_post.rs @@ -0,0 +1,107 @@ +use axum::{ + extract::State, + http::{HeaderMap, StatusCode}, + response::{Html, IntoResponse, Redirect}, + Form, +}; +use axum_extra::extract::cookie::CookieJar; +use serde::Deserialize; +use slug_types::RpcResult; + +use crate::{ + api::{ + auth::{optional_principal, SLUG_SESSION_COOKIE}, + rpc::rpc_post_with_bearer, + }, + canonical_path::canonicalize_tag, + html::layout, + state::AppState, +}; + +#[derive(Debug, Deserialize)] +pub struct WebPostForm { + pub room: String, + pub thread_tag: String, + pub text: String, +} + +fn post_redirect_location(room: &str, thread_tag: &str) -> String { + let tag = canonicalize_tag(thread_tag); + if room.trim() == "public" { + format!("/t/{tag}") + } else { + let room = room.trim(); + let Some((a, b)) = room.split_once('/') else { + return "/".to_string(); + }; + format!("/r/{a}/{b}/{tag}") + } +} + +pub async fn post_web_ingest( + State(state): State, + headers: HeaderMap, + jar: CookieJar, + Form(form): Form, +) -> impl IntoResponse { + let reduced = state.reduced.read().await; + let Some(username) = optional_principal(&headers, &jar, &reduced) else { + drop(reduced); + return Redirect::temporary("/login").into_response(); + }; + + let bearer = headers + .get(axum::http::header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .and_then(|s| s.strip_prefix("Bearer ").map(|t| t.trim().to_string())) + .or_else(|| jar.get(SLUG_SESSION_COOKIE).map(|c| c.value().to_string())); + + drop(reduced); + + let Some(bearer) = bearer else { + return Redirect::temporary("/login").into_response(); + }; + + let room = form.room.trim().to_string(); + let thread_tag = form.thread_tag.trim().to_string(); + let text = form.text.clone(); + + if text.trim().is_empty() { + return error_page( + "empty post", + "Write something in the text area (DSL / prose).", + &username, + ) + .into_response(); + } + + match rpc_post_with_bearer(&state, &bearer, room.clone(), thread_tag.clone(), text).await { + Ok(RpcResult::PostOk { .. }) => { + Redirect::to(&post_redirect_location(&room, &thread_tag)).into_response() + } + Ok(_) => error_page("unexpected response", "Post did not return PostOk.", &username).into_response(), + Err((msg, hint)) => error_page( + &msg, + hint.as_deref().unwrap_or(""), + &username, + ) + .into_response(), + } +} + +fn error_page(title: &str, detail: &str, user: &str) -> impl IntoResponse { + use maud::html; + let body = html! { + nav class="breadcrumb" { + a href="/" { "slug.social" } + } + h1 { "could not post" } + p { (title) } + @if !detail.is_empty() { + pre class="muted" { (detail) } + } + p class="muted" { "signed in as @" (user) " · " a href="/" { "home" } } + }; + let page = layout("post error — slug.social", "view-thread", body, None); + (StatusCode::BAD_REQUEST, Html(page.into_string())) +} diff --git a/server/src/html/forum.rs b/server/src/html/forum.rs index 228a120065dbacd8a308ba6e8bfc6ab111877c4b..8dfcd6b23a18e1571c4f0b3b60c865fa8f576f2f 100644 --- a/server/src/html/forum.rs +++ b/server/src/html/forum.rs @@ -1,21 +1,24 @@ use axum::{ extract::{Path, Query, State}, - http::{header, StatusCode}, + http::{header, HeaderMap, StatusCode}, response::{Html, IntoResponse, Response}, }; -use serde::Deserialize; +use axum_extra::extract::cookie::CookieJar; use maud::{html, Markup}; +use serde::Deserialize; use crate::{ + api::optional_principal, canonical_path::canonicalize_tag, + events::ThreadCapability, reducer::{ReducerState, ScopeId}, state::AppState, timeago, }; use super::{ - authorship_address, bc_threads, cli_panel, layout, now_ms, - recency_class, render_linkified_with_embeds, + authorship_address, bc_segment, bc_threads, cli_panel, layout, now_ms, recency_class, + render_linkified_with_embeds, }; #[derive(Clone)] @@ -26,17 +29,72 @@ struct ThreadRow { ingests: usize, } -/// Collect thread rows from reducer state (unsorted). -fn collect_thread_rows(reduced: &ReducerState, now: i64) -> Vec { +/// URL prefix for thread pages: public `/t/…` or room `/r/{short}/{slug}/…`. +#[derive(Clone)] +pub struct ThreadNav { + pub room_wire: String, + scope: ScopeId, + path_prefix: String, +} + +impl ThreadNav { + pub fn public() -> Self { + Self { + room_wire: "public".into(), + scope: ScopeId::Public, + path_prefix: "/t".into(), + } + } + + /// `room_id` wire form `shortid/slug`. + pub fn from_room_id(room_id: &str) -> Option { + let (short, slug) = room_id.split_once('/')?; + if short.is_empty() || slug.is_empty() { + return None; + } + Some(Self { + room_wire: room_id.to_string(), + scope: ScopeId::Room(room_id.to_string()), + path_prefix: format!("/r/{short}/{slug}"), + }) + } + + fn scope(&self) -> ScopeId { + self.scope.clone() + } + + fn thread_url(&self, tag: &str) -> String { + format!("{}/{}", self.path_prefix, tag) + } + + fn thread_page_url(&self, tag: &str, offset: usize) -> String { + let base = self.thread_url(tag); + if offset == 0 { + base + } else { + format!("{base}?offset={offset}") + } + } + + fn post_url(&self, tag: &str, idx: usize) -> String { + format!("{}/{}/{}", self.path_prefix, tag, idx) + } + + fn expand_url(&self, tag: &str, idx: usize) -> String { + format!("{}/{}/{}/expand", self.path_prefix, tag, idx) + } +} + +fn collect_thread_rows_for_scope(reduced: &ReducerState, scope: &ScopeId, now: i64) -> Vec { let _ = now; reduced .forum_threads .iter() - .filter(|((scope, _), _)| scope == &ScopeId::Public) + .filter(|((s, _), _)| s == scope) .map(|((_, tag), thread)| { let ingests = reduced .ingests_by_scope_thread - .get(&(ScopeId::Public, tag.clone())) + .get(&(scope.clone(), tag.clone())) .map(|q| q.len()) .unwrap_or(0); ThreadRow { @@ -49,16 +107,46 @@ fn collect_thread_rows(reduced: &ReducerState, now: i64) -> Vec { .collect() } -/// Render the thread feed div (id="thread-feed"). Used by both index() and SSE broadcast. -fn render_thread_feed(rows: &[ThreadRow], now: i64) -> Markup { +fn rooms_for_user(reduced: &ReducerState, username: &str) -> Vec { + let mut v: Vec = reduced + .grants + .iter() + .filter(|(rid, m)| reduced.rooms.contains(*rid) && m.contains_key(username)) + .map(|(rid, _)| rid.clone()) + .collect(); + v.sort(); + v +} + +fn user_can_view_room(reduced: &ReducerState, room_id: &str, username: Option<&str>) -> bool { + if !reduced.rooms.contains(room_id) { + return false; + } + let Some(u) = username else { + return false; + }; + reduced.user_has_cap(room_id, u, ThreadCapability::View) + || reduced.user_has_cap(room_id, u, ThreadCapability::Post) + || reduced.user_has_cap(room_id, u, ThreadCapability::Manage) +} + +fn user_can_post_room(reduced: &ReducerState, room_id: &str, username: &str) -> bool { + reduced.user_has_cap(room_id, username, ThreadCapability::Post) +} + +/// `feed_id` is e.g. `thread-feed` (public bump list, SSE) or `room-thread-feed`. +fn render_thread_feed(nav: Option<&ThreadNav>, feed_id: &str, rows: &[ThreadRow], now: i64) -> Markup { html! { - div id="thread-feed" { + div id=(feed_id) { @if rows.is_empty() { p class="muted" { "no threads yet" } } @else { ul class="thread-feed" { @for r in rows { - @let thread_href = format!("/t/{}", r.tag); + @let thread_href = nav + .as_ref() + .map(|n| n.thread_url(&r.tag)) + .unwrap_or_else(|| format!("/t/{}", r.tag)); @let hover = timeago::rfc3339_utc(r.last_ts); @let ago = timeago::timeago(now, r.last_ts); @let age_cls = recency_class(now, r.last_ts); @@ -83,36 +171,148 @@ fn render_thread_feed(rows: &[ThreadRow], now: i64) -> Markup { } } +fn auth_strip( + headers: &HeaderMap, + jar: &CookieJar, + reduced: &ReducerState, +) -> Markup { + match optional_principal(headers, jar, reduced) { + Some(u) => html! { + p class="muted auth-strip" { + "@" (u) + " · " + a href="/logout" { "log out" } + } + }, + None => html! { + p class="muted auth-strip" { + a href="/login" { "log in" } + } + }, + } +} + +fn bc_room(nav: &ThreadNav, room_slug: &str, thread_tag: Option<&str>) -> Markup { + html! { + a href="/" { "slug.social" } + @if let Some(t) = thread_tag { + (bc_segment( + &format!("r / {room_slug}"), + &nav.path_prefix, + false, + )) + (bc_segment(&format!("#{t}"), &nav.thread_url(t), true)) + } @else { + (bc_segment( + &format!("r / {room_slug}"), + &nav.path_prefix, + true, + )) + } + } +} + +fn compose_form(nav: &ThreadNav, thread_tag: &str, show: bool) -> Markup { + if !show { + return html! {}; + } + html! { + section class="compose" { + h3 { "reply" } + p class="muted" { "Uses the same ingest DSL as the CLI. You must be logged in." } + form method="POST" action="/post" { + input type="hidden" name="room" value=(nav.room_wire.clone()); + input type="hidden" name="thread_tag" value=(thread_tag); + textarea name="text" rows="8" cols="80" placeholder="prose or ~/items and votes…" {} + p { + button type="submit" { "post" } + } + } + } + } +} + +fn new_thread_form_public(show: bool) -> Markup { + if !show { + return html! {}; + } + html! { + section class="compose" { + h3 { "new public thread" } + p class="muted" { "Set thread tag and body. Example: start with a title line or use the CLI-shaped DSL." } + form method="POST" action="/post" { + input type="hidden" name="room" value="public"; + label for="new-thread-tag" { "thread tag" } + input type="text" id="new-thread-tag" name="thread_tag" pattern="[a-z0-9_\\-]{1,64}" placeholder="my-topic"; + label for="new-thread-text" { "text" } + textarea id="new-thread-text" name="text" rows="6" placeholder="#my-topic\n\nYour first post…" {} + p { button type="submit" { "create / post" } } + } + } + } +} -/// Returns the current thread feed HTML fragment for SSE broadcast. -/// selector: `#thread-feed` +/// Returns the current public thread feed HTML fragment for SSE (`#thread-feed`). pub async fn thread_feed_html(state: &AppState) -> String { let now = now_ms(); + let nav = ThreadNav::public(); let mut rows = { let reduced = state.reduced.read().await; - collect_thread_rows(&reduced, now) + collect_thread_rows_for_scope(&reduced, &ScopeId::Public, now) }; rows.sort_by(|a, b| b.last_ts.cmp(&a.last_ts)); - render_thread_feed(&rows, now).into_string() + render_thread_feed(Some(&nav), "thread-feed", &rows, now).into_string() } -pub async fn index(State(state): State) -> impl IntoResponse { +/// Home: private rooms (signed-in), then public bump-ordered threads. +pub async fn home( + State(state): State, + headers: HeaderMap, + jar: CookieJar, +) -> impl IntoResponse { let now = now_ms(); - let mut rows: Vec = { - let reduced = state.reduced.read().await; - collect_thread_rows(&reduced, now) - }; - // Bump order: most recently active first. - rows.sort_by(|a, b| b.last_ts.cmp(&a.last_ts)); + let reduced = state.reduced.read().await; + let user = optional_principal(&headers, &jar, &reduced); + let room_ids = user + .as_ref() + .map(|u| rooms_for_user(&reduced, u)) + .unwrap_or_default(); + let mut public_rows = collect_thread_rows_for_scope(&reduced, &ScopeId::Public, now); + drop(reduced); + public_rows.sort_by(|a, b| b.last_ts.cmp(&a.last_ts)); + + let nav = ThreadNav::public(); + let reduced_read = state.reduced.read().await; + let strip = auth_strip(&headers, &jar, &reduced_read); + let show_forms = user.is_some(); + drop(reduced_read); let page = layout( "slug.social", "view-thread", html! { + (strip) nav class="breadcrumb" { (bc_threads(None)) } + @if !room_ids.is_empty() { + h2 { "your rooms" } + ul class="thread-feed" { + @for rid in &room_ids { + @if let Some(nav_r) = ThreadNav::from_room_id(rid) { + @let slug = if let Some((_, s)) = rid.split_once('/') { s } else { rid.as_str() }; + li { + a href=(nav_r.path_prefix) { + (slug) + span class="muted" { " · " (rid) } + } + } + } + } + } + } + h2 { "public threads" } p class="muted" { "dark = time-ordered · light = vote-ranked" } - h2 { "threads" } - (render_thread_feed(&rows, now)) + (render_thread_feed(Some(&nav), "thread-feed", &public_rows, now)) + (new_thread_form_public(show_forms)) (cli_panel("npx slugsocial forum")) }, None, @@ -127,9 +327,13 @@ pub struct ThreadViewQuery { const PAGE_SIZE: usize = 10; -fn render_thread_paginator(tag: &str, offset: usize, total: usize, top: bool) -> Markup { +fn render_thread_paginator(nav: &ThreadNav, tag: &str, offset: usize, total: usize, top: bool) -> Markup { let newer_offset = offset.checked_add(PAGE_SIZE).filter(|&o| o < total); - let older_offset = if offset > 0 { Some(offset.saturating_sub(PAGE_SIZE)) } else { None }; + let older_offset = if offset > 0 { + Some(offset.saturating_sub(PAGE_SIZE)) + } else { + None + }; let latest_offset = total.saturating_sub(PAGE_SIZE); let on_latest = offset >= latest_offset; let (id, scroll_href, scroll_label) = if top { @@ -141,7 +345,7 @@ fn render_thread_paginator(tag: &str, offset: usize, total: usize, top: bool) -> div class="thread-paginator" id=(id) { a href=(scroll_href) class="post-nav-btn" { (scroll_label) } @if let Some(o) = older_offset { - a href=(format!("/t/{tag}?offset={o}")) class="post-nav-btn" { "← older" } + a href=(nav.thread_page_url(tag, o)) class="post-nav-btn" { "← older" } } @else { span class="post-nav-btn disabled" { "← older" } } @@ -149,37 +353,38 @@ fn render_thread_paginator(tag: &str, offset: usize, total: usize, top: bool) -> (offset + 1) "–" (total.min(offset + PAGE_SIZE)) " / " (total) } @if let Some(o) = newer_offset { - a href=(format!("/t/{tag}?offset={o}")) class="post-nav-btn" { "newer →" } + a href=(nav.thread_page_url(tag, o)) class="post-nav-btn" { "newer →" } } @else { span class="post-nav-btn disabled" { "newer →" } } @if !on_latest { - a href=(format!("/t/{tag}?offset={latest_offset}")) class="post-nav-btn" { "latest" } + a href=(nav.thread_page_url(tag, latest_offset)) class="post-nav-btn" { "latest" } } } } } -/// Thread view — `/t/:tag` — dark, paginated. -pub async fn thread_view( - State(state): State, - Path(tag): Path, - Query(q): Query, +async fn thread_view_inner( + state: AppState, + tag: String, + q: ThreadViewQuery, + nav: ThreadNav, + headers: HeaderMap, + jar: CookieJar, ) -> impl IntoResponse { let tag = canonicalize_tag(&tag); + let scope = nav.scope(); - // Newest-first queue → chronological for the page. let all_ids: Vec = { let reduced = state.reduced.read().await; reduced .ingests_by_scope_thread - .get(&(ScopeId::Public, tag.clone())) + .get(&(scope.clone(), tag.clone())) .map(|q| q.iter().rev().cloned().collect()) .unwrap_or_default() }; let total = all_ids.len(); - // Default: first page (oldest posts first, like a book). let offset = q.offset.unwrap_or(0); let page_ids: Vec = all_ids.into_iter().skip(offset).take(PAGE_SIZE).collect(); @@ -189,18 +394,49 @@ pub async fn thread_view( .iter() .filter_map(|id| reduced.ingests_by_id.get(id).cloned()) .collect::>(); - let subtitle: Option = None; - (ingests, subtitle) + (ingests, None::) + }; + + let reduced = state.reduced.read().await; + let user = optional_principal(&headers, &jar, &reduced); + let sc = nav.scope(); + let show_compose = match &sc { + ScopeId::Public => user.is_some(), + ScopeId::Room(rid) => user + .as_ref() + .map(|u| user_can_post_room(&reduced, rid, u)) + .unwrap_or(false), }; + let strip = auth_strip(&headers, &jar, &reduced); + drop(reduced); let now = now_ms(); - let paginator_top = render_thread_paginator(&tag, offset, total, true); - let paginator_bot = render_thread_paginator(&tag, offset, total, false); + let paginator_top = render_thread_paginator(&nav, &tag, offset, total, true); + let paginator_bot = render_thread_paginator(&nav, &tag, offset, total, false); + + let bc: Markup = match &sc { + ScopeId::Public => bc_threads(Some(&tag)), + ScopeId::Room(rid) => { + let slug = if let Some((_, s)) = rid.split_once('/') { + s + } else { + rid.as_str() + }; + bc_room(&nav, slug, Some(&tag)) + } + }; + + let cli = match &sc { + ScopeId::Public => format!("npx slugsocial forum {tag}"), + ScopeId::Room(r) => format!("npx slugsocial private {r} forum {tag}"), + }; + let page = layout( &format!("#{tag}"), "view-thread", html! { - nav class="breadcrumb" { (bc_threads(Some(&tag))) } + (strip) + nav class="breadcrumb" { (bc) } h2 { "#" (tag) @if let Some(sub) = &subtitle { ": " (sub) } } p class="muted" { "top=oldest · bottom=newest" } @if display_ingests.is_empty() { @@ -209,7 +445,7 @@ pub async fn thread_view( (paginator_top) @for (i, ing) in display_ingests.iter().enumerate() { @let post_idx = offset + i; - @let post_href = format!("/t/{tag}/{post_idx}"); + @let post_href = nav.post_url(&tag, post_idx); @let hover = timeago::rfc3339_utc(ing.ts); @let ago = timeago::timeago(now, ing.ts); @let truncated = ing.raw.len() > 2000; @@ -222,8 +458,9 @@ pub async fn thread_view( } (render_linkified_with_embeds(display_body)) @if truncated { + @let exp = nav.expand_url(&tag, post_idx); a href="#" class="show-full-link" - onclick=(format!("fetch('/t/{tag}/{post_idx}/expand').then(r=>r.text()).then(eval);return false")) { + onclick=(format!("fetch('{exp}').then(r=>r.text()).then(eval);return false")) { "[show full post]" } } @@ -231,34 +468,171 @@ pub async fn thread_view( } (paginator_bot) } - (cli_panel(&format!("npx slugsocial forum {tag}"))) + (compose_form(&nav, &tag, show_compose)) + (cli_panel(&cli)) }, None, ); Html(page.into_string()).into_response() } -/// Single-post view — `/t/:tag/:index` — shows one ingest at full length. -pub async fn thread_post_view( +/// Thread view — `/t/:tag` +pub async fn thread_view( State(state): State, - Path((tag, index_str)): Path<(String, String)>, + Path(tag): Path, + Query(q): Query, + headers: HeaderMap, + jar: CookieJar, ) -> impl IntoResponse { - let tag = canonicalize_tag(&tag); + thread_view_inner(state, tag, q, ThreadNav::public(), headers, jar).await +} + +/// Room thread — `/r/:short/:slug/:tag` +pub async fn room_thread_view( + State(state): State, + Path((room_short, room_slug, tag)): Path<(String, String, String)>, + Query(q): Query, + headers: HeaderMap, + jar: CookieJar, +) -> impl IntoResponse { + let room_id = format!("{room_short}/{room_slug}"); + let reduced = state.reduced.read().await; + let user = optional_principal(&headers, &jar, &reduced); + if !user_can_view_room(&reduced, &room_id, user.as_deref()) { + drop(reduced); + return room_forbidden_page().into_response(); + } + drop(reduced); + let Some(nav) = ThreadNav::from_room_id(&room_id) else { + return (StatusCode::NOT_FOUND, "bad room path").into_response(); + }; + thread_view_inner(state, tag, q, nav, headers, jar) + .await + .into_response() +} + +fn room_forbidden_page() -> impl IntoResponse { + let body = html! { + nav class="breadcrumb" { a href="/" { "slug.social" } } + h1 { "private room" } + p { "Log in with an account that has been granted access to this room." } + p { a href="/login" { "log in" } " · " a href="/" { "home" } } + }; + let page = layout("private room — slug.social", "view-thread", body, None); + (StatusCode::FORBIDDEN, Html(page.into_string())) +} + +/// Private room index — `/r/:short/:slug` +pub async fn room_page( + State(state): State, + Path((room_short, room_slug)): Path<(String, String)>, + headers: HeaderMap, + jar: CookieJar, +) -> impl IntoResponse { + let room_id = format!("{room_short}/{room_slug}"); let now = now_ms(); + let reduced = state.reduced.read().await; + if !reduced.rooms.contains(&room_id) { + drop(reduced); + return (StatusCode::NOT_FOUND, "room not found").into_response(); + } + let user = optional_principal(&headers, &jar, &reduced); + if !user_can_view_room(&reduced, &room_id, user.as_deref()) { + drop(reduced); + return room_forbidden_page().into_response(); + } + let scope = ScopeId::Room(room_id.clone()); + let mut rows = collect_thread_rows_for_scope(&reduced, &scope, now); + let strip = auth_strip(&headers, &jar, &reduced); + let show_new = user + .as_ref() + .map(|u| user_can_post_room(&reduced, &room_id, u)) + .unwrap_or(false); + drop(reduced); + rows.sort_by(|a, b| b.last_ts.cmp(&a.last_ts)); + + let Some(nav) = ThreadNav::from_room_id(&room_id) else { + return (StatusCode::NOT_FOUND, "room not found").into_response(); + }; + let slug_display = room_slug.as_str(); + let cli = format!("npx slugsocial private {room_id} forum"); + + let page = layout( + &format!("room {slug_display} — slug.social"), + "view-thread", + html! { + (strip) + nav class="breadcrumb" { (bc_room(&nav, slug_display, None)) } + h2 { (slug_display) } + p class="muted" { (room_id) } + h3 { "threads" } + (render_thread_feed(Some(&nav), "room-thread-feed", &rows, now)) + @if show_new { + (new_thread_form_for_room(&nav, show_new)) + } + (cli_panel(&cli)) + }, + None, + ); + Html(page.into_string()).into_response() +} + +fn new_thread_form_for_room(nav: &ThreadNav, show: bool) -> Markup { + if !show { + return html! {}; + } + html! { + section class="compose" { + h3 { "new thread in this room" } + form method="POST" action="/post" { + input type="hidden" name="room" value=(nav.room_wire.clone()); + label for="room-new-tag" { "thread tag" } + input type="text" id="room-new-tag" name="thread_tag" pattern="[a-z0-9_\\-]{1,64}" required; + textarea name="text" rows="6" placeholder="First post body…" required {} + p { button type="submit" { "post" } } + } + } + } +} + +async fn thread_post_view_inner( + state: AppState, + tag: String, + index_str: String, + nav: ThreadNav, +) -> impl IntoResponse { + let tag = canonicalize_tag(&tag); let index: usize = index_str.parse().unwrap_or(0); + let scope = nav.scope(); + let now = now_ms(); let (ing, subtitle) = { let reduced = state.reduced.read().await; - let ing = reduced.ingests_by_scope_thread.get(&(ScopeId::Public, tag.clone())) + let ing = reduced + .ingests_by_scope_thread + .get(&(scope.clone(), tag.clone())) .and_then(|q| q.iter().rev().nth(index)) .and_then(|id| reduced.ingests_by_id.get(id).cloned()); - let subtitle: Option = None; - (ing, subtitle) + (ing, None::) }; + + let sc = nav.scope(); + let bc: Markup = match &sc { + ScopeId::Public => bc_threads(Some(&tag)), + ScopeId::Room(rid) => { + let slug = if let Some((_, s)) = rid.split_once('/') { + s + } else { + rid.as_str() + }; + bc_room(&nav, slug, Some(&tag)) + } + }; + let page = layout( &format!("#{tag} / post #{index}"), "view-thread", html! { - nav class="breadcrumb" { (bc_threads(Some(&tag))) } + nav class="breadcrumb" { (bc) } h2 { "#" (tag) @if let Some(sub) = &subtitle { ": " (sub) } " / post #" (index) } @if let Some(ing) = ing { @let hover = timeago::rfc3339_utc(ing.ts); @@ -280,21 +654,51 @@ pub async fn thread_post_view( Html(page.into_string()).into_response() } -/// Inline expand handler — `/t/:tag/:id/expand` -/// Returns a JS snippet that morphs the truncated post into its full version. -pub async fn thread_post_expand( +pub async fn thread_post_view( State(state): State, Path((tag, index_str)): Path<(String, String)>, +) -> impl IntoResponse { + thread_post_view_inner(state, tag, index_str, ThreadNav::public()).await +} + +pub async fn room_thread_post_view( + State(state): State, + Path((room_short, room_slug, tag, index_str)): Path<(String, String, String, String)>, + headers: HeaderMap, + jar: CookieJar, +) -> impl IntoResponse { + let room_id = format!("{room_short}/{room_slug}"); + let reduced = state.reduced.read().await; + let user = optional_principal(&headers, &jar, &reduced); + if !user_can_view_room(&reduced, &room_id, user.as_deref()) { + drop(reduced); + return room_forbidden_page().into_response(); + } + drop(reduced); + let Some(nav) = ThreadNav::from_room_id(&room_id) else { + return (StatusCode::NOT_FOUND, "bad room path").into_response(); + }; + thread_post_view_inner(state, tag, index_str, nav) + .await + .into_response() +} + +async fn thread_post_expand_inner( + state: AppState, + tag: String, + index_str: String, + nav: ThreadNav, ) -> impl IntoResponse { let tag = canonicalize_tag(&tag); let index: usize = index_str.parse().unwrap_or(0); let now = now_ms(); + let scope = nav.scope(); let ing = { let reduced = state.reduced.read().await; reduced .ingests_by_scope_thread - .get(&(ScopeId::Public, tag.clone())) + .get(&(scope.clone(), tag.clone())) .and_then(|q| q.iter().rev().nth(index)) .and_then(|id| reduced.ingests_by_id.get(id).cloned()) }; @@ -303,7 +707,7 @@ pub async fn thread_post_expand( return (StatusCode::NOT_FOUND, "post not found").into_response(); }; - let post_href = format!("/t/{tag}/{index}"); + let post_href = nav.post_url(&tag, index); let hover = timeago::rfc3339_utc(ing.ts); let ago = timeago::timeago(now, ing.ts); @@ -319,7 +723,6 @@ pub async fn thread_post_expand( }; let full_html_str = full_html.into_string(); - // Escape backticks and backslashes for JS template literal let escaped = full_html_str .replace('\\', "\\\\") .replace('`', "\\`") @@ -334,7 +737,36 @@ pub async fn thread_post_expand( Response::builder() .status(StatusCode::OK) .header(header::CONTENT_TYPE, "text/javascript; charset=utf-8") - .body(js) + .body(axum::body::Body::from(js)) .unwrap() .into_response() } + +pub async fn thread_post_expand( + State(state): State, + Path((tag, index_str)): Path<(String, String)>, +) -> impl IntoResponse { + thread_post_expand_inner(state, tag, index_str, ThreadNav::public()).await +} + +pub async fn room_thread_post_expand( + State(state): State, + Path((room_short, room_slug, tag, index_str)): Path<(String, String, String, String)>, + headers: HeaderMap, + jar: CookieJar, +) -> impl IntoResponse { + let room_id = format!("{room_short}/{room_slug}"); + let reduced = state.reduced.read().await; + let user = optional_principal(&headers, &jar, &reduced); + if !user_can_view_room(&reduced, &room_id, user.as_deref()) { + drop(reduced); + return (StatusCode::FORBIDDEN, "forbidden").into_response(); + } + drop(reduced); + let Some(nav) = ThreadNav::from_room_id(&room_id) else { + return (StatusCode::NOT_FOUND, "not found").into_response(); + }; + thread_post_expand_inner(state, tag, index_str, nav) + .await + .into_response() +} diff --git a/server/src/html/mod.rs b/server/src/html/mod.rs index 9c5af9654c7010d2cdb100e4cf63ba63e77c8c57..26e86124aae7cd878c92e1dc927e19d9fd2feaba 100644 --- a/server/src/html/mod.rs +++ b/server/src/html/mod.rs @@ -16,7 +16,10 @@ use breadcrumb_path::OntologyPath; pub use auth::{auth_complete_page, auth_signed_in_fragment, choose_username_error_fragment, choose_username_page}; pub use editor::{editor_check, editor_page}; -pub use forum::{index, thread_feed_html, thread_post_expand, thread_post_view, thread_view}; +pub use forum::{ + home, room_page, room_thread_post_expand, room_thread_post_view, room_thread_view, thread_feed_html, + thread_post_expand, thread_post_view, thread_view, +}; pub use garden::{garden_index, ontology_path}; pub use search::{search_page, search_results_fragment}; diff --git a/server/src/lib.rs b/server/src/lib.rs index bf2f73d4d0f26a357961e88c52c3b4f72626af81..b074cc31b94f23d1d566513392d7da3c02653c97 100644 --- a/server/src/lib.rs +++ b/server/src/lib.rs @@ -16,7 +16,7 @@ pub mod state; pub mod timeago; use axum::Router; -use axum::routing::post; +use axum::routing::{get, post}; use tower_http::trace::TraceLayer; use crate::state::AppState; @@ -25,17 +25,48 @@ pub use reducer::ReducerState; pub fn create_app(state: AppState) -> Router { Router::new() - .route("/healthz", axum::routing::get(|| async { "ok" })) - .route("/static/:filename", axum::routing::get(crate::html::serve_theme_css)) - .route("/join/:token", axum::routing::get(api::get_join_invite)) - .route("/auth/login", axum::routing::get(api::get_auth_login)) - .route("/auth/callback", axum::routing::get(api::get_auth_callback)) - .route("/auth/complete", axum::routing::get(api::get_auth_complete)) - .route("/auth/choose-username", axum::routing::get(api::get_choose_username)) - .route("/auth/choose-username", axum::routing::post(api::post_choose_username)) - .route("/api/v0/pending-session", axum::routing::post(api::post_pending_session)) - .route("/api/v0/pending-session/:id", axum::routing::get(api::get_pending_session)) - .route("/api/v0/whoami", axum::routing::get(api::get_whoami)) + .route("/healthz", get(|| async { "ok" })) + .route("/static/:filename", get(crate::html::serve_theme_css)) + .route("/", get(crate::html::home)) + .route("/login", get(api::get_web_login)) + .route("/logout", get(api::get_logout)) + .route("/post", post(api::post_web_ingest)) + .route("/sse", get(api::get_html_stream)) + .route("/stream", get(api::get_stream)) + .route("/search", get(crate::html::search_page)) + .route("/search/results", get(crate::html::search_results_fragment)) + .route("/try", get(crate::html::editor_page)) + .route("/try/check", post(crate::html::editor_check)) + .route("/~", get(crate::html::garden_index)) + .route("/~/*path", get(crate::html::ontology_path)) + .route( + "/t/:tag/:index/expand", + get(crate::html::thread_post_expand), + ) + .route("/t/:tag/:index", get(crate::html::thread_post_view)) + .route("/t/:tag", get(crate::html::thread_view)) + .route( + "/r/:room_short/:room_slug/:thread_tag/:index/expand", + get(crate::html::room_thread_post_expand), + ) + .route( + "/r/:room_short/:room_slug/:thread_tag/:index", + get(crate::html::room_thread_post_view), + ) + .route( + "/r/:room_short/:room_slug/:thread_tag", + get(crate::html::room_thread_view), + ) + .route("/r/:room_short/:room_slug", get(crate::html::room_page)) + .route("/join/:token", get(api::get_join_invite)) + .route("/auth/login", get(api::get_auth_login)) + .route("/auth/callback", get(api::get_auth_callback)) + .route("/auth/complete", get(api::get_auth_complete)) + .route("/auth/choose-username", get(api::get_choose_username)) + .route("/auth/choose-username", post(api::post_choose_username)) + .route("/api/v0/pending-session", post(api::post_pending_session)) + .route("/api/v0/pending-session/:id", get(api::get_pending_session)) + .route("/api/v0/whoami", get(api::get_whoami)) .route("/api/v0/rpc", post(api::handle_rpc_batch)) .with_state(state) .layer(TraceLayer::new_for_http())