| 1 | """Tests for the HTML emit renderer.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import tempfile |
| 6 | import unittest |
| 7 | from html.parser import HTMLParser |
| 8 | from pathlib import Path |
| 9 | |
| 10 | import last30days as cli |
| 11 | from lib import html_render, schema |
| 12 | |
| 13 | |
| 14 | def _report(topic: str, cluster_titles: list[str]) -> schema.Report: |
| 15 | items: list[schema.SourceItem] = [] |
| 16 | candidates: list[schema.Candidate] = [] |
| 17 | clusters: list[schema.Cluster] = [] |
| 18 | |
| 19 | for index, title in enumerate(cluster_titles, start=1): |
| 20 | item = schema.SourceItem( |
| 21 | item_id=f"item-{index}", |
| 22 | source="grounding", |
| 23 | title=title, |
| 24 | body=f"Body for {title}", |
| 25 | url=f"https://example.test/{index}", |
| 26 | container="example.test", |
| 27 | published_at="2026-04-20", |
| 28 | date_confidence="high", |
| 29 | engagement={"views": index * 100}, |
| 30 | snippet=f"Snippet for {title}", |
| 31 | ) |
| 32 | candidate = schema.Candidate( |
| 33 | candidate_id=f"candidate-{index}", |
| 34 | item_id=item.item_id, |
| 35 | source="grounding", |
| 36 | title=title, |
| 37 | url=item.url, |
| 38 | snippet=item.snippet, |
| 39 | subquery_labels=["primary"], |
| 40 | native_ranks={"primary:grounding": index}, |
| 41 | local_relevance=0.9, |
| 42 | freshness=80, |
| 43 | engagement=50, |
| 44 | source_quality=1.0, |
| 45 | rrf_score=0.5, |
| 46 | final_score=90 - index, |
| 47 | sources=["grounding"], |
| 48 | source_items=[item], |
| 49 | ) |
| 50 | cluster = schema.Cluster( |
| 51 | cluster_id=f"cluster-{index}", |
| 52 | title=title, |
| 53 | candidate_ids=[candidate.candidate_id], |
| 54 | representative_ids=[candidate.candidate_id], |
| 55 | sources=["grounding"], |
| 56 | score=90 - index, |
| 57 | ) |
| 58 | items.append(item) |
| 59 | candidates.append(candidate) |
| 60 | clusters.append(cluster) |
| 61 | |
| 62 | return schema.Report( |
| 63 | topic=topic, |
| 64 | range_from="2026-03-30", |
| 65 | range_to="2026-04-29", |
| 66 | generated_at="2026-04-29T12:00:00+00:00", |
| 67 | provider_runtime=schema.ProviderRuntime( |
| 68 | reasoning_provider="local", |
| 69 | planner_model="mock-planner", |
| 70 | rerank_model="mock-rerank", |
| 71 | ), |
| 72 | query_plan=schema.QueryPlan( |
| 73 | intent="research", |
| 74 | freshness_mode="balanced_recent", |
| 75 | cluster_mode="story", |
| 76 | raw_topic=topic, |
| 77 | subqueries=[ |
| 78 | schema.SubQuery( |
| 79 | label="primary", |
| 80 | search_query=topic, |
| 81 | ranking_query=topic, |
| 82 | sources=["grounding"], |
| 83 | ) |
| 84 | ], |
| 85 | source_weights={"grounding": 1.0}, |
| 86 | ), |
| 87 | clusters=clusters, |
| 88 | ranked_candidates=candidates, |
| 89 | items_by_source={"grounding": items}, |
| 90 | errors_by_source={}, |
| 91 | artifacts={"pre_research_flags_present": True}, |
| 92 | ) |
| 93 | |
| 94 | |
| 95 | def _assert_parses(test_case: unittest.TestCase, html: str) -> None: |
| 96 | parser = HTMLParser() |
| 97 | parser.feed(html) |
| 98 | parser.close() |
| 99 | test_case.assertIn("</html>", html) |
| 100 | |
| 101 | |
| 102 | class HtmlRenderSnapshotTests(unittest.TestCase): |
| 103 | def test_rich_cluster_fixture_snapshot(self): |
| 104 | rendered = html_render.render_html( |
| 105 | _report("AI agent frameworks", ["OpenClaw ships containers", "Skills marketplace grows"]) |
| 106 | ) |
| 107 | snapshot_markers = [ |
| 108 | "<!DOCTYPE html>", |
| 109 | "<title>last30days · AI agent frameworks</title>", |
| 110 | '<div class="badge"><span class="accent">🌐</span> ' |
| 111 | "last30days · AI agent frameworks · Mar 30 to Apr 29, 2026 · v", |
| 112 | '<div class="meta">2026-03-30 to 2026-04-29', |
| 113 | '<div class="engine-footer"><pre>---\n✅ All agents reported back!', |
| 114 | 'Generated 2026-04-29 by /last30days v', |
| 115 | '<span class="rerun">/last30days AI agent frameworks</span>', |
| 116 | ] |
| 117 | for marker in snapshot_markers: |
| 118 | self.assertIn(marker, rendered) |
| 119 | self.assertNotIn("EVIDENCE FOR SYNTHESIS", rendered) |
| 120 | self.assertNotIn("END OF last30days CANONICAL OUTPUT", rendered) |
| 121 | |
| 122 | def test_thin_cluster_fixture_snapshot(self): |
| 123 | rendered = html_render.render_html(_report("obscure topic", [])) |
| 124 | snapshot_markers = [ |
| 125 | "<title>last30days · obscure topic</title>", |
| 126 | "no active sources", |
| 127 | "topic: obscure topic", |
| 128 | ] |
| 129 | for marker in snapshot_markers: |
| 130 | self.assertIn(marker, rendered) |
| 131 | |
| 132 | def test_comparison_mode_snapshot(self): |
| 133 | reports = [ |
| 134 | ("OpenClaw", _report("OpenClaw", ["Containers"])), |
| 135 | ("Hermes", _report("Hermes", ["Memory"])), |
| 136 | ] |
| 137 | rendered = html_render.render_html_comparison(reports) |
| 138 | snapshot_markers = [ |
| 139 | "<title>last30days · OpenClaw vs Hermes</title>", |
| 140 | 'comparing 2: OpenClaw, Hermes</div>', |
| 141 | '<div class="meta">2026-03-30 to 2026-04-29', |
| 142 | '<span class="rerun">/last30days OpenClaw vs Hermes</span>', |
| 143 | ] |
| 144 | for marker in snapshot_markers: |
| 145 | self.assertIn(marker, rendered) |
| 146 | |
| 147 | |
| 148 | class HtmlRenderBehaviorTests(unittest.TestCase): |
| 149 | def test_prose_label_promotion(self): |
| 150 | md = html_render._promote_prose_labels("What I learned:") |
| 151 | rendered = html_render._markdown_to_html(md) |
| 152 | self.assertIn("<h2>What I learned</h2>", rendered) |
| 153 | self.assertNotIn("What I learned:", rendered) |
| 154 | |
| 155 | def test_claude_code_list_free_markers_render_as_lists(self): |
| 156 | # On Claude Code the chat report writes `1\.` and `• ` instead of |
| 157 | # markdown lists; the export copies that text verbatim. |
| 158 | md = "KEY PATTERNS:\n1\\. First, per [CNN](https://example.test/a)\n2\\. Second\n\nAsk me:\n• Go deeper\n• Compare" |
| 159 | rendered = html_render._markdown_to_html(md) |
| 160 | self.assertIn("<ol>\n<li>First, per", rendered) |
| 161 | self.assertIn("<li>Second</li>\n</ol>", rendered) |
| 162 | self.assertIn("<ul>\n<li>Go deeper</li>\n<li>Compare</li>\n</ul>", rendered) |
| 163 | self.assertNotIn("\\.", rendered) |
| 164 | self.assertNotIn("•", rendered) |
| 165 | |
| 166 | def test_hard_break_backslashes_from_the_terminal_report_are_dropped(self): |
| 167 | # In the Claude Code terminal each pseudo-list line but the last ends in |
| 168 | # a `\\` hard break; the export keeps the lists and drops the backslash. |
| 169 | md = ( |
| 170 | "KEY PATTERNS from the research:\\\n" |
| 171 | "1\\. First, per [r/x](https://reddit.com/r/x)\\\n" |
| 172 | "2\\. Second\n\n" |
| 173 | "Some things I can help with:\\\n" |
| 174 | "• Go deeper\\\n" |
| 175 | "• Compare" |
| 176 | ) |
| 177 | rendered = html_render._markdown_to_html(md) |
| 178 | self.assertIn("<p>KEY PATTERNS from the research:</p>", rendered) |
| 179 | self.assertIn('<li>First, per <a href="https://reddit.com/r/x"', rendered) |
| 180 | self.assertIn("<li>Second</li>\n</ol>", rendered) |
| 181 | self.assertIn("<ul>\n<li>Go deeper</li>\n<li>Compare</li>\n</ul>", rendered) |
| 182 | self.assertNotIn("\\", rendered) |
| 183 | |
| 184 | def test_terminal_patterns_label_with_a_hard_break_still_becomes_a_heading(self): |
| 185 | synthesis = ( |
| 186 | "What I learned:\\\n" |
| 187 | "Teams ship agents.\n\n" |
| 188 | "KEY PATTERNS from the research:\\\n" |
| 189 | "1\\. First\\\n" |
| 190 | "2\\. Second" |
| 191 | ) |
| 192 | rendered = html_render.render_html( |
| 193 | _report("AI agent frameworks", ["One"]), synthesis_md=synthesis |
| 194 | ) |
| 195 | self.assertIn("Key patterns from the research</h2>", rendered) |
| 196 | self.assertIn("What I learned</h2>", rendered) |
| 197 | self.assertNotIn("KEY PATTERNS from the research:", rendered) |
| 198 | |
| 199 | def test_an_escaped_trailing_backslash_is_kept(self): |
| 200 | rendered = html_render._markdown_to_html("Path is C:\\\\") |
| 201 | self.assertIn("\\", rendered) |
| 202 | |
| 203 | def test_each_story_keeps_its_own_pulled_quote(self): |
| 204 | md = ( |
| 205 | "**North West takes the stage** - Fans say she sounds like her father.\n" |
| 206 | '> "Ofc shes literally him😭" 🎵 @haktimel2 on TikTok · 825,451 likes\n' |
| 207 | "\n" |
| 208 | "**The album debate** - Reddit is less convinced.\n" |
| 209 | "\n" |
| 210 | '> "Internet feelings vs reality." 🟠 u/CappaccinoJay on r/hiphopheads · 1,315 upvotes\n' |
| 211 | ) |
| 212 | rendered = html_render._markdown_to_html(md) |
| 213 | self.assertEqual(2, rendered.count("<blockquote>")) |
| 214 | self.assertIn( |
| 215 | "<blockquote>"Ofc shes literally him😭" 🎵 @haktimel2 on TikTok · 825,451 likes</blockquote>", |
| 216 | rendered, |
| 217 | ) |
| 218 | self.assertIn( |
| 219 | "<blockquote>"Internet feelings vs reality." 🟠 u/CappaccinoJay" |
| 220 | " on r/hiphopheads · 1,315 upvotes</blockquote>", |
| 221 | rendered, |
| 222 | ) |
| 223 | first_quote = rendered.index("<blockquote>") |
| 224 | self.assertLess(rendered.index("North West takes the stage"), first_quote) |
| 225 | self.assertLess(first_quote, rendered.index("The album debate")) |
| 226 | self.assertLess(rendered.index("The album debate"), rendered.rindex("<blockquote>")) |
| 227 | |
| 228 | def test_pulled_quote_text_renders_literally(self): |
| 229 | md = ( |
| 230 | '> "a > b, 5 * 4 | see https://example.test/x?a=1&b=2 <script>" ' |
| 231 | "🟠 u/ada on r/math · 12 upvotes" |
| 232 | ) |
| 233 | rendered = html_render._markdown_to_html(md) |
| 234 | self.assertEqual( |
| 235 | "<blockquote>"a > b, 5 * 4 | see https://example.test/x?a=1&b=2" |
| 236 | " <script>" 🟠 u/ada on r/math · 12 upvotes</blockquote>", |
| 237 | rendered.strip(), |
| 238 | ) |
| 239 | for tag in ("<a ", "<em>", "<table", "<script>"): |
| 240 | self.assertNotIn(tag, rendered) |
| 241 | |
| 242 | def test_list_free_markers_inside_code_are_left_alone(self): |
| 243 | rendered = html_render._markdown_to_html("```\n• keep\n1\\. keep\n```") |
| 244 | self.assertIn("• keep", rendered) |
| 245 | self.assertIn("1\\. keep", rendered) |
| 246 | |
| 247 | def test_invitation_strip(self): |
| 248 | md = "---\nI'm now an expert on OpenClaw. Some things you could ask:\n\nJust ask." |
| 249 | self.assertNotIn("I'm now an expert", html_render._strip_invitation(md)) |
| 250 | |
| 251 | def test_evidence_block_strip(self): |
| 252 | md = "keep\n<!-- EVIDENCE FOR SYNTHESIS -->\nsecret\n<!-- END EVIDENCE FOR SYNTHESIS -->" |
| 253 | stripped = html_render._strip_evidence_block(md) |
| 254 | self.assertIn("keep", stripped) |
| 255 | self.assertNotIn("EVIDENCE FOR SYNTHESIS", stripped) |
| 256 | self.assertNotIn("secret", stripped) |
| 257 | |
| 258 | def test_engine_footer_wrapping_preserves_tree(self): |
| 259 | md = ( |
| 260 | "<!-- PASS-THROUGH FOOTER: emit verbatim. -->\n" |
| 261 | "✅ All agents reported back!\n" |
| 262 | "├─ 🔵 X: 2 posts\n" |
| 263 | "└─ 🌐 Web: 1 result\n" |
| 264 | "<!-- END PASS-THROUGH FOOTER -->" |
| 265 | ) |
| 266 | body = html_render._wrap_engine_footer(html_render._markdown_to_html(md)) |
| 267 | self.assertIn('<div class="engine-footer"><pre>✅ All agents reported back!', body) |
| 268 | self.assertIn("├─ 🔵 X: 2 posts", body) |
| 269 | self.assertIn("└─ 🌐 Web: 1 result", body) |
| 270 | |
| 271 | def test_fenced_engine_footer_wrapping_preserves_tree(self): |
| 272 | md = ( |
| 273 | "```text\n" |
| 274 | "---\n" |
| 275 | "✅ All agents reported back!\n" |
| 276 | "├─ 🔵 X: 2 posts\n" |
| 277 | "└─ 🌐 Web: 1 result\n" |
| 278 | "---\n" |
| 279 | "```" |
| 280 | ) |
| 281 | body = html_render._wrap_engine_footer(html_render._markdown_to_html(md)) |
| 282 | self.assertIn('<div class="engine-footer"><pre>---\n✅ All agents reported back!', body) |
| 283 | self.assertIn("├─ 🔵 X: 2 posts", body) |
| 284 | self.assertIn("└─ 🌐 Web: 1 result", body) |
| 285 | |
| 286 | def test_fenced_footer_match_does_not_swallow_an_earlier_text_block(self): |
| 287 | md = ( |
| 288 | "```text\n---\nquoted by the synthesis\n---\n```\n\n" |
| 289 | "Prose between the blocks.\n\n" |
| 290 | "```text\n---\n✅ All agents reported back!\n└─ 🌐 Web: 1 result\n---\n```" |
| 291 | ) |
| 292 | matches = list(html_render.FENCED_ENGINE_FOOTER_PATTERN.finditer(md)) |
| 293 | self.assertEqual(len(matches), 1) |
| 294 | self.assertNotIn("Prose between the blocks.", matches[0].group(0)) |
| 295 | self.assertNotIn("quoted by the synthesis", matches[0].group(0)) |
| 296 | |
| 297 | protected, footers = html_render._protect_engine_footers(md) |
| 298 | self.assertIn("Prose between the blocks.", protected) |
| 299 | self.assertEqual(len(footers), 1) |
| 300 | |
| 301 | def test_colophon_contains_topic_and_rerun_command(self): |
| 302 | rendered = html_render.render_html(_report("AI agent frameworks", [])) |
| 303 | self.assertIn("topic: AI agent frameworks", rendered) |
| 304 | self.assertIn("/last30days AI agent frameworks", rendered) |
| 305 | |
| 306 | def test_parseability(self): |
| 307 | _assert_parses(self, html_render.render_html(_report("parse me", ["One"]))) |
| 308 | |
| 309 | def test_self_containedness(self): |
| 310 | rendered = html_render.render_html(_report("self contained", [])) |
| 311 | self.assertNotIn("<script", rendered.lower()) |
| 312 | self.assertEqual(0, rendered.count('rel="stylesheet"')) |
| 313 | self.assertNotIn("fonts.googleapis.com", rendered) |
| 314 | self.assertNotIn("fonts.gstatic.com", rendered) |
| 315 | self.assertNotIn('rel="preconnect"', rendered) |
| 316 | |
| 317 | def test_markdown_links_convert(self): |
| 318 | rendered = html_render._markdown_to_html("[name](https://example.test/path)") |
| 319 | self.assertIn( |
| 320 | '<a href="https://example.test/path" rel="noopener noreferrer">name</a>', |
| 321 | rendered, |
| 322 | ) |
| 323 | |
| 324 | def test_markdown_links_reject_javascript_scheme(self): |
| 325 | """A `[label](javascript:...)` link must NOT render as a clickable href. |
| 326 | |
| 327 | The HTML artifact is opened in a browser, so allowing arbitrary URL |
| 328 | schemes turns synthesized markdown into a stored-XSS surface. External |
| 329 | sources (Reddit, X, HN, etc.) can plant such links and the LLM may |
| 330 | carry them through synthesis; the renderer is the last gate. |
| 331 | """ |
| 332 | for payload in ( |
| 333 | "[click](javascript:alert(1))", |
| 334 | "[click](JAVASCRIPT:alert(1))", |
| 335 | "[click](vbscript:alert(1))", |
| 336 | "[click](file:///etc/passwd)", |
| 337 | ): |
| 338 | rendered = html_render._markdown_to_html(payload) |
| 339 | self.assertNotIn("<a ", rendered, msg=f"payload accepted: {payload}") |
| 340 | self.assertNotIn("href=", rendered, msg=f"payload accepted: {payload}") |
| 341 | # The label still surfaces as plain text so context isn't lost. |
| 342 | self.assertIn("click", rendered, msg=f"label dropped: {payload}") |
| 343 | |
| 344 | def test_markdown_links_reject_data_uri(self): |
| 345 | rendered = html_render._markdown_to_html( |
| 346 | "[click](data:text/html,<svg/onload=alert(1)>)" |
| 347 | ) |
| 348 | self.assertNotIn("<a ", rendered) |
| 349 | self.assertNotIn("href=", rendered) |
| 350 | # The label still surfaces as plain text so context isn't lost. |
| 351 | self.assertIn("click", rendered) |
| 352 | |
| 353 | def test_markdown_links_strip_leading_whitespace_javascript(self): |
| 354 | """Leading whitespace in the URL must not let a `javascript:` payload |
| 355 | bypass the scheme check (browsers strip leading whitespace before |
| 356 | parsing the scheme).""" |
| 357 | rendered = html_render._markdown_to_html("[click](\tjavascript:alert(1))") |
| 358 | # `[^)\\s]+` already rejects whitespace inside the URL, so the regex |
| 359 | # doesn't match and the label is left as plain text. The point of the |
| 360 | # assertion is to pin that behavior: NO `<a href>` is produced. |
| 361 | self.assertNotIn("<a ", rendered) |
| 362 | self.assertNotIn("href=", rendered) |
| 363 | |
| 364 | def test_meta_marker_escapes_payload_through_pipeline(self): |
| 365 | """A META marker carrying markup must not render as live HTML. |
| 366 | |
| 367 | The marker is exempted from the comment-strip pass and promoted into a |
| 368 | <div class="meta">. Its text can come from LLM-synthesized content |
| 369 | derived from untrusted source bodies, so a crafted |
| 370 | `<!-- META: <img src=x onerror=...> -->` must be escaped, not rendered. |
| 371 | """ |
| 372 | md = "intro\n\n<!-- META: <img src=x onerror=alert(1)> -->\n\nmore" |
| 373 | body = html_render._markdown_to_html(md) |
| 374 | body = html_render._wrap_engine_footer(body) |
| 375 | body = html_render._promote_meta_marker(body) |
| 376 | self.assertNotIn("<img", body) |
| 377 | self.assertIn("<img src=x onerror=alert(1)>", body) |
| 378 | |
| 379 | def test_meta_marker_escapes_raw_fallback(self): |
| 380 | """The raw (unescaped) META fallback path must also escape its payload.""" |
| 381 | body = html_render._promote_meta_marker( |
| 382 | "<!-- META: <img src=x onerror=alert(1)> -->" |
| 383 | ) |
| 384 | self.assertNotIn("<img", body) |
| 385 | self.assertEqual( |
| 386 | body, '<div class="meta"><img src=x onerror=alert(1)></div>' |
| 387 | ) |
| 388 | |
| 389 | def test_meta_marker_preserves_plain_text(self): |
| 390 | """Legitimate date/source-name markers render unchanged (no double-escape).""" |
| 391 | body = html_render._promote_meta_marker( |
| 392 | "<!-- META: 2026-01-01 to 2026-01-31 · reddit, x -->" |
| 393 | ) |
| 394 | self.assertEqual( |
| 395 | body, |
| 396 | '<div class="meta">2026-01-01 to 2026-01-31 · reddit, x</div>', |
| 397 | ) |
| 398 | |
| 399 | def test_markdown_links_allow_relative_url(self): |
| 400 | rendered = html_render._markdown_to_html("[home](/path?x=1#section)") |
| 401 | self.assertIn( |
| 402 | '<a href="/path?x=1#section" rel="noopener noreferrer">home</a>', |
| 403 | rendered, |
| 404 | ) |
| 405 | |
| 406 | def test_markdown_links_allow_mailto(self): |
| 407 | rendered = html_render._markdown_to_html("[mail](mailto:a@example.com)") |
| 408 | self.assertIn( |
| 409 | '<a href="mailto:a@example.com" rel="noopener noreferrer">mail</a>', |
| 410 | rendered, |
| 411 | ) |
| 412 | |
| 413 | def test_no_file_header_h1(self): |
| 414 | rendered = html_render.render_html(_report("AI agent frameworks", ["One"])) |
| 415 | self.assertNotIn("<h1>last30days v", rendered) |
| 416 | |
| 417 | def test_no_safety_note(self): |
| 418 | rendered = html_render.render_html(_report("AI agent frameworks", ["One"])) |
| 419 | self.assertNotIn("Safety note", rendered) |
| 420 | |
| 421 | def test_synthesis_md_embedded(self): |
| 422 | synthesis = "**Test brief** - body content per [@example](https://example.com)" |
| 423 | rendered = html_render.render_html( |
| 424 | _report("AI agent frameworks", ["One"]), |
| 425 | synthesis_md=synthesis, |
| 426 | ) |
| 427 | self.assertIn("<strong>Test brief</strong> - body content per", rendered) |
| 428 | self.assertIn( |
| 429 | '<a href="https://example.com" rel="noopener noreferrer">@example</a>', |
| 430 | rendered, |
| 431 | ) |
| 432 | metadata_index = rendered.index('<div class="meta">') |
| 433 | synthesis_index = rendered.index("<strong>Test brief</strong>") |
| 434 | footer_index = rendered.index('<div class="engine-footer">') |
| 435 | self.assertLess(metadata_index, synthesis_index) |
| 436 | self.assertLess(synthesis_index, footer_index) |
| 437 | |
| 438 | def test_warnings_excluded_from_html_artifact(self): |
| 439 | """Data quality warnings must NOT appear in the shareable HTML. |
| 440 | |
| 441 | Recipients of a shared HTML brief don't have context to act on |
| 442 | warnings about pre-flight resolution / engine state. The HTML is the |
| 443 | artifact; warnings stay in the engine's stderr logs where the |
| 444 | generator (not the recipient) sees them. |
| 445 | """ |
| 446 | report = _report("OpenClaw", ["Containers"]) |
| 447 | report.artifacts["pre_research_flags_present"] = False |
| 448 | report.artifacts["plan_source"] = "deterministic" |
| 449 | report.warnings.append("Brave quota exhausted") |
| 450 | rendered = html_render.render_html(report) |
| 451 | # Warning text variations must all be absent from the artifact. |
| 452 | self.assertNotIn("Data quality note", rendered) |
| 453 | self.assertNotIn("Brave quota exhausted", rendered) |
| 454 | self.assertNotIn("DEGRADED RUN WARNING", rendered) |
| 455 | self.assertNotIn("Pre-Research Status", rendered) |
| 456 | # No blockquote at all in mock output - just badge + meta + footer + colophon |
| 457 | self.assertEqual(0, rendered.count("<blockquote>")) |
| 458 | |
| 459 | |
| 460 | SUGGESTIONS = ( |
| 461 | "- What is the real story behind the apology letter?\n" |
| 462 | "- Break down the BULLY tracklist reactions\n" |
| 463 | "- Compare how Reddit and X are reacting" |
| 464 | ) |
| 465 | EXPERT_INVITATIONS = { |
| 466 | "prompting": ( |
| 467 | "---\nI'm now an expert on product photos for Midjourney. What do you want to make? For example:\n" |
| 468 | f"{SUGGESTIONS}\n\n" |
| 469 | "Just describe your vision and I'll write a prompt you can paste straight into Midjourney." |
| 470 | ), |
| 471 | "recommendations": f"---\nI'm now an expert on kids skis. Want me to go deeper? For example:\n{SUGGESTIONS}", |
| 472 | "news": f"---\nI'm now an expert on Kanye West. Some things you could ask:\n{SUGGESTIONS}", |
| 473 | "general": f"---\nI'm now an expert on Kanye West. Some things I can help with:\n{SUGGESTIONS}", |
| 474 | } |
| 475 | COMPARISON_INVITATION = ( |
| 476 | "I've compared Cursor vs Windsurf using the latest community data. Some things you could ask:\n" |
| 477 | f"{SUGGESTIONS}" |
| 478 | ) |
| 479 | OLD_LINK_LINE = ( |
| 480 | "\n\nI have all the links to the 14 Reddit threads, 22 X posts, and 5 web articles I pulled from. Just ask." |
| 481 | ) |
| 482 | REPORT_BODY = ( |
| 483 | "What I learned:\n\n" |
| 484 | "**The apology letter** - fans are split, per [@example](https://example.com)\n\n" |
| 485 | "---\n\n" |
| 486 | "KEY PATTERNS from the research:\n" |
| 487 | "1. Closing pattern stays in the brief\n\n" |
| 488 | ) |
| 489 | |
| 490 | |
| 491 | def test_citation_url_keeps_balanced_parentheses(): |
| 492 | text = html_render._markdown_to_html( |
| 493 | "[Paper](https://example.test/wiki/Article_(journal)?lang=en&view=full)." |
| 494 | ) |
| 495 | assert 'href="https://example.test/wiki/Article_(journal)?lang=en&view=full"' in text |
| 496 | assert "</a>.</p>" in text |
| 497 | |
| 498 | |
| 499 | def test_nested_citation_keeps_full_destination_and_following_link(): |
| 500 | rendered = html_render.render_html( |
| 501 | _report("Paper search", ["One"]), |
| 502 | synthesis_md=( |
| 503 | "See [Paper](https://example.test/search?filter=(and(type:paper,year:2026))&view=full). " |
| 504 | "Then [Index](https://example.test/index)." |
| 505 | ), |
| 506 | ) |
| 507 | assert ( |
| 508 | '<p>See <a href="https://example.test/search?filter=(and(type:paper,year:2026))&view=full"' |
| 509 | ' rel="noopener noreferrer">Paper</a>. ' |
| 510 | 'Then <a href="https://example.test/index" rel="noopener noreferrer">Index</a>.</p>' |
| 511 | ) in rendered |
| 512 | |
| 513 | |
| 514 | def test_unclosed_citation_leaves_following_link_intact(): |
| 515 | text = html_render._markdown_to_html( |
| 516 | "[Draft](https://example.test/search?filter=(alpha) then [Index](https://example.test/index)." |
| 517 | ) |
| 518 | assert ( |
| 519 | "<p>[Draft](https://example.test/search?filter=(alpha) then " |
| 520 | '<a href="https://example.test/index" rel="noopener noreferrer">Index</a>.</p>' |
| 521 | ) in text |
| 522 | |
| 523 | |
| 524 | class InvitationStripTests(unittest.TestCase): |
| 525 | def test_comparison_invitation_does_not_discard_synthesis_prose(self): |
| 526 | synthesis = ( |
| 527 | "I've compared the changelogs across both projects.\n\n" |
| 528 | "## Compatibility details\n\n" |
| 529 | "Both retain the old API.\n\n" |
| 530 | + COMPARISON_INVITATION |
| 531 | ) |
| 532 | rendered = html_render.render_html_comparison( |
| 533 | [("App A", _report("App A", ["One"])), ("App B", _report("App B", ["Two"]))], |
| 534 | synthesis_md=synthesis, |
| 535 | ) |
| 536 | self.assertIn("I've compared the changelogs across both projects.", rendered) |
| 537 | self.assertIn("<h2>Compatibility details</h2>", rendered) |
| 538 | self.assertIn("Both retain the old API.", rendered) |
| 539 | self.assertNotIn("Some things you could ask", rendered) |
| 540 | |
| 541 | def test_old_reports_lose_each_expert_invitation(self): |
| 542 | for name, invitation in EXPERT_INVITATIONS.items(): |
| 543 | with self.subTest(shape=name): |
| 544 | stripped = html_render._strip_invitation(REPORT_BODY + invitation + OLD_LINK_LINE) |
| 545 | self.assertNotIn("I'm now an expert", stripped) |
| 546 | self.assertNotIn("apology letter?", stripped) |
| 547 | self.assertNotIn("Just ask.", stripped) |
| 548 | self.assertIn("Closing pattern stays in the brief", stripped) |
| 549 | |
| 550 | def test_old_comparison_report_loses_its_invitation(self): |
| 551 | stripped = html_render._strip_invitation(REPORT_BODY + COMPARISON_INVITATION + OLD_LINK_LINE) |
| 552 | self.assertNotIn("I've compared Cursor vs Windsurf", stripped) |
| 553 | self.assertNotIn("Just ask.", stripped) |
| 554 | self.assertIn("Closing pattern stays in the brief", stripped) |
| 555 | |
| 556 | def test_reports_ending_at_the_invitation_lose_each_shape(self): |
| 557 | shapes = {**EXPERT_INVITATIONS, "comparison": COMPARISON_INVITATION} |
| 558 | for name, invitation in shapes.items(): |
| 559 | with self.subTest(shape=name): |
| 560 | stripped = html_render._strip_invitation(REPORT_BODY + invitation + "\n") |
| 561 | self.assertNotIn("I'm now an expert", stripped) |
| 562 | self.assertNotIn("I've compared", stripped) |
| 563 | self.assertNotIn("apology letter?", stripped) |
| 564 | self.assertNotIn("Just describe your vision", stripped) |
| 565 | self.assertIn("Closing pattern stays in the brief", stripped) |
| 566 | |
| 567 | def test_body_rule_before_the_invitation_keeps_the_body(self): |
| 568 | stripped = html_render._strip_invitation(REPORT_BODY + EXPERT_INVITATIONS["general"]) |
| 569 | self.assertEqual(stripped, REPORT_BODY) |
| 570 | |
| 571 | def test_report_ending_at_the_invitation_renders_ending_at_the_footer(self): |
| 572 | rendered = html_render.render_html( |
| 573 | _report("Kanye West", ["One"]), |
| 574 | synthesis_md=REPORT_BODY + EXPERT_INVITATIONS["general"], |
| 575 | ) |
| 576 | self.assertNotIn("I'm now an expert", rendered) |
| 577 | self.assertNotIn("apology letter?", rendered) |
| 578 | self.assertIn("Closing pattern stays in the brief", rendered) |
| 579 | body = rendered.split('<div class="colophon">', 1)[0].rstrip() |
| 580 | self.assertIn("All agents reported back!", body) |
| 581 | self.assertTrue(body.endswith("---</pre></div>"), body[-200:]) |
| 582 | |
| 583 | def test_comparison_ending_at_the_invitation_renders_ending_at_the_footer(self): |
| 584 | rendered = html_render.render_html_comparison( |
| 585 | [("Cursor", _report("Cursor", ["One"])), ("Windsurf", _report("Windsurf", ["Two"]))], |
| 586 | synthesis_md=REPORT_BODY + COMPARISON_INVITATION, |
| 587 | ) |
| 588 | self.assertNotIn("I've compared", rendered) |
| 589 | self.assertNotIn("apology letter?", rendered) |
| 590 | self.assertIn("Closing pattern stays in the brief", rendered) |
| 591 | self.assertIn("All agents reported back!", rendered) |
| 592 | |
| 593 | def test_old_saved_report_renders_without_the_invitation(self): |
| 594 | rendered = html_render.render_html( |
| 595 | _report("Kanye West", ["One"]), |
| 596 | synthesis_md=REPORT_BODY + EXPERT_INVITATIONS["general"] + OLD_LINK_LINE, |
| 597 | ) |
| 598 | self.assertNotIn("I'm now an expert", rendered) |
| 599 | self.assertNotIn("Just ask.", rendered) |
| 600 | self.assertIn("<strong>The apology letter</strong>", rendered) |
| 601 | self.assertIn("Closing pattern stays in the brief", rendered) |
| 602 | self.assertIn('<div class="engine-footer">', rendered) |
| 603 | |
| 604 | |
| 605 | def test_report_blocks_after_a_list_render_outside_the_list(): |
| 606 | result = html_render._markdown_to_html( |
| 607 | "- First item\nFollow-up prose\n\n1. Ranked result\n🌐 last30days · today" |
| 608 | ) |
| 609 | assert "</ul>\n<p>Follow-up prose</p>" in result |
| 610 | assert '</ol>\n<div class="badge">' in result |
| 611 | |
| 612 | |
| 613 | class HtmlCliIntegrationTests(unittest.TestCase): |
| 614 | def test_parser_accepts_html_emit(self): |
| 615 | args = cli.build_parser().parse_args(["AI agents", "--emit=html"]) |
| 616 | self.assertEqual("html", args.emit) |
| 617 | |
| 618 | def test_synthesis_file_cli(self): |
| 619 | synthesis = "**Test brief** - body content per [@example](https://example.com)" |
| 620 | with tempfile.NamedTemporaryFile("w", encoding="utf-8", delete=False) as tmp: |
| 621 | tmp.write(synthesis) |
| 622 | tmp_path = tmp.name |
| 623 | try: |
| 624 | args = cli.build_parser().parse_args([ |
| 625 | "OpenClaw", |
| 626 | "--mock", |
| 627 | "--emit=html", |
| 628 | "--synthesis-file", |
| 629 | tmp_path, |
| 630 | ]) |
| 631 | rendered = cli.emit_output( |
| 632 | _report("OpenClaw", ["Containers"]), |
| 633 | args.emit, |
| 634 | synthesis_md=cli.read_synthesis_file(args.synthesis_file), |
| 635 | ) |
| 636 | finally: |
| 637 | Path(tmp_path).unlink(missing_ok=True) |
| 638 | self.assertIn("<strong>Test brief</strong> - body content per", rendered) |
| 639 | |
| 640 | def test_save_output_uses_raw_html_extension_and_suffix(self): |
| 641 | report = _report("AI Agent Frameworks", []) |
| 642 | with self.subTest("plain"): |
| 643 | path = cli.compute_save_path_display("/tmp", report.topic, "", "html") |
| 644 | self.assertTrue(path.endswith("/ai-agent-frameworks-raw-html.html")) |
| 645 | with self.subTest("suffix"): |
| 646 | path = cli.compute_save_path_display("/tmp", report.topic, "v3", "html") |
| 647 | self.assertTrue(path.endswith("/ai-agent-frameworks-raw-html-v3.html")) |
| 648 | with self.subTest("suffix_traversal_sanitized"): |
| 649 | # A suffix carrying path separators / parent refs must be sanitized |
| 650 | # to a flat token so it can never escape the save directory. |
| 651 | path = cli.compute_save_path_display("/tmp", report.topic, "../../etc", "html") |
| 652 | self.assertNotIn("..", path) |
| 653 | self.assertTrue(path.endswith("/ai-agent-frameworks-raw-html-etc.html")) |
| 654 | |
| 655 | def test_save_suffix_cannot_escape_save_directory(self): |
| 656 | report = _report("AI Agent Frameworks", []) |
| 657 | with tempfile.TemporaryDirectory() as tmpdir: |
| 658 | out = cli.save_output(report, "md", tmpdir, suffix="../../ESCAPED") |
| 659 | # The written file stays inside the intended directory, and the |
| 660 | # traversal fragment never lands in the filename. |
| 661 | self.assertEqual(Path(tmpdir).resolve(), out.parent) |
| 662 | self.assertNotIn("..", out.name) |
| 663 | self.assertTrue(out.name.startswith("ai-agent-frameworks-raw")) |
| 664 | |
| 665 | def test_discover_save_suffix_cannot_escape_save_directory(self): |
| 666 | with tempfile.TemporaryDirectory() as tmpdir: |
| 667 | out = cli._save_discovery_output( |
| 668 | "# discovery\n", |
| 669 | domain="AI agents", |
| 670 | emit="md", |
| 671 | save_dir=tmpdir, |
| 672 | suffix="../../ESCAPED", |
| 673 | ) |
| 674 | self.assertEqual(Path(tmpdir).resolve(), out.parent) |
| 675 | self.assertNotIn("..", out.name) |
| 676 | self.assertTrue(out.name.startswith("ai-agents-discover-raw")) |
| 677 | |
| 678 | def test_save_output_can_persist_comparison_html(self): |
| 679 | reports = [ |
| 680 | ("OpenClaw", _report("OpenClaw", ["Containers"])), |
| 681 | ("Hermes", _report("Hermes", ["Memory"])), |
| 682 | ] |
| 683 | rendered = cli.emit_comparison_output(reports, "html") |
| 684 | with tempfile.TemporaryDirectory() as tmpdir: |
| 685 | path = cli.save_output( |
| 686 | reports[0][1], |
| 687 | "html", |
| 688 | tmpdir, |
| 689 | topic_override=cli.comparison_topic(reports), |
| 690 | rendered_content=rendered, |
| 691 | ) |
| 692 | self.assertEqual("openclaw-vs-hermes-raw-html.html", path.name) |
| 693 | saved = path.read_text(encoding="utf-8") |
| 694 | self.assertIn("last30days · OpenClaw vs Hermes", saved) |
| 695 | self.assertIn("comparing 2: OpenClaw, Hermes", saved) |
| 696 | self.assertNotIn("last30days · OpenClaw</title>", saved) |
| 697 | |
| 698 | if __name__ == "__main__": |
| 699 | unittest.main() |
| 700 |