Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / infra / agents / agentd / src / tests.rs
tests.rs1090 lines · 48.7 KiBRaw
| 1 | //! Tests: unit tables + in-process integration (mock OpenRouter + mock |
| 2 | //! runner + temp git repos). |
| 3 | //! |
| 4 | //! Run: `cargo test -p agentd`. |
| 5 | |
| 6 | #[cfg(test)] |
| 7 | mod unit { |
| 8 | use crate::auth::{origin_allowed, session_token_from_cookie, Auth}; |
| 9 | use crate::models::{ |
| 10 | branch_name, cap_final_diff, cap_plan_markdown, plan_gate_message, render_todos, slugify, |
| 11 | truncate_result, trim_placeholder, validate_commit_message, |
| 12 | validate_commit_message_for_issue, validate_todos, TodoItem, |
| 13 | FINAL_DIFF_CAP_BYTES, MAX_TODOS, MAX_TODO_CHARS, PLAN_MD_CAP_BYTES, |
| 14 | RESULT_TRUNCATE_BYTES, INBOX_PLAN_APPROVE, INBOX_PLAN_CHANGES, INBOX_REVIEW_CHANGES, |
| 15 | PENDING_PLAN, PENDING_REVIEW, |
| 16 | }; |
| 17 | use crate::openrouter::{parse_chat_response, Message}; |
| 18 | use crate::agent::{format_pending_answer, trim_messages}; |
| 19 | use crate::markdown::render_markdown; |
| 20 | use crate::models::{ |
| 21 | Event, Pending, Task, TaskStatus, EVENT_ASSISTANT, EVENT_STATUS, EVENT_TODOS, |
| 22 | EVENT_TOOL_CALL, EVENT_TOOL_RESULT, EVENT_USER_MESSAGE, PENDING_BUDGET, PENDING_CHAT, |
| 23 | PENDING_QUESTION, |
| 24 | }; |
| 25 | use crate::ui::{ |
| 26 | dashboard_title, render_cards, render_dashboard_page, render_diff_lines, render_panel, |
| 27 | render_task_page, render_timeline_events, |
| 28 | }; |
| 29 | use crate::rules::ancestor_dirs; |
| 30 | use crate::store::{InboxRow, Store}; |
| 31 | use crate::tools::{shell_looks_mutating, validate_build_command, validate_shell_command}; |
| 32 | |
| 33 | fn test_store() -> (Store, tempfile::TempDir) { |
| 34 | let dir = tempfile::tempdir().unwrap(); |
| 35 | let store = Store::open(dir.path()).unwrap(); |
| 36 | (store, dir) |
| 37 | } |
| 38 | |
| 39 | #[test] |
| 40 | fn markdown_safe_subset() { |
| 41 | // Basic blocks + inline formatting. |
| 42 | let html = render_markdown("Hello **bold** and *italic* with `code`."); |
| 43 | assert!(html.contains("<strong>bold</strong>"), "bold: {html}"); |
| 44 | assert!(html.contains("<em>italic</em>"), "italic: {html}"); |
| 45 | assert!(html.contains("<code>code</code>"), "code: {html}"); |
| 46 | // Fenced code block is escaped. |
| 47 | let html = render_markdown("```rust\nlet x = a < b;\n```"); |
| 48 | assert!(html.contains("<pre"), "pre: {html}"); |
| 49 | assert!(html.contains("a < b"), "escaped: {html}"); |
| 50 | assert!(!html.contains("let x = a < b;"), "no raw angle: {html}"); |
| 51 | // Lists. |
| 52 | let html = render_markdown("- one\n- two\n"); |
| 53 | assert!(html.contains("<ul>") && html.contains("<li>one</li>"), "ul: {html}"); |
| 54 | let html = render_markdown("1. one\n2. two\n"); |
| 55 | assert!(html.contains("<ol>"), "ol: {html}"); |
| 56 | // Safe links kept, javascript: dropped to text. |
| 57 | let html = render_markdown("[site](https://example.com/a?b=1)"); |
| 58 | assert!(html.contains("<a href=\"https://example.com/a?b=1\""), "link: {html}"); |
| 59 | let html = render_markdown("[x](javascript:alert(1))"); |
| 60 | assert!(!html.contains("<a"), "no anchor for javascript:: {html}"); |
| 61 | assert!(!html.contains("javascript:"), "no scheme text: {html}"); |
| 62 | assert!(html.contains("x"), "link text survives: {html}"); |
| 63 | } |
| 64 | |
| 65 | #[test] |
| 66 | fn markdown_xss_escaped() { |
| 67 | // Raw HTML (block + inline) is escaped, never passed through. |
| 68 | let html = render_markdown("<script>alert(1)</script>"); |
| 69 | assert!(!html.contains("<script>"), "no raw script: {html}"); |
| 70 | assert!(html.contains("<script>"), "escaped: {html}"); |
| 71 | let html = render_markdown("a <b>bold</b> move"); |
| 72 | assert!(!html.contains("<b>"), "no raw b: {html}"); |
| 73 | assert!(html.contains("<b>bold</b>"), "escaped inline: {html}"); |
| 74 | // Event handlers / img onerror never become elements. |
| 75 | let html = render_markdown("<img src=x onerror=alert(1)>"); |
| 76 | assert!(!html.contains("<img"), "no img: {html}"); |
| 77 | assert!(html.contains("<img"), "escaped: {html}"); |
| 78 | // Markdown image syntax renders alt text only (no external fetch). |
| 79 | let html = render_markdown(""); |
| 80 | assert!(!html.contains("<img"), "no img element: {html}"); |
| 81 | assert!(html.contains("alt"), "alt text: {html}"); |
| 82 | } |
| 83 | |
| 84 | #[test] |
| 85 | fn build_allowlist_accepts() { |
| 86 | for cmd in [ |
| 87 | "./gradlew :notes:compileDevKotlin", |
| 88 | "./gradlew :games:logicgate:lint --console=plain", |
| 89 | "./gradlew :notes:testDebugUnitTest --stacktrace --info", |
| 90 | "./gradlew :backup:detekt", |
| 91 | "./gradlew :notes:checkMetadata", |
| 92 | "./gradlew :notes:lintDev", |
| 93 | "./gradlew :notes:cargoBuildNativeDebug", |
| 94 | "./gradlew :notes:metadata", |
| 95 | "./gradlew :my-app:testFooUnitTest", |
| 96 | "./check notes", |
| 97 | "./check games/logicgate", |
| 98 | "./gradlew :a:b:c:testBarUnitTest --console=plain", |
| 99 | ] { |
| 100 | assert!(validate_build_command(cmd).is_ok(), "should accept {cmd:?}"); |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | #[test] |
| 105 | fn build_allowlist_rejects() { |
| 106 | for cmd in [ |
| 107 | "", |
| 108 | "./gradlew :notes:assembleDebug", |
| 109 | "./gradlew :notes:test", |
| 110 | "./gradlew :notes:testDebug", |
| 111 | "./gradlew :Notes:lint", |
| 112 | "./gradlew notes:lint", |
| 113 | "./gradlew :notes:lint --daemon", |
| 114 | "./gradlew :notes:lint && ./gradlew :notes:detekt", |
| 115 | "./gradlew :notes:lint; rm -rf /", |
| 116 | "./gradlew :notes:lint | tee x", |
| 117 | "./gradlew :notes:lint > out", |
| 118 | "./gradlew :notes:lint $(whoami)", |
| 119 | "./check all", |
| 120 | "./check", |
| 121 | "./check notes backup", |
| 122 | "./install notes", |
| 123 | "adb shell ls", |
| 124 | "cargo test", |
| 125 | "rm -rf /", |
| 126 | "./gradlew", |
| 127 | "gradlew :notes:lint; evil", |
| 128 | ] { |
| 129 | assert!(validate_build_command(cmd).is_err(), "should reject {cmd:?}"); |
| 130 | } |
| 131 | // Error messages name the allowed forms. |
| 132 | let err = validate_build_command("./gradlew :notes:assembleDebug").unwrap_err(); |
| 133 | assert!(err.contains("compileDevKotlin"), "helpful: {err}"); |
| 134 | } |
| 135 | |
| 136 | #[test] |
| 137 | fn shell_rejection_table() { |
| 138 | for cmd in [ |
| 139 | "./gradlew :notes:lint", |
| 140 | "GRADLEW build", |
| 141 | "./check notes", |
| 142 | "./install notes", |
| 143 | "adb devices", |
| 144 | "sudo adb shell", |
| 145 | "cargo build", |
| 146 | "cargo test --all", |
| 147 | "cargo run -p foo", |
| 148 | "cargo check", |
| 149 | "cargo clippy -- -D warnings", |
| 150 | "echo hi | cargo test", |
| 151 | ] { |
| 152 | assert!(validate_shell_command(cmd).is_err(), "should reject {cmd:?}"); |
| 153 | } |
| 154 | for cmd in [ |
| 155 | "ls notes/", |
| 156 | "echo hello", |
| 157 | "grep -r foo notes/ | head", |
| 158 | "python3 scripts/x.py", |
| 159 | "git status", |
| 160 | "rg pattern notes/ -l", |
| 161 | ] { |
| 162 | assert!(validate_shell_command(cmd).is_ok(), "should allow {cmd:?}"); |
| 163 | } |
| 164 | let err = validate_shell_command("./gradlew :notes:lint").unwrap_err(); |
| 165 | assert!(err.contains("build"), "points to build tool: {err}"); |
| 166 | } |
| 167 | |
| 168 | #[test] |
| 169 | fn commit_message_validation() { |
| 170 | assert!(validate_commit_message("notes: fix editor crash\n\nLong body here.").is_ok()); |
| 171 | assert!(validate_commit_message("games/logicgate: add level\n\nBody text.").is_ok()); |
| 172 | assert!(validate_commit_message("x").is_err()); // no scope |
| 173 | assert!(validate_commit_message("Notes: fix\n\nBody.").is_err()); // uppercase scope |
| 174 | assert!(validate_commit_message("notes: \n\nBody.").is_err()); // empty desc |
| 175 | assert!(validate_commit_message("notes: only one line").is_err()); // no body |
| 176 | assert!(validate_commit_message("").is_err()); |
| 177 | let long = format!("notes: {}\n\nBody.", "x".repeat(80)); |
| 178 | assert!(validate_commit_message(&long).is_err()); // first line > 80 |
| 179 | } |
| 180 | |
| 181 | #[test] |
| 182 | fn commit_message_issue_suffix() { |
| 183 | // No linked issue: plain validation, suffix not required. |
| 184 | assert!(validate_commit_message_for_issue("notes: fix editor crash\n\nBody.", None).is_ok()); |
| 185 | // Linked issue: suffix required, helpful error otherwise. |
| 186 | assert!(validate_commit_message_for_issue("notes: fix widget (#903)\n\nBody.", Some(903)).is_ok()); |
| 187 | assert!(validate_commit_message_for_issue("games/logicgate: add level (#12)\n\nBody.", Some(12)).is_ok()); |
| 188 | let err = validate_commit_message_for_issue("notes: fix editor crash\n\nBody.", Some(903)).unwrap_err(); |
| 189 | assert!(err.contains("(#903)"), "helpful: {err}"); |
| 190 | // Wrong number or placement rejected. |
| 191 | assert!(validate_commit_message_for_issue("notes: fix (#904)\n\nBody.", Some(903)).is_err()); |
| 192 | assert!(validate_commit_message_for_issue("notes: (#903) fix\n\nBody.", Some(903)).is_err()); |
| 193 | // Suffix does not excuse other violations. |
| 194 | assert!(validate_commit_message_for_issue("notes: fix (#903)", Some(903)).is_err()); // no body |
| 195 | assert!(validate_commit_message_for_issue("x", Some(903)).is_err()); |
| 196 | } |
| 197 | |
| 198 | #[test] |
| 199 | fn branch_slug_generation() { |
| 200 | assert_eq!(branch_name(7, "Fix editor crash!"), "agent/7-fix-editor-crash"); |
| 201 | assert_eq!(branch_name(1, "!!!"), "agent/1-task"); |
| 202 | assert_eq!(branch_name(2, "games/logicgate: new level"), "agent/2-games-logicgate-new-level"); |
| 203 | let slug = slugify(&"a".repeat(200)); |
| 204 | assert!(slug.len() <= 48, "slug capped: {slug}"); |
| 205 | // Only safe ref chars. |
| 206 | for b in [3, 4] { |
| 207 | let name = branch_name(b, "Héllo wörld @$% & stuff"); |
| 208 | assert!( |
| 209 | name.chars().all(|c| c.is_ascii_alphanumeric() || c == '/' || c == '-'), |
| 210 | "{name}" |
| 211 | ); |
| 212 | } |
| 213 | // `git check-ref-format`-ish: no `..`, no trailing `-`. |
| 214 | assert!(!branch_name(5, "trailing---").ends_with('-')); |
| 215 | } |
| 216 | |
| 217 | #[test] |
| 218 | fn truncation_and_trimming() { |
| 219 | let (short, trunc) = truncate_result("hello"); |
| 220 | assert_eq!(short, "hello"); |
| 221 | assert!(!trunc); |
| 222 | let big = "x".repeat(RESULT_TRUNCATE_BYTES + 1000); |
| 223 | let (t, trunc) = truncate_result(&big); |
| 224 | assert!(trunc); |
| 225 | assert!(t.len() < big.len()); |
| 226 | assert!(t.contains("truncated")); |
| 227 | // Char-boundary safety with multibyte text. |
| 228 | let uni = "é".repeat(RESULT_TRUNCATE_BYTES + 10); |
| 229 | let (u, _) = truncate_result(&uni); |
| 230 | assert!(u.contains("truncated")); |
| 231 | let ph = trim_placeholder("build", 9999); |
| 232 | assert!(ph.contains("build") && ph.contains("9999")); |
| 233 | |
| 234 | // Context trimming: middle tool results become placeholders. |
| 235 | let mut msgs = vec![Message::system("s".into()), Message::user("u".into())]; |
| 236 | for i in 0..8 { |
| 237 | msgs.push(Message::tool_result(format!("c{i}"), "y".repeat(5000))); |
| 238 | } |
| 239 | msgs.push(Message::user("last".into())); |
| 240 | trim_messages(&mut msgs, 10_000); |
| 241 | let trimmed = msgs |
| 242 | .iter() |
| 243 | .filter(|m| { |
| 244 | m.content |
| 245 | .as_ref() |
| 246 | .map(|c| c.contains("trimmed")) |
| 247 | .unwrap_or(false) |
| 248 | }) |
| 249 | .count(); |
| 250 | assert!(trimmed >= 2, "old results trimmed, got {trimmed}"); |
| 251 | // Tail preserved. |
| 252 | assert!(msgs.last().unwrap().content.as_ref().unwrap().contains("last")); |
| 253 | } |
| 254 | |
| 255 | #[test] |
| 256 | fn argon2_login_and_session_lifecycle() { |
| 257 | use argon2::{Argon2, PasswordHasher, password_hash::SaltString}; |
| 258 | let salt = SaltString::from_b64("AAAAAAAAAAAAAAAAAAAAAA").unwrap(); |
| 259 | let hash = Argon2::default() |
| 260 | .hash_password(b"correct horse", &salt) |
| 261 | .unwrap() |
| 262 | .to_string(); |
| 263 | let (store, _dir) = test_store(); |
| 264 | let auth = Auth::new(store, hash); |
| 265 | assert!(auth.verify_password("correct horse")); |
| 266 | assert!(!auth.verify_password("wrong")); |
| 267 | let token = auth.issue_session().unwrap(); |
| 268 | assert!(auth.check_token(&token)); |
| 269 | assert!(!auth.check_token("bogus")); |
| 270 | auth.revoke_token(&token); |
| 271 | assert!(!auth.check_token(&token)); |
| 272 | } |
| 273 | |
| 274 | #[test] |
| 275 | fn origin_check_table() { |
| 276 | assert!(origin_allowed(Some("https://agents.maproj.org"), "https://agents.maproj.org")); |
| 277 | assert!(!origin_allowed(None, "https://agents.maproj.org")); |
| 278 | assert!(!origin_allowed(Some("https://evil.test"), "https://agents.maproj.org")); |
| 279 | assert!(!origin_allowed(Some("https://agents.maproj.org.evil.test"), "https://agents.maproj.org")); |
| 280 | assert!(!origin_allowed(Some("http://agents.maproj.org"), "https://agents.maproj.org")); |
| 281 | } |
| 282 | |
| 283 | #[test] |
| 284 | fn cookie_parse() { |
| 285 | assert_eq!( |
| 286 | session_token_from_cookie("a=1; agentd_session=tok123; b=2"), |
| 287 | Some("tok123".to_string()) |
| 288 | ); |
| 289 | assert_eq!(session_token_from_cookie("agentd_session=; a=1"), None); |
| 290 | assert_eq!(session_token_from_cookie("other=1"), None); |
| 291 | } |
| 292 | |
| 293 | // ---- OpenRouter response fixtures ---- |
| 294 | |
| 295 | fn tool_call_fixture() -> &'static [u8] { |
| 296 | br#"{ |
| 297 | "id": "gen-1", "choices": [{ |
| 298 | "message": { |
| 299 | "role": "assistant", |
| 300 | "content": "Reading the file.", |
| 301 | "tool_calls": [{ |
| 302 | "id": "call_1", "type": "function", |
| 303 | "function": {"name": "read_file", "arguments": "{\"path\": \"notes/x.kt\"}"} |
| 304 | }] |
| 305 | } |
| 306 | }], |
| 307 | "usage": {"prompt_tokens": 100, "completion_tokens": 20, "total_tokens": 120, "cost": 0.0003} |
| 308 | }"# |
| 309 | } |
| 310 | |
| 311 | #[test] |
| 312 | fn assistant_text_constructor() { |
| 313 | let m = Message::assistant_text("hi".into()); |
| 314 | assert_eq!(m.role, "assistant"); |
| 315 | } |
| 316 | |
| 317 | #[test] |
| 318 | fn openrouter_parses_tool_calls_and_cost() { |
| 319 | let turn = parse_chat_response(tool_call_fixture()).unwrap(); |
| 320 | assert_eq!(turn.text, "Reading the file."); |
| 321 | assert_eq!(turn.tool_calls.len(), 1); |
| 322 | assert_eq!(turn.tool_calls[0].function.name, "read_file"); |
| 323 | assert_eq!(turn.usage.prompt_tokens, 100); |
| 324 | assert!((turn.usage.cost_usd() - 0.0003).abs() < 1e-9); |
| 325 | } |
| 326 | |
| 327 | #[test] |
| 328 | fn openrouter_parses_text_only_and_missing_cost() { |
| 329 | let body = br#"{"choices": [{"message": {"role": "assistant", "content": "done"}}], |
| 330 | "usage": {"prompt_tokens": 5, "completion_tokens": 2}}"#; |
| 331 | let turn = parse_chat_response(body).unwrap(); |
| 332 | assert_eq!(turn.text, "done"); |
| 333 | assert!(turn.tool_calls.is_empty()); |
| 334 | assert_eq!(turn.usage.cost_usd(), 0.0); |
| 335 | } |
| 336 | |
| 337 | #[test] |
| 338 | fn openrouter_parses_total_cost_and_parts_array() { |
| 339 | let body = br#"{"choices": [{"message": {"role": "assistant", |
| 340 | "content": [{"type": "text", "text": "hel"}, {"type": "text", "text": "lo"}]}}], |
| 341 | "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_cost": 0.001}}"#; |
| 342 | let turn = parse_chat_response(body).unwrap(); |
| 343 | assert_eq!(turn.text, "hello"); |
| 344 | assert!((turn.usage.cost_usd() - 0.001).abs() < 1e-9); |
| 345 | } |
| 346 | |
| 347 | #[test] |
| 348 | fn openrouter_parses_errors_and_empty_choices() { |
| 349 | let body = br#"{"error": {"message": "insufficient credits", "code": 402}}"#; |
| 350 | assert!(parse_chat_response(body).is_err()); |
| 351 | let body = br#"{"choices": []}"#; |
| 352 | assert!(parse_chat_response(body).is_err()); |
| 353 | assert!(parse_chat_response(b"not json").is_err()); |
| 354 | } |
| 355 | |
| 356 | #[test] |
| 357 | fn system_prompt_injects_scope_and_rules() { |
| 358 | let p = crate::prompt::system_prompt("notes", Some("ROOT-RULES"), Some("MODULE-RULES")); |
| 359 | assert!(p.contains("notes")); |
| 360 | assert!(p.contains("ROOT-RULES")); |
| 361 | assert!(p.contains("MODULE-RULES")); |
| 362 | assert!(p.contains("finish")); |
| 363 | // Product default: Plan first ON. |
| 364 | assert!(p.contains("Plan first is ON")); |
| 365 | let off = crate::prompt::build_system_prompt( |
| 366 | "notes", &[], Some("R"), Some("M"), "", "", false, false, |
| 367 | ); |
| 368 | assert!(off.contains("Plan first is OFF")); |
| 369 | let approved = crate::prompt::build_system_prompt( |
| 370 | "notes", &[], Some("R"), Some("M"), "my plan", "", true, true, |
| 371 | ); |
| 372 | assert!(approved.contains("plan was approved")); |
| 373 | assert!(approved.contains("my plan")); |
| 374 | } |
| 375 | |
| 376 | #[test] |
| 377 | fn store_roundtrip_and_claim() { |
| 378 | let (store, _dir) = test_store(); |
| 379 | let id = store.create_task("t", "p", "notes", "m", 60, 2.0).unwrap(); |
| 380 | store.set_branch(id, "agent/1-t").unwrap(); |
| 381 | let claimed = store.claim_queued(0).unwrap().unwrap(); |
| 382 | assert_eq!(claimed.id, id); |
| 383 | assert!(store.next_queued().unwrap().is_none()); |
| 384 | // Second claim loses (already running). |
| 385 | store.create_task("t2", "p", "notes", "m", 60, 2.0).unwrap(); |
| 386 | // Events append with increasing seq. |
| 387 | store.push_event(id, "status", &serde_json::json!({"a": 1})).unwrap(); |
| 388 | store.push_event(id, "status", &serde_json::json!({"a": 2})).unwrap(); |
| 389 | let evs = store.list_events(id, None).unwrap(); |
| 390 | assert_eq!(evs.len(), 2); |
| 391 | assert_eq!(evs[0].seq, 0); |
| 392 | assert_eq!(evs[1].seq, 1); |
| 393 | let after = store.list_events(id, Some(0)).unwrap(); |
| 394 | assert_eq!(after.len(), 1); |
| 395 | } |
| 396 | |
| 397 | #[test] |
| 398 | fn triage_kv_and_task_roundtrip() { |
| 399 | use crate::models::{TASK_KIND_TASK, TASK_KIND_TRIAGE}; |
| 400 | let (store, _dir) = test_store(); |
| 401 | |
| 402 | // kv: missing → set → get → overwrite. |
| 403 | assert_eq!(store.kv_get("triage_watermark").unwrap(), None); |
| 404 | store.kv_set("triage_watermark", "2026-11-05T00:00:00Z").unwrap(); |
| 405 | assert_eq!( |
| 406 | store.kv_get("triage_watermark").unwrap(), |
| 407 | Some("2026-11-05T00:00:00Z".to_string()) |
| 408 | ); |
| 409 | store.kv_set("triage_watermark", "2026-11-06T00:00:00Z").unwrap(); |
| 410 | assert_eq!( |
| 411 | store.kv_get("triage_watermark").unwrap(), |
| 412 | Some("2026-11-06T00:00:00Z".to_string()) |
| 413 | ); |
| 414 | |
| 415 | // Normal tasks default to kind='task'. |
| 416 | let plain = store.create_task("t", "p", "notes", "m", 60, 2.0).unwrap(); |
| 417 | assert_eq!(store.get_task(plain).unwrap().unwrap().kind, TASK_KIND_TASK); |
| 418 | |
| 419 | // Triage task: kind, budget, plan gate off, issue link. |
| 420 | let tri = store |
| 421 | .create_triage_task(903, "#903 widgets", "prompt", "weather", "m") |
| 422 | .unwrap(); |
| 423 | let task = store.get_task(tri).unwrap().unwrap(); |
| 424 | assert_eq!(task.kind, TASK_KIND_TRIAGE); |
| 425 | assert_eq!(task.budget_steps, 40); |
| 426 | assert!((task.budget_usd - 0.50).abs() < 1e-9); |
| 427 | assert!(!task.require_plan); |
| 428 | assert_eq!(task.issue_number, Some(903)); |
| 429 | |
| 430 | // triage rows: missing → insert true → insert false (idempotent) → |
| 431 | // get → set_result → recent ordering. |
| 432 | assert!(store.triage_get(903).unwrap().is_none()); |
| 433 | assert!(store.triage_insert(903, tri).unwrap()); |
| 434 | assert!(!store.triage_insert(903, tri).unwrap()); |
| 435 | let row = store.triage_get(903).unwrap().unwrap(); |
| 436 | assert_eq!(row.issue_number, 903); |
| 437 | assert_eq!(row.task_id, tri); |
| 438 | assert_eq!(row.status, "queued"); |
| 439 | store |
| 440 | .triage_set_result(903, "done", Some(r#"{"kind":"bug"}"#)) |
| 441 | .unwrap(); |
| 442 | let row = store.triage_get(903).unwrap().unwrap(); |
| 443 | assert_eq!(row.status, "done"); |
| 444 | assert_eq!(row.result_json, Some(r#"{"kind":"bug"}"#.to_string())); |
| 445 | |
| 446 | let tri2 = store |
| 447 | .create_triage_task(904, "#904 other", "prompt", "", "m") |
| 448 | .unwrap(); |
| 449 | assert!(store.triage_insert(904, tri2).unwrap()); |
| 450 | let recent = store.triage_recent(10).unwrap(); |
| 451 | assert_eq!(recent.len(), 2); |
| 452 | assert_eq!(recent[0].issue_number, 904); |
| 453 | assert_eq!(recent[1].issue_number, 903); |
| 454 | assert_eq!(store.triage_recent(1).unwrap().len(), 1); |
| 455 | } |
| 456 | |
| 457 | #[test] |
| 458 | fn history_persisted_and_trimming_never_mutates_stored() { |
| 459 | use crate::models::Pending; |
| 460 | let (store, _dir) = test_store(); |
| 461 | let id = store.create_task("t", "p", "notes", "m", 60, 2.0).unwrap(); |
| 462 | let msgs = vec![ |
| 463 | Message::user("Task: t\n\np".into()), |
| 464 | Message::assistant_calls( |
| 465 | Some("reading".into()), |
| 466 | vec![crate::openrouter::ToolCall { |
| 467 | id: "c1".into(), |
| 468 | kind: "function".into(), |
| 469 | function: crate::openrouter::FunctionCall { |
| 470 | name: "read_file".into(), |
| 471 | arguments: "{}".into(), |
| 472 | }, |
| 473 | }], |
| 474 | ), |
| 475 | Message::tool_result("c1".into(), "content here".into()), |
| 476 | ]; |
| 477 | for m in &msgs { |
| 478 | store.append_message(id, m).unwrap(); |
| 479 | } |
| 480 | let loaded = store.load_messages(id).unwrap(); |
| 481 | assert_eq!(loaded.len(), 3); |
| 482 | assert_eq!(loaded[0].role, "user"); |
| 483 | // Clone-trim: the stored rows are untouched. |
| 484 | let big: Vec<Message> = (0..10) |
| 485 | .map(|i| Message::tool_result(format!("cx{i}"), "y".repeat(5000))) |
| 486 | .collect(); |
| 487 | let mut wide = loaded.clone(); |
| 488 | wide.extend(big); |
| 489 | let before: Vec<String> = store |
| 490 | .load_messages(id) |
| 491 | .unwrap() |
| 492 | .iter() |
| 493 | .map(|m| m.content.clone().unwrap_or_default()) |
| 494 | .collect(); |
| 495 | let trimmed = crate::agent::trimmed_clone(&wide, 10_000); |
| 496 | assert!(trimmed.len() == wide.len(), "trim never drops messages"); |
| 497 | let after: Vec<String> = store |
| 498 | .load_messages(id) |
| 499 | .unwrap() |
| 500 | .iter() |
| 501 | .map(|m| m.content.clone().unwrap_or_default()) |
| 502 | .collect(); |
| 503 | assert_eq!(before, after, "stored history never mutated"); |
| 504 | // Pairing: every tool_calls id still has its result in the clone. |
| 505 | let mut calls = std::collections::HashSet::new(); |
| 506 | let mut results = std::collections::HashSet::new(); |
| 507 | for m in &trimmed { |
| 508 | if m.role == "assistant" { |
| 509 | if let Some(cs) = &m.tool_calls { |
| 510 | for c in cs { |
| 511 | calls.insert(c.id.clone()); |
| 512 | } |
| 513 | } |
| 514 | } |
| 515 | if m.role == "tool" { |
| 516 | if let Some(tid) = &m.tool_call_id { |
| 517 | results.insert(tid.clone()); |
| 518 | } |
| 519 | } |
| 520 | } |
| 521 | for c in &calls { |
| 522 | assert!(results.contains(c), "unanswered call {c} after trim"); |
| 523 | } |
| 524 | // Pending round-trips through the row. |
| 525 | let p = Pending::new("question", Some("c9".into()), serde_json::json!({"question": "q?"})); |
| 526 | let eff = store |
| 527 | .park_task(id, crate::models::TaskStatus::NeedsInput, &p, None) |
| 528 | .unwrap(); |
| 529 | assert_eq!(eff, crate::models::TaskStatus::NeedsInput); |
| 530 | let t = store.get_task(id).unwrap().unwrap(); |
| 531 | assert_eq!(t.pending.unwrap().kind, "question"); |
| 532 | assert!(t.slot.is_none()); |
| 533 | let _ = Pending::new("x", None, serde_json::Value::Null); |
| 534 | } |
| 535 | |
| 536 | #[test] |
| 537 | fn park_task_lost_wakeup_requeues() { |
| 538 | use crate::models::{Pending, TaskStatus}; |
| 539 | let (store, _dir) = test_store(); |
| 540 | let id = store.create_task("t", "p", "notes", "m", 60, 2.0).unwrap(); |
| 541 | // Message inserted mid-park (before park_task runs): re-queues. |
| 542 | store.inbox_post_kind(id, "answer!", "").unwrap(); |
| 543 | let p = Pending::new("question", Some("c1".into()), serde_json::json!({})); |
| 544 | let eff = store.park_task(id, TaskStatus::NeedsInput, &p, None).unwrap(); |
| 545 | assert_eq!(eff, TaskStatus::Queued, "inbox message forces re-queue"); |
| 546 | // Draining consumes each row exactly once. |
| 547 | let rows = store.drain_inbox(id).unwrap(); |
| 548 | assert_eq!(rows, vec!["answer!".to_string()]); |
| 549 | assert!(store.drain_inbox(id).unwrap().is_empty()); |
| 550 | } |
| 551 | |
| 552 | #[test] |
| 553 | fn inbox_post_requeues_parked_and_succeeded() { |
| 554 | use crate::models::{Pending, TaskStatus}; |
| 555 | let (store, _dir) = test_store(); |
| 556 | let id = store.create_task("t", "p", "notes", "m", 60, 2.0).unwrap(); |
| 557 | let p = Pending::new("chat", None, serde_json::json!({})); |
| 558 | store.park_task(id, TaskStatus::NeedsInput, &p, None).unwrap(); |
| 559 | assert!(store.inbox_post_kind(id, "hello", "").unwrap()); |
| 560 | assert_eq!(store.get_task(id).unwrap().unwrap().status, TaskStatus::Queued); |
| 561 | // Running tasks: inbox stored, no re-queue (driver drains it). |
| 562 | store.update_status(id, TaskStatus::Running, None, None).unwrap(); |
| 563 | store.drain_inbox(id).unwrap(); |
| 564 | assert!(!store.inbox_post_kind(id, "steer", "").unwrap()); |
| 565 | assert_eq!(store.get_task(id).unwrap().unwrap().status, TaskStatus::Running); |
| 566 | // Terminal tasks: no re-queue. |
| 567 | store.update_status(id, TaskStatus::Discarded, None, None).unwrap(); |
| 568 | assert!(!store.inbox_post_kind(id, "late", "").unwrap()); |
| 569 | } |
| 570 | |
| 571 | #[test] |
| 572 | fn restart_recovery_marks_only_running() { |
| 573 | use crate::models::{Pending, TaskStatus}; |
| 574 | let (store, _dir) = test_store(); |
| 575 | let running = store.create_task("r", "p", "notes", "m", 60, 2.0).unwrap(); |
| 576 | store.claim_queued(0).unwrap(); |
| 577 | let parked = store.create_task("p", "p", "notes", "m", 60, 2.0).unwrap(); |
| 578 | let p = Pending::new("question", Some("c1".into()), serde_json::json!({})); |
| 579 | store.park_task(parked, TaskStatus::NeedsInput, &p, None).unwrap(); |
| 580 | // Only the `running` row is an orphan. |
| 581 | let orphans = store.interrupted_running_ids().unwrap(); |
| 582 | assert_eq!(orphans, vec![running]); |
| 583 | // Synthetic results cover exactly the unanswered calls. |
| 584 | store |
| 585 | .append_message( |
| 586 | running, |
| 587 | &Message::assistant_calls( |
| 588 | None, |
| 589 | vec![crate::openrouter::ToolCall { |
| 590 | id: "cx".into(), |
| 591 | kind: "function".into(), |
| 592 | function: crate::openrouter::FunctionCall { |
| 593 | name: "read_file".into(), |
| 594 | arguments: "{}".into(), |
| 595 | }, |
| 596 | }], |
| 597 | ), |
| 598 | ) |
| 599 | .unwrap(); |
| 600 | let hist = store.load_messages(running).unwrap(); |
| 601 | let answered: Vec<&str> = hist |
| 602 | .iter() |
| 603 | .filter(|m| m.role == "tool") |
| 604 | .filter_map(|m| m.tool_call_id.as_deref()) |
| 605 | .collect(); |
| 606 | assert!(answered.is_empty()); |
| 607 | let _ = parked; |
| 608 | } |
| 609 | |
| 610 | #[test] |
| 611 | fn secrets_scrubbed() { |
| 612 | let s = crate::agent::scrub_secrets("use Bearer secret-token-123 now"); |
| 613 | assert!(!s.contains("secret-token-123"), "{s}"); |
| 614 | assert!(s.contains("[redacted]")); |
| 615 | } |
| 616 | |
| 617 | #[test] |
| 618 | fn shell_mutation_detector_table() { |
| 619 | // Rejected (mutating) patterns. |
| 620 | for cmd in [ |
| 621 | "echo hi > out.txt", |
| 622 | "cat a >> b", |
| 623 | "echo x 2> err", |
| 624 | "cmd1 | tee log.txt", |
| 625 | "tee newfile", |
| 626 | "sed -i 's/a/b/' notes/f.kt", |
| 627 | "sed --in-place 's/a/b/' f", |
| 628 | "mv a b", |
| 629 | "sudo mv a b", |
| 630 | "cp a b", |
| 631 | "rm -rf notes/tmp", |
| 632 | "touch newfile", |
| 633 | "mkdir -p notes/sub", |
| 634 | "git add notes/f.kt", |
| 635 | "git commit -m 'x'", |
| 636 | "git checkout -b feat", |
| 637 | "git -C notes apply fix.patch", |
| 638 | "git clean -fd", |
| 639 | "git reset --hard HEAD", |
| 640 | "git stash push", |
| 641 | "echo hi; rm x", |
| 642 | ] { |
| 643 | assert!(shell_looks_mutating(cmd), "should look mutating: {cmd:?}"); |
| 644 | } |
| 645 | // Allowed (read-only) commands. |
| 646 | for cmd in [ |
| 647 | "ls notes/", |
| 648 | "echo hello", |
| 649 | "git status", |
| 650 | "git diff --stat", |
| 651 | "git log --oneline -5", |
| 652 | "git show HEAD:notes/f.kt", |
| 653 | "git blame notes/f.kt", |
| 654 | "rg pattern notes/ -l", |
| 655 | "grep -r foo notes/ | head", |
| 656 | "guarantee availability", |
| 657 | "cat notes/file.txt", |
| 658 | "remember to teethe brush", |
| 659 | // Documented gap: this detector is best-effort. A model that |
| 660 | // really wants to mutate can do it through an allowed command |
| 661 | // (python/perl apply-patch, etc.). The plan gate keeps honest |
| 662 | // agents on the plan-first path; it is not a sandbox. |
| 663 | ] { |
| 664 | assert!(!shell_looks_mutating(cmd), "should look read-only: {cmd:?}"); |
| 665 | } |
| 666 | } |
| 667 | |
| 668 | #[test] |
| 669 | fn todos_validation_and_rendering() { |
| 670 | assert_eq!(plan_gate_message(), "Propose a plan with propose_plan and wait for approval before editing or building."); |
| 671 | let ok = vec![ |
| 672 | TodoItem { text: "write code".to_string(), status: "pending".to_string() }, |
| 673 | TodoItem { text: "run build".to_string(), status: "in_progress".to_string() }, |
| 674 | TodoItem { text: "done thing".to_string(), status: "done".to_string() }, |
| 675 | ]; |
| 676 | assert!(validate_todos(&ok).is_ok()); |
| 677 | let rendered = render_todos(Some(&serde_json::to_string(&ok).unwrap())); |
| 678 | assert!(rendered.contains("[ ] write code"), "{rendered}"); |
| 679 | assert!(rendered.contains("[>] run build"), "{rendered}"); |
| 680 | assert!(rendered.contains("[x] done thing"), "{rendered}"); |
| 681 | assert_eq!(render_todos(None), ""); |
| 682 | assert_eq!(render_todos(Some("[]")), ""); |
| 683 | assert_eq!(render_todos(Some("not json")), ""); |
| 684 | // Too many items. |
| 685 | let many: Vec<TodoItem> = (0..=MAX_TODOS) |
| 686 | .map(|i| TodoItem { text: format!("t{i}"), status: "pending".to_string() }) |
| 687 | .collect(); |
| 688 | assert!(validate_todos(&many).is_err()); |
| 689 | assert!(validate_todos(&many[..MAX_TODOS]).is_ok()); |
| 690 | // Bad status / long text / empty text. |
| 691 | assert!(validate_todos(&[TodoItem { text: "t".to_string(), status: "bogus".to_string() }]).is_err()); |
| 692 | assert!(validate_todos(&[TodoItem { text: "x".repeat(MAX_TODO_CHARS + 1), status: "pending".to_string() }]).is_err()); |
| 693 | assert!(validate_todos(&[TodoItem { text: "".to_string(), status: "pending".to_string() }]).is_err()); |
| 694 | assert!(validate_todos(&[TodoItem { text: " ".to_string(), status: "done".to_string() }]).is_err()); |
| 695 | } |
| 696 | |
| 697 | #[test] |
| 698 | fn final_diff_and_plan_caps() { |
| 699 | let (short, trunc) = cap_final_diff("abc"); |
| 700 | assert_eq!(short, "abc"); |
| 701 | assert!(!trunc); |
| 702 | let big = "d".repeat(FINAL_DIFF_CAP_BYTES + 500); |
| 703 | let (capped, trunc) = cap_final_diff(&big); |
| 704 | assert!(trunc); |
| 705 | assert!(capped.contains("diff truncated")); |
| 706 | assert!(capped.len() < big.len()); |
| 707 | let (p, trunc) = cap_plan_markdown("plan"); |
| 708 | assert_eq!(p, "plan"); |
| 709 | assert!(!trunc); |
| 710 | let big_plan = "p".repeat(PLAN_MD_CAP_BYTES + 10); |
| 711 | let (capped, trunc) = cap_plan_markdown(&big_plan); |
| 712 | assert!(trunc && capped.contains("plan truncated")); |
| 713 | // Multibyte boundary safety. |
| 714 | let uni = "é".repeat(FINAL_DIFF_CAP_BYTES + 5); |
| 715 | let (u, _) = cap_final_diff(&uni); |
| 716 | assert!(u.contains("diff truncated")); |
| 717 | } |
| 718 | |
| 719 | #[test] |
| 720 | fn rules_ancestor_walk() { |
| 721 | assert!(ancestor_dirs("AGENTS.md").is_empty()); |
| 722 | assert!(ancestor_dirs("notes/file.txt") == vec!["notes".to_string()]); |
| 723 | assert_eq!( |
| 724 | ancestor_dirs("notes/sub/deep/f.kt"), |
| 725 | vec!["notes".to_string(), "notes/sub".to_string(), "notes/sub/deep".to_string()] |
| 726 | ); |
| 727 | assert!(ancestor_dirs("/notes/file.txt") == vec!["notes".to_string()]); |
| 728 | assert!(ancestor_dirs("single").is_empty()); |
| 729 | } |
| 730 | |
| 731 | #[test] |
| 732 | fn pending_answer_formatting() { |
| 733 | use crate::models::Pending; |
| 734 | let row = |text: &str, kind: &str| InboxRow { |
| 735 | text: text.to_string(), |
| 736 | kind: kind.to_string(), |
| 737 | }; |
| 738 | // Plan approve. |
| 739 | let p = Pending::new(PENDING_PLAN, Some("c1".into()), serde_json::json!({})); |
| 740 | assert_eq!( |
| 741 | format_pending_answer(&p, &[row("approved", INBOX_PLAN_APPROVE)]), |
| 742 | "Plan approved. Proceed." |
| 743 | ); |
| 744 | // Plan changes (plan stays unapproved). |
| 745 | assert_eq!( |
| 746 | format_pending_answer(&p, &[row("add tests", INBOX_PLAN_CHANGES)]), |
| 747 | "User requested changes to the plan: add tests" |
| 748 | ); |
| 749 | // Review changes. |
| 750 | let r = Pending::new(PENDING_REVIEW, Some("c9".into()), serde_json::json!({})); |
| 751 | assert_eq!( |
| 752 | format_pending_answer(&r, &[row("fix naming", INBOX_REVIEW_CHANGES)]), |
| 753 | "User reviewed the change and requested: fix naming" |
| 754 | ); |
| 755 | // Plain ask_user answer passes through raw. |
| 756 | let q = Pending::new("question", Some("c2".into()), serde_json::json!({})); |
| 757 | assert_eq!( |
| 758 | format_pending_answer(&q, &[row("hello world", "")]), |
| 759 | "hello world" |
| 760 | ); |
| 761 | } |
| 762 | |
| 763 | #[test] |
| 764 | fn store_plan_todos_rules_review_roundtrip() { |
| 765 | use crate::models::TaskStatus; |
| 766 | let (store, _dir) = test_store(); |
| 767 | let id = store.create_task("t", "p", "notes", "m", 60, 2.0).unwrap(); |
| 768 | // Plan gate flag (new-task "Plan first" checkbox). |
| 769 | store.set_plan_gate(id, true).unwrap(); |
| 770 | let t = store.get_task(id).unwrap().unwrap(); |
| 771 | assert!(t.require_plan && !t.plan_approved); |
| 772 | assert_eq!(t.status, TaskStatus::Queued); |
| 773 | // Plan text + approval. |
| 774 | store.set_plan_md(id, "## plan\n1. do things").unwrap(); |
| 775 | store.approve_plan(id).unwrap(); |
| 776 | let t = store.get_task(id).unwrap().unwrap(); |
| 777 | assert_eq!(t.plan_md.as_deref(), Some("## plan\n1. do things")); |
| 778 | assert!(t.plan_approved); |
| 779 | // Todos. |
| 780 | let items = vec![TodoItem { text: "a".to_string(), status: "done".to_string() }, TodoItem { text: "b".to_string(), status: "pending".to_string() }]; |
| 781 | store.set_todos(id, &serde_json::to_string(&items).unwrap()).unwrap(); |
| 782 | let t = store.get_task(id).unwrap().unwrap(); |
| 783 | assert!(t.todos_json.unwrap().contains("\"text\":\"a\"")); |
| 784 | // Rules merge: existing entries win, nulls record known-missing. |
| 785 | let mut first = std::collections::BTreeMap::new(); |
| 786 | first.insert("AGENTS.md".to_string(), Some("ROOT".to_string())); |
| 787 | first.insert("notes/nope/AGENTS.md".to_string(), None); |
| 788 | store.merge_rules(id, &first).unwrap(); |
| 789 | let mut second = std::collections::BTreeMap::new(); |
| 790 | second.insert("AGENTS.md".to_string(), Some("CHANGED".to_string())); |
| 791 | second.insert("notes/sub/AGENTS.md".to_string(), Some("SUB".to_string())); |
| 792 | store.merge_rules(id, &second).unwrap(); |
| 793 | let t = store.get_task(id).unwrap().unwrap(); |
| 794 | let map: serde_json::Value = serde_json::from_str(&t.rules_json.unwrap()).unwrap(); |
| 795 | assert_eq!(map["AGENTS.md"], serde_json::Value::String("ROOT".to_string())); |
| 796 | assert!(map["notes/nope/AGENTS.md"].is_null()); |
| 797 | assert_eq!(map["notes/sub/AGENTS.md"], serde_json::Value::String("SUB".to_string())); |
| 798 | // Review snapshot + push bookkeeping. |
| 799 | store.set_review(id, "wipsha", "diff --git ...", "notes: x\n\nBody.", "summ").unwrap(); |
| 800 | let t = store.get_task(id).unwrap().unwrap(); |
| 801 | assert_eq!(t.wip_sha.as_deref(), Some("wipsha")); |
| 802 | assert_eq!(t.final_diff.as_deref(), Some("diff --git ...")); |
| 803 | store.set_pushed(id, "pushedsha").unwrap(); |
| 804 | let t = store.get_task(id).unwrap().unwrap(); |
| 805 | assert!(t.pushed); |
| 806 | assert_eq!(t.pushed_sha.as_deref(), Some("pushedsha")); |
| 807 | assert_eq!(t.base_sha.as_deref(), Some("pushedsha")); |
| 808 | assert!(t.wip_sha.is_none() && t.pending.is_none()); |
| 809 | // Tagged inbox rows round-trip with kinds. |
| 810 | store.inbox_post_kind(id, "approved", INBOX_PLAN_APPROVE).unwrap(); |
| 811 | store.inbox_post_kind(id, "plain", "").unwrap(); |
| 812 | let rows = store.drain_inbox_tagged(id).unwrap(); |
| 813 | assert_eq!(rows.len(), 2); |
| 814 | assert_eq!(rows[0].kind, INBOX_PLAN_APPROVE); |
| 815 | assert_eq!(rows[1].kind, ""); |
| 816 | assert!(store.drain_inbox(id).unwrap().is_empty()); |
| 817 | } |
| 818 | |
| 819 | #[test] |
| 820 | fn approve_claim_is_exclusive_and_holds_messages() { |
| 821 | use crate::models::TaskStatus; |
| 822 | let (store, _dir) = test_store(); |
| 823 | let id = store.create_task("t", "p", "notes", "m", 60, 2.0).unwrap(); |
| 824 | store.update_status(id, TaskStatus::Review, None, None).unwrap(); |
| 825 | assert!(store.claim_approve(id).unwrap(), "first approve claims"); |
| 826 | assert!(!store.claim_approve(id).unwrap(), "double click is refused"); |
| 827 | // A message mid-approve is kept but must not re-queue the task. |
| 828 | assert!(!store.inbox_post_kind(id, "one more thing", "").unwrap()); |
| 829 | assert_eq!(store.get_task(id).unwrap().unwrap().status, TaskStatus::Review); |
| 830 | // Approve succeeds; finishing re-queues so the message becomes a follow-up. |
| 831 | store.update_status(id, TaskStatus::Succeeded, None, None).unwrap(); |
| 832 | store.finish_approve(id).unwrap(); |
| 833 | assert_eq!(store.get_task(id).unwrap().unwrap().status, TaskStatus::Queued); |
| 834 | assert!(!store.claim_approve(id).unwrap(), "not in review any more"); |
| 835 | // Stale claims from a crash are cleared at startup. |
| 836 | let id2 = store.create_task("t2", "p", "notes", "m", 60, 2.0).unwrap(); |
| 837 | store.update_status(id2, TaskStatus::Review, None, None).unwrap(); |
| 838 | assert!(store.claim_approve(id2).unwrap()); |
| 839 | assert_eq!(store.clear_stale_approving().unwrap(), 1); |
| 840 | assert!(store.claim_approve(id2).unwrap()); |
| 841 | } |
| 842 | |
| 843 | // ---- chat UI (ui.rs presentation) ---- |
| 844 | |
| 845 | fn ui_task(status: TaskStatus, pending: Option<Pending>) -> Task { |
| 846 | Task { |
| 847 | id: 1, |
| 848 | title: "Test task".to_string(), |
| 849 | prompt: "do things".to_string(), |
| 850 | module_scope: "notes".to_string(), |
| 851 | model: "test/model".to_string(), |
| 852 | kind: crate::models::TASK_KIND_TASK.to_string(), |
| 853 | status, |
| 854 | slot: None, |
| 855 | branch: "agent/1-test-task".to_string(), |
| 856 | base_sha: None, |
| 857 | commit_sha: None, |
| 858 | pushed: false, |
| 859 | created_at: 0, |
| 860 | updated_at: 0, |
| 861 | started_at: None, |
| 862 | finished_at: None, |
| 863 | steps: 3, |
| 864 | prompt_tokens: 100, |
| 865 | completion_tokens: 50, |
| 866 | cost_usd: 0.001, |
| 867 | budget_steps: 60, |
| 868 | budget_usd: 2.0, |
| 869 | error: None, |
| 870 | summary: None, |
| 871 | pending, |
| 872 | todos_json: None, |
| 873 | rules_json: None, |
| 874 | require_plan: true, |
| 875 | plan_approved: false, |
| 876 | wip_sha: None, |
| 877 | pushed_sha: None, |
| 878 | final_diff: None, |
| 879 | commit_message: None, |
| 880 | issue_number: None, |
| 881 | plan_md: None, |
| 882 | stop_requested: false, |
| 883 | } |
| 884 | } |
| 885 | |
| 886 | fn ui_event(seq: i64, kind: &str, body: serde_json::Value) -> Event { |
| 887 | Event { id: seq, task_id: 1, seq, ts: 0, kind: kind.to_string(), body } |
| 888 | } |
| 889 | |
| 890 | #[test] |
| 891 | fn ui_question_card_option_forms_post_to_messages() { |
| 892 | let p = Pending::new( |
| 893 | PENDING_QUESTION, |
| 894 | Some("c1".into()), |
| 895 | serde_json::json!({ |
| 896 | "question": "Pick **one**?", |
| 897 | "options": ["alpha", "beta"], |
| 898 | "multi_select": true, |
| 899 | }), |
| 900 | ); |
| 901 | let html = render_cards(&ui_task(TaskStatus::NeedsInput, Some(p))).into_string(); |
| 902 | // One form per option, each posting its text to /messages. |
| 903 | assert!(html.contains("action=\"/tasks/1/messages\""), "messages action: {html}"); |
| 904 | assert!(html.contains("value=\"alpha\""), "alpha option: {html}"); |
| 905 | assert!(html.contains("value=\"beta\""), "beta option: {html}"); |
| 906 | assert!(html.contains("Waiting for you (question)"), "park marker: {html}"); |
| 907 | // Multi-select checkboxes (joined server-side) + free-text box. |
| 908 | assert!(html.contains("name=\"options\""), "checkboxes: {html}"); |
| 909 | assert!(html.contains("<textarea"), "free text: {html}"); |
| 910 | // Question text through the safe markdown subset. |
| 911 | assert!(html.contains("<strong>one</strong>"), "markdown: {html}"); |
| 912 | } |
| 913 | |
| 914 | #[test] |
| 915 | fn ui_plan_card_approve_and_changes_forms() { |
| 916 | let p = Pending::new( |
| 917 | PENDING_PLAN, |
| 918 | Some("c2".into()), |
| 919 | serde_json::json!({"plan_markdown": "## Plan\nDo **things** first."}), |
| 920 | ); |
| 921 | let html = render_cards(&ui_task(TaskStatus::NeedsInput, Some(p))).into_string(); |
| 922 | assert!(html.contains("action=\"/tasks/1/plan/approve\""), "approve: {html}"); |
| 923 | assert!(html.contains("action=\"/tasks/1/plan/changes\""), "changes: {html}"); |
| 924 | assert!(html.contains("Waiting for you (plan)"), "park marker: {html}"); |
| 925 | assert!(html.contains("<strong>things</strong>"), "plan markdown: {html}"); |
| 926 | } |
| 927 | |
| 928 | #[test] |
| 929 | fn ui_review_card_diff_classes_and_actions() { |
| 930 | let mut t = ui_task(TaskStatus::Review, None); |
| 931 | t.summary = Some("Changed the greeting.".to_string()); |
| 932 | t.commit_message = Some("notes: change greeting\n\nBody.".to_string()); |
| 933 | t.final_diff = Some( |
| 934 | "@@ -1,2 +1,2 @@\n ctx\n-old line\n+new line\n more\n".to_string(), |
| 935 | ); |
| 936 | let html = render_cards(&t).into_string(); |
| 937 | assert!(html.contains("class=\"del\""), "removed line class: {html}"); |
| 938 | assert!(html.contains("class=\"add\""), "added line class: {html}"); |
| 939 | assert!(html.contains("action=\"/tasks/1/approve\""), "approve: {html}"); |
| 940 | assert!(html.contains("action=\"/tasks/1/discard\""), "discard: {html}"); |
| 941 | assert!(html.contains("Approve & push"), "approve label: {html}"); |
| 942 | assert!(html.contains("notes: change greeting"), "commit message: {html}"); |
| 943 | assert!(html.contains("Changed the greeting."), "summary: {html}"); |
| 944 | } |
| 945 | |
| 946 | #[test] |
| 947 | fn ui_assistant_and_question_xss_escaped() { |
| 948 | let events = vec)"})), |
| 951 | ui_event(2, EVENT_USER_MESSAGE, serde_json::json!({"text": "<b>hi</b>"})), |
| 952 | ]; |
| 953 | let html = render_timeline_events(&events).into_string(); |
| 954 | assert!(!html.contains("<script"), "no script element: {html}"); |
| 955 | assert!(!html.contains("javascript:"), "no js scheme: {html}"); |
| 956 | assert!(!html.contains("<a"), "no anchor: {html}"); |
| 957 | assert!(html.contains("<script>"), "raw html escaped: {html}"); |
| 958 | assert!(html.contains("<b>hi</b>"), "user text escaped: {html}"); |
| 959 | // A hostile question payload is escaped the same way. |
| 960 | let p = Pending::new( |
| 961 | PENDING_QUESTION, |
| 962 | Some("c9".into()), |
| 963 | serde_json::json!({"question": "<img src=x onerror=alert(1)>?", "options": []}), |
| 964 | ); |
| 965 | let card = render_cards(&ui_task(TaskStatus::NeedsInput, Some(p))).into_string(); |
| 966 | assert!(!card.contains("<img"), "no img: {card}"); |
| 967 | assert!(card.contains("<img"), "escaped: {card}"); |
| 968 | } |
| 969 | |
| 970 | #[test] |
| 971 | fn ui_tool_call_result_merge_and_caps() { |
| 972 | let args = serde_json::json!({"path": "notes/file.txt"}).to_string(); |
| 973 | let events = vec![ |
| 974 | ui_event(0, EVENT_TOOL_CALL, serde_json::json!({"name": "read_file", "args": args})), |
| 975 | ui_event(1, EVENT_TOOL_RESULT, serde_json::json!({"name": "read_file", "truncated": false, "result": "hello\n"})), |
| 976 | // Orphan result (no preceding same-name call) renders on its own. |
| 977 | ui_event(2, EVENT_TOOL_RESULT, serde_json::json!({"name": "build", "truncated": true, "result": "log tail"})), |
| 978 | // A still-running call (no result follows) shows the chip. |
| 979 | ui_event(3, EVENT_TOOL_CALL, serde_json::json!({"name": "run_tests", "args": "{}"})), |
| 980 | ]; |
| 981 | let html = render_timeline_events(&events).into_string(); |
| 982 | assert_eq!(html.matches("details class=\"tool\"").count(), 3, "merged + orphan + running: {html}"); |
| 983 | assert!(html.contains("▸ read_file"), "chip: {html}"); |
| 984 | assert!(html.contains("hello"), "merged result inside: {html}"); |
| 985 | assert!(html.contains("(running…)"), "pending call: {html}"); |
| 986 | assert!(html.contains("[result truncated]"), "flag surfaced: {html}"); |
| 987 | // Long args cap the chip but keep a longer escaped copy inside. |
| 988 | let long_args = "x".repeat(200); |
| 989 | let events = vec![ui_event(0, EVENT_TOOL_CALL, serde_json::json!({"name": "build", "args": long_args}))]; |
| 990 | let html = render_timeline_events(&events).into_string(); |
| 991 | assert!(html.contains("…"), "chip capped: {html}"); |
| 992 | assert!(html.contains(&"x".repeat(200)), "full args inside: {html}"); |
| 993 | } |
| 994 | |
| 995 | #[test] |
| 996 | fn ui_todos_panel_only() { |
| 997 | let events = vec![ui_event( |
| 998 | 0, |
| 999 | EVENT_TODOS, |
| 1000 | serde_json::json!({"items": [{"text": "edit greeting", "status": "in_progress"}]}), |
| 1001 | )]; |
| 1002 | let timeline = render_timeline_events(&events).into_string(); |
| 1003 | assert!(!timeline.contains("edit greeting"), "todos not in timeline: {timeline}"); |
| 1004 | let mut t = ui_task(TaskStatus::Running, None); |
| 1005 | t.todos_json = Some( |
| 1006 | serde_json::to_string(&[ |
| 1007 | crate::models::TodoItem { text: "edit greeting".to_string(), status: "in_progress".to_string() }, |
| 1008 | crate::models::TodoItem { text: "run build".to_string(), status: "done".to_string() }, |
| 1009 | ]) |
| 1010 | .unwrap(), |
| 1011 | ); |
| 1012 | let panel = render_panel(&t, "vayun-mathur/Modern-Apps").into_string(); |
| 1013 | assert!(panel.contains("edit greeting"), "todo in panel: {panel}"); |
| 1014 | assert!(panel.contains("▶"), "in-progress marker: {panel}"); |
| 1015 | assert!(panel.contains("run build"), "done todo: {panel}"); |
| 1016 | assert!(panel.contains("git fetch origin agent/1-test-task"), "fetch line: {panel}"); |
| 1017 | } |
| 1018 | |
| 1019 | #[test] |
| 1020 | fn ui_pages_have_no_inline_script_or_style() { |
| 1021 | let t = ui_task(TaskStatus::Running, None); |
| 1022 | let task_html = render_task_page(&t, &[], false, "vayun-mathur/Modern-Apps").into_string(); |
| 1023 | assert!(task_html.contains("<script src=\"/static/app.js\""), "bundled script: {task_html}"); |
| 1024 | assert_eq!(task_html.matches("<script").count(), 1, "no inline script: {task_html}"); |
| 1025 | assert!(!task_html.contains("<style"), "no style block: {task_html}"); |
| 1026 | assert!(!task_html.contains("style="), "no inline style: {task_html}"); |
| 1027 | assert!(task_html.contains("Stop"), "stop while running: {task_html}"); |
| 1028 | let dash = render_dashboard_page(&[], false).into_string(); |
| 1029 | assert_eq!(dash.matches("<script").count(), 1, "dashboard script: {dash}"); |
| 1030 | assert!(!dash.contains("<style"), "dashboard style: {dash}"); |
| 1031 | // Composer follow-up placeholder on succeeded tasks. |
| 1032 | let done_html = render_task_page( |
| 1033 | &ui_task(TaskStatus::Succeeded, None), |
| 1034 | &[], |
| 1035 | false, |
| 1036 | "vayun-mathur/Modern-Apps", |
| 1037 | ) |
| 1038 | .into_string(); |
| 1039 | assert!(done_html.contains("Follow-up"), "follow-up composer: {done_html}"); |
| 1040 | // Parked cards exist for the textless kinds too. |
| 1041 | for kind in [PENDING_CHAT, PENDING_BUDGET] { |
| 1042 | let p = Pending::new(kind, None, serde_json::json!({"message": "m"})); |
| 1043 | let card = render_cards(&ui_task(TaskStatus::NeedsInput, Some(p))).into_string(); |
| 1044 | assert!(card.contains("Waiting for you"), "explanation for {kind}: {card}"); |
| 1045 | } |
| 1046 | // Diff viewer classes escape hostile content. |
| 1047 | let diff = render_diff_lines("+<script>alert(1)</script>\n-foo").into_string(); |
| 1048 | assert!(!diff.contains("<script"), "diff escaped: {diff}"); |
| 1049 | assert!(diff.contains("class=\"add\"") && diff.contains("class=\"del\""), "classes: {diff}"); |
| 1050 | } |
| 1051 | |
| 1052 | #[test] |
| 1053 | fn ui_dashboard_grouping_and_title_count() { |
| 1054 | let mut needs_q = ui_task(TaskStatus::NeedsInput, Some(Pending::new( |
| 1055 | PENDING_QUESTION, Some("c1".into()), |
| 1056 | serde_json::json!({"question": "Which color?"}), |
| 1057 | ))); |
| 1058 | needs_q.id = 1; |
| 1059 | let mut review = ui_task(TaskStatus::Review, None); |
| 1060 | review.id = 2; |
| 1061 | review.summary = Some("All done here.".to_string()); |
| 1062 | let mut running = ui_task(TaskStatus::Running, None); |
| 1063 | running.id = 3; |
| 1064 | let mut succeeded = ui_task(TaskStatus::Succeeded, None); |
| 1065 | succeeded.id = 4; |
| 1066 | let tasks = vec![needs_q, review, running, succeeded]; |
| 1067 | assert_eq!(dashboard_title(0), "agentd"); |
| 1068 | assert_eq!(dashboard_title(2), "(2) agentd"); |
| 1069 | let html = render_dashboard_page(&tasks, false).into_string(); |
| 1070 | assert!(html.contains("<title>(2) agentd</title>"), "title count: {html}"); |
| 1071 | assert!(html.contains("Needs you (2)"), "section first: {html}"); |
| 1072 | let needs_pos = html.find("Needs you").unwrap(); |
| 1073 | let running_pos = html.find(">Running<").unwrap(); |
| 1074 | let recent_pos = html.find(">Recent<").unwrap(); |
| 1075 | assert!(needs_pos < running_pos && running_pos < recent_pos, "section order: {html}"); |
| 1076 | assert!(html.contains("question: Which color?"), "question reason: {html}"); |
| 1077 | assert!(html.contains("review: All done here."), "review reason: {html}"); |
| 1078 | } |
| 1079 | |
| 1080 | #[test] |
| 1081 | fn ui_status_events_capped_and_muted() { |
| 1082 | let events = vec![ |
| 1083 | ui_event(0, EVENT_STATUS, serde_json::json!({"message": "task queued"})), |
| 1084 | ui_event(1, "mystery_kind", serde_json::json!({"x": 1})), |
| 1085 | ]; |
| 1086 | let html = render_timeline_events(&events).into_string(); |
| 1087 | assert!(html.contains("status-line"), "muted status line: {html}"); |
| 1088 | assert!(html.contains("task queued"), "message kept: {html}"); |
| 1089 | } |
| 1090 | } |