| 1 | //! Self-contained HTML rendering of a conversation export. |
| 2 | //! |
| 3 | //! The page is built from the same sanitized projection as the Markdown |
| 4 | //! document and carries no script and no external resource; its |
| 5 | //! content-security-policy forbids both. Message text is shown verbatim rather |
| 6 | //! than rendered as Markdown, tool calls and results sit in collapsed |
| 7 | //! sections, and the local restore-point table is omitted because snapshot ids |
| 8 | //! mean nothing to a reader of the file. |
| 9 | |
| 10 | use std::collections::HashMap; |
| 11 | use std::fmt::Write as FmtWrite; |
| 12 | |
| 13 | use codewhale_command_contract::facets::{ |
| 14 | ConversationExportProjection, ExportBlock, ExportMessage, ExportTurnOutcome, HistoryEntry, |
| 15 | TranscriptProjection, |
| 16 | }; |
| 17 | use codewhale_sanitize::sanitize::{ |
| 18 | inline_text, is_internal_role, redact_url_for_display, sanitize_text, |
| 19 | }; |
| 20 | |
| 21 | use super::export::{ |
| 22 | OMISSION_NOTE, format_export_time, redacted_json_text, role_label, tool_names, |
| 23 | }; |
| 24 | |
| 25 | const CONTENT_SECURITY_POLICY: &str = "default-src 'none'; style-src 'unsafe-inline'"; |
| 26 | |
| 27 | const STYLE: &str = r#" |
| 28 | :root{color-scheme:light dark;--bg:#fff;--fg:#1f2328;--muted:#656d76;--line:#d0d7de;--card:#f6f8fa;--user:#ddf4ff;--tool:#fff8c5;--error:#ffebe9} |
| 29 | @media (prefers-color-scheme:dark){:root{--bg:#0d1117;--fg:#e6edf3;--muted:#8d96a0;--line:#30363d;--card:#161b22;--user:#0c2d6b;--tool:#3b2e00;--error:#490202}} |
| 30 | *{box-sizing:border-box} |
| 31 | body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.55 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif} |
| 32 | main{max-width:860px;margin:0 auto;padding:2rem 1rem 4rem} |
| 33 | h1{font-size:1.6rem;margin:0 0 .75rem;overflow-wrap:anywhere} |
| 34 | dl{display:grid;grid-template-columns:max-content 1fr;gap:.2rem 1rem;margin:0 0 1rem;color:var(--muted);font-size:.9rem} |
| 35 | dt{font-weight:600} |
| 36 | dd{margin:0;overflow-wrap:anywhere} |
| 37 | .note{border-left:3px solid var(--line);padding:.25rem .75rem;color:var(--muted);font-size:.9rem;margin:0 0 2rem} |
| 38 | .message{border:1px solid var(--line);border-radius:8px;margin:0 0 1rem;overflow:hidden} |
| 39 | .message>h2{margin:0;padding:.4rem .8rem;font-size:.8rem;text-transform:uppercase;letter-spacing:.05em;background:var(--card);border-bottom:1px solid var(--line)} |
| 40 | .message.user>h2{background:var(--user)} |
| 41 | .message.tool>h2{background:var(--tool)} |
| 42 | .message.error>h2{background:var(--error)} |
| 43 | .body{padding:.6rem .8rem} |
| 44 | .text{white-space:pre-wrap;overflow-wrap:anywhere} |
| 45 | .omitted{margin:.25rem 0;color:var(--muted);font-style:italic} |
| 46 | .meta{margin:.25rem 0;color:var(--muted);font-size:.8rem} |
| 47 | details{border:1px solid var(--line);border-radius:6px;margin:.5rem 0;background:var(--card)} |
| 48 | summary{cursor:pointer;padding:.35rem .7rem;font-size:.9rem} |
| 49 | .inner{padding:0 .7rem .6rem} |
| 50 | pre{margin:.25rem 0;padding:.6rem;border:1px solid var(--line);border-radius:6px;background:var(--bg);overflow-x:auto;white-space:pre-wrap;overflow-wrap:anywhere;font:12.5px/1.45 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace} |
| 51 | footer{margin-top:2rem;padding-top:1rem;border-top:1px solid var(--line);color:var(--muted);font-size:.8rem} |
| 52 | "#; |
| 53 | |
| 54 | pub(in crate::commands) fn render(projection: ConversationExportProjection) -> String { |
| 55 | let ConversationExportProjection { |
| 56 | metadata, |
| 57 | transcript, |
| 58 | restore_points: _, |
| 59 | turn_outcomes, |
| 60 | } = projection; |
| 61 | let names = tool_names(&transcript); |
| 62 | let heading = metadata |
| 63 | .title |
| 64 | .as_deref() |
| 65 | .map(inline_text) |
| 66 | .filter(|title| !title.is_empty()) |
| 67 | .unwrap_or_else(|| "Codewhale conversation".to_string()); |
| 68 | let version = env!("CARGO_PKG_VERSION"); |
| 69 | |
| 70 | let mut out = String::new(); |
| 71 | let _ = write!( |
| 72 | out, |
| 73 | "<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n\ |
| 74 | <meta http-equiv=\"Content-Security-Policy\" content=\"{CONTENT_SECURITY_POLICY}\">\n\ |
| 75 | <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\ |
| 76 | <meta name=\"generator\" content=\"Codewhale {version}\">\n\ |
| 77 | <title>{}</title>\n<style>{STYLE}</style>\n</head>\n<body>\n<main>\n<header>\n<h1>{}</h1>\n<dl>\n", |
| 78 | escape_html(&heading), |
| 79 | escape_html(&heading), |
| 80 | ); |
| 81 | for (name, value) in [ |
| 82 | ("Exported", format_export_time(metadata.exported_at_unix)), |
| 83 | ("Session", inline_text(&metadata.session_label)), |
| 84 | ("Provider", inline_text(&metadata.provider)), |
| 85 | ("Model", inline_text(&metadata.model)), |
| 86 | ("Mode", inline_text(&metadata.mode)), |
| 87 | ("Workspace", inline_text(&metadata.workspace_name)), |
| 88 | ("Messages", metadata.message_count.to_string()), |
| 89 | ] { |
| 90 | let _ = writeln!(out, "<dt>{name}</dt><dd>{}</dd>", escape_html(&value)); |
| 91 | } |
| 92 | let _ = writeln!( |
| 93 | out, |
| 94 | "</dl>\n<p class=\"note\">{OMISSION_NOTE}</p>\n</header>" |
| 95 | ); |
| 96 | |
| 97 | match transcript { |
| 98 | TranscriptProjection::HistoryFallback(entries) => { |
| 99 | if entries.is_empty() && !turn_outcomes.is_empty() { |
| 100 | for outcome in &turn_outcomes { |
| 101 | render_turn_outcome(&mut out, outcome); |
| 102 | } |
| 103 | } else { |
| 104 | render_history(&mut out, &entries); |
| 105 | } |
| 106 | } |
| 107 | TranscriptProjection::Authoritative(messages) => { |
| 108 | let mut outcomes = turn_outcomes.iter().peekable(); |
| 109 | let message_count = messages.len(); |
| 110 | render_turn_outcomes_through(&mut out, &mut outcomes, 0, message_count == 0); |
| 111 | for (index, message) in messages.into_iter().enumerate() { |
| 112 | render_message(&mut out, index + 1, message, &names); |
| 113 | render_turn_outcomes_through( |
| 114 | &mut out, |
| 115 | &mut outcomes, |
| 116 | index + 1, |
| 117 | index + 1 == message_count, |
| 118 | ); |
| 119 | } |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | let _ = writeln!( |
| 124 | out, |
| 125 | "<footer>Generated by Codewhale {version}</footer>\n</main>\n</body>\n</html>" |
| 126 | ); |
| 127 | out |
| 128 | } |
| 129 | |
| 130 | fn render_turn_outcomes_through<'a, I>( |
| 131 | out: &mut String, |
| 132 | outcomes: &mut std::iter::Peekable<I>, |
| 133 | message_count: usize, |
| 134 | last: bool, |
| 135 | ) where |
| 136 | I: Iterator<Item = &'a ExportTurnOutcome>, |
| 137 | { |
| 138 | while let Some(outcome) = |
| 139 | outcomes.next_if(|outcome| last || outcome.after_message_count <= message_count) |
| 140 | { |
| 141 | render_turn_outcome(out, outcome); |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | fn render_turn_outcome(out: &mut String, outcome: &ExportTurnOutcome) { |
| 146 | let status = inline_text(&outcome.status); |
| 147 | let status = if status.is_empty() { |
| 148 | "failed" |
| 149 | } else { |
| 150 | status.as_str() |
| 151 | }; |
| 152 | let _ = writeln!( |
| 153 | out, |
| 154 | "<section class=\"message error\">\n<h2>Turn outcome · {}</h2>\n<div class=\"body\">", |
| 155 | escape_html(status) |
| 156 | ); |
| 157 | let mut meta = format!( |
| 158 | "Status {status} · Ended {}", |
| 159 | format_export_time(outcome.ended_at_unix) |
| 160 | ); |
| 161 | if let Some(code) = outcome |
| 162 | .code |
| 163 | .as_deref() |
| 164 | .map(inline_text) |
| 165 | .filter(|code| !code.is_empty()) |
| 166 | { |
| 167 | let _ = write!(meta, " · Code {code}"); |
| 168 | } |
| 169 | out.push_str(&caption(&meta)); |
| 170 | push_text(out, &sanitize_text(&outcome.error)); |
| 171 | out.push_str("</div>\n</section>\n"); |
| 172 | } |
| 173 | |
| 174 | fn render_history(out: &mut String, entries: &[HistoryEntry]) { |
| 175 | if entries.is_empty() { |
| 176 | out.push_str("<p class=\"omitted\">[empty conversation]</p>\n"); |
| 177 | return; |
| 178 | } |
| 179 | out.push_str( |
| 180 | "<p class=\"note\">Structured API messages were unavailable; the entries below are a sanitized visible-history fallback.</p>\n", |
| 181 | ); |
| 182 | for (index, entry) in entries.iter().enumerate() { |
| 183 | let (role, body) = match entry { |
| 184 | HistoryEntry::Sanitized { role, body } => (role.as_str(), sanitize_text(body)), |
| 185 | HistoryEntry::Literal { role, body } => (role.as_str(), body.clone()), |
| 186 | }; |
| 187 | open_section(out, index + 1, &inline_text(role)); |
| 188 | push_text(out, &body); |
| 189 | out.push_str("</div>\n</section>\n"); |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | fn open_section(out: &mut String, index: usize, role: &str) { |
| 194 | let class = match role { |
| 195 | "user" => "user", |
| 196 | "tool" => "tool", |
| 197 | "assistant" => "assistant", |
| 198 | _ => "other", |
| 199 | }; |
| 200 | let _ = writeln!( |
| 201 | out, |
| 202 | "<section class=\"message {class}\" id=\"m{index}\">\n<h2>{index}. {}</h2>\n<div class=\"body\">", |
| 203 | escape_html(role) |
| 204 | ); |
| 205 | } |
| 206 | |
| 207 | fn render_message( |
| 208 | out: &mut String, |
| 209 | index: usize, |
| 210 | message: ExportMessage, |
| 211 | names: &HashMap<String, String>, |
| 212 | ) { |
| 213 | open_section(out, index, &role_label(&message)); |
| 214 | if is_internal_role(&message.role) { |
| 215 | out.push_str("<p class=\"omitted\">[internal context omitted]</p>\n"); |
| 216 | } else if message.blocks.is_empty() { |
| 217 | out.push_str("<p class=\"omitted\">[no content]</p>\n"); |
| 218 | } else { |
| 219 | for block in message.blocks { |
| 220 | render_block(out, block, names); |
| 221 | } |
| 222 | } |
| 223 | out.push_str("</div>\n</section>\n"); |
| 224 | } |
| 225 | |
| 226 | fn render_block(out: &mut String, block: ExportBlock, names: &HashMap<String, String>) { |
| 227 | match block { |
| 228 | ExportBlock::Text { text } => push_text(out, &sanitize_text(&text)), |
| 229 | ExportBlock::ImageReference { url } => { |
| 230 | let _ = writeln!( |
| 231 | out, |
| 232 | "<p class=\"meta\">Image attachment · {}</p>", |
| 233 | escape_html(&inline_text(&redact_url_for_display(&url))) |
| 234 | ); |
| 235 | } |
| 236 | ExportBlock::ImageOmitted => out.push_str( |
| 237 | "<p class=\"meta\">Image attachment · reference omitted (inline or local image payload)</p>\n", |
| 238 | ), |
| 239 | ExportBlock::InternalReasoning => { |
| 240 | out.push_str("<p class=\"omitted\">[internal reasoning and signature omitted]</p>\n"); |
| 241 | } |
| 242 | ExportBlock::ToolCall { |
| 243 | id, |
| 244 | name, |
| 245 | caller, |
| 246 | input, |
| 247 | } => { |
| 248 | let mut meta = format!("ID {}", inline_text(&id)); |
| 249 | if let Some(caller) = caller { |
| 250 | let _ = write!(meta, " · caller {}", inline_text(&caller.caller_type)); |
| 251 | if let Some(tool_id) = caller.tool_id.as_deref() { |
| 252 | let _ = write!(meta, " ({})", inline_text(tool_id)); |
| 253 | } |
| 254 | } |
| 255 | push_details( |
| 256 | out, |
| 257 | &format!("Tool call · {}", inline_text(&name)), |
| 258 | &(caption(&meta) + &pre(&redacted_json_text(input))), |
| 259 | ); |
| 260 | } |
| 261 | ExportBlock::ToolResult { |
| 262 | tool_use_id, |
| 263 | content, |
| 264 | is_error, |
| 265 | structured, |
| 266 | } => { |
| 267 | let mut summary = "Tool result".to_string(); |
| 268 | if let Some(name) = names.get(&tool_use_id) { |
| 269 | let _ = write!(summary, " · {}", inline_text(name)); |
| 270 | } |
| 271 | if is_error { |
| 272 | summary.push_str(" · error"); |
| 273 | } |
| 274 | let mut inner = caption(&format!("Tool call ID {}", inline_text(&tool_use_id))); |
| 275 | inner.push_str(&pre(&sanitize_text(&content))); |
| 276 | if let Some(blocks) = structured { |
| 277 | inner.push_str(&caption("Structured result blocks")); |
| 278 | inner.push_str(&pre(&redacted_json_text(blocks))); |
| 279 | } |
| 280 | push_details(out, &summary, &inner); |
| 281 | } |
| 282 | ExportBlock::ServerToolCall { id, name, input } => push_details( |
| 283 | out, |
| 284 | &format!("Server tool call · {}", inline_text(&name)), |
| 285 | &(caption(&format!("ID {}", inline_text(&id))) + &pre(&redacted_json_text(input))), |
| 286 | ), |
| 287 | ExportBlock::ToolSearchResult { |
| 288 | tool_use_id, |
| 289 | content, |
| 290 | } => push_details( |
| 291 | out, |
| 292 | "Tool-search result", |
| 293 | &(caption(&format!("Tool call ID {}", inline_text(&tool_use_id))) |
| 294 | + &pre(&redacted_json_text(content))), |
| 295 | ), |
| 296 | ExportBlock::CodeExecutionResult { |
| 297 | tool_use_id, |
| 298 | content, |
| 299 | } => push_details( |
| 300 | out, |
| 301 | "Code-execution result", |
| 302 | &(caption(&format!("Tool call ID {}", inline_text(&tool_use_id))) |
| 303 | + &pre(&redacted_json_text(content))), |
| 304 | ), |
| 305 | } |
| 306 | } |
| 307 | |
| 308 | fn push_text(out: &mut String, text: &str) { |
| 309 | let text = text.trim_end(); |
| 310 | if text.trim().is_empty() { |
| 311 | out.push_str("<p class=\"omitted\">[empty text]</p>\n"); |
| 312 | } else { |
| 313 | let _ = writeln!(out, "<div class=\"text\">{}</div>", escape_html(text)); |
| 314 | } |
| 315 | } |
| 316 | |
| 317 | fn caption(text: &str) -> String { |
| 318 | format!("<p class=\"meta\">{}</p>\n", escape_html(text)) |
| 319 | } |
| 320 | |
| 321 | fn pre(text: &str) -> String { |
| 322 | format!("<pre>{}</pre>\n", escape_html(text)) |
| 323 | } |
| 324 | |
| 325 | fn push_details(out: &mut String, summary: &str, inner: &str) { |
| 326 | let _ = writeln!( |
| 327 | out, |
| 328 | "<details>\n<summary>{}</summary>\n<div class=\"inner\">\n{inner}</div>\n</details>", |
| 329 | escape_html(summary) |
| 330 | ); |
| 331 | } |
| 332 | |
| 333 | fn escape_html(text: &str) -> String { |
| 334 | let mut escaped = String::with_capacity(text.len()); |
| 335 | for ch in text.chars() { |
| 336 | match ch { |
| 337 | '&' => escaped.push_str("&"), |
| 338 | '<' => escaped.push_str("<"), |
| 339 | '>' => escaped.push_str(">"), |
| 340 | '"' => escaped.push_str("""), |
| 341 | '\'' => escaped.push_str("'"), |
| 342 | _ => escaped.push(ch), |
| 343 | } |
| 344 | } |
| 345 | escaped |
| 346 | } |
| 347 |