| 1 | //! Bounded, redacted, read-only transcript peek for the dashboard (#4397). |
| 2 | //! |
| 3 | //! The dashboard needs to show *what a saved session was about* without |
| 4 | //! becoming a second transcript viewer. Three constraints shape this module, |
| 5 | //! and all three are enforced here rather than in the client: |
| 6 | //! |
| 7 | //! * **Bounded on the wire.** The peek carries at most |
| 8 | //! [`MAX_PEEK_ENTRIES`] entries of at most [`MAX_ENTRY_CHARS`] characters. |
| 9 | //! Doing this client-side would mean shipping a multi-megabyte transcript to |
| 10 | //! a browser in order to throw most of it away. |
| 11 | //! * **Redacted.** A saved transcript can contain an API key a user pasted, a |
| 12 | //! token echoed by a tool, an `Authorization` header in a curl command. The |
| 13 | //! dashboard is reachable over a LAN; a peek pane is not the place to |
| 14 | //! re-emit those. |
| 15 | //! * **Read-only and non-live.** A peek is a recording. It carries no turn |
| 16 | //! status, no "running" flag, nothing that could be mistaken for live state. |
| 17 | //! Live state comes from a resumed thread and its SSE stream, never from |
| 18 | //! here — see `runtime_web/app.mjs`'s reply-target rules. |
| 19 | //! |
| 20 | //! Tool payloads are summarised to a kind and a size, never inlined: a tool |
| 21 | //! result is the most likely place for both bulk and secrets. |
| 22 | |
| 23 | use serde::Serialize; |
| 24 | |
| 25 | use crate::session_manager::SavedSession; |
| 26 | use codewhale_models::ContentBlock; |
| 27 | |
| 28 | /// Most entries a peek carries. The dashboard shows a tail, so this is "the |
| 29 | /// last N exchanges", which is what a peek is for. |
| 30 | pub const MAX_PEEK_ENTRIES: usize = 100; |
| 31 | pub const DEFAULT_PEEK_ENTRIES: usize = 12; |
| 32 | |
| 33 | /// Longest text any single entry carries. |
| 34 | pub const MAX_ENTRY_CHARS: usize = 400; |
| 35 | |
| 36 | /// What produced an entry. Deliberately coarse — the peek is not a |
| 37 | /// reconstruction of the turn structure. |
| 38 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] |
| 39 | #[serde(rename_all = "snake_case")] |
| 40 | pub enum PeekEntryKind { |
| 41 | User, |
| 42 | Assistant, |
| 43 | Reasoning, |
| 44 | /// A tool call or result, summarised. Never the payload itself. |
| 45 | Tool, |
| 46 | } |
| 47 | |
| 48 | /// One bounded line of recorded conversation. |
| 49 | #[derive(Debug, Clone, PartialEq, Eq, Serialize)] |
| 50 | pub struct PeekEntry { |
| 51 | pub kind: PeekEntryKind, |
| 52 | /// Already bounded and redacted. Safe to render as text — and only as |
| 53 | /// text; the client inserts it with `textContent`, never `innerHTML`. |
| 54 | pub text: String, |
| 55 | /// True when [`Self::text`] was shortened. |
| 56 | pub truncated: bool, |
| 57 | /// True when at least one redaction was applied. |
| 58 | pub redacted: bool, |
| 59 | } |
| 60 | |
| 61 | /// A read-only view of a saved session. |
| 62 | /// |
| 63 | /// Note what is absent: no turn status, no `active`, no `running`. A saved |
| 64 | /// session has none of those, and inventing them is the fabricated-live-state |
| 65 | /// failure this whole slice exists to avoid. |
| 66 | #[derive(Debug, Clone, PartialEq, Eq, Serialize)] |
| 67 | pub struct SessionPeek { |
| 68 | pub session_id: String, |
| 69 | pub title: String, |
| 70 | pub workspace: std::path::PathBuf, |
| 71 | pub model: String, |
| 72 | pub mode: String, |
| 73 | pub archived: bool, |
| 74 | /// Messages of conversation, runtime control traffic excluded. The peek |
| 75 | /// never shows that traffic, so counting it here would print a total the |
| 76 | /// pane cannot account for. |
| 77 | pub message_count: usize, |
| 78 | pub updated_at: chrono::DateTime<chrono::Utc>, |
| 79 | /// Entries actually carried, oldest-first within the tail. |
| 80 | pub entries: Vec<PeekEntry>, |
| 81 | /// How many messages were dropped from the front to fit the bound. The |
| 82 | /// client shows this rather than implying it has the whole conversation. |
| 83 | pub omitted_before: usize, |
| 84 | /// Always true: a peek is a recording of a saved session, never a live |
| 85 | /// thread. Serialised so a client cannot mistake one payload for the |
| 86 | /// other even by accident. |
| 87 | pub live: bool, |
| 88 | } |
| 89 | |
| 90 | /// Build a bounded, redacted peek from a loaded session. |
| 91 | #[must_use] |
| 92 | pub fn build_peek(session: &SavedSession, max_entries: usize) -> SessionPeek { |
| 93 | let max_entries = max_entries.clamp(1, MAX_PEEK_ENTRIES); |
| 94 | // Runtime control traffic is persisted with `role = "user"` because strict |
| 95 | // chat templates reject anything else mid-conversation — see |
| 96 | // `runtime_handoff`, which owns both the envelope and its recognition. |
| 97 | // Rendering that transport role would attribute the runtime's own |
| 98 | // bookkeeping to the person, and in a session with busy sub-agents it is |
| 99 | // most of what the pane would show. Drop it before the tail is taken: |
| 100 | // filtering afterwards spends the entry budget on rows nobody sees. |
| 101 | let conversation: Vec<_> = session |
| 102 | .messages |
| 103 | .iter() |
| 104 | .filter(|message| !crate::runtime_handoff::is_internal_runtime_handoff(message)) |
| 105 | .collect(); |
| 106 | let total = conversation.len(); |
| 107 | let start = total.saturating_sub(max_entries); |
| 108 | |
| 109 | let entries: Vec<PeekEntry> = conversation[start..] |
| 110 | .iter() |
| 111 | .map(|message| { |
| 112 | let kind = match message.role.as_str() { |
| 113 | "user" => PeekEntryKind::User, |
| 114 | _ => PeekEntryKind::Assistant, |
| 115 | }; |
| 116 | entry_for_message(kind, message) |
| 117 | }) |
| 118 | .collect(); |
| 119 | |
| 120 | SessionPeek { |
| 121 | session_id: session.metadata.id.clone(), |
| 122 | title: session.metadata.title.clone(), |
| 123 | workspace: session.metadata.workspace.clone(), |
| 124 | model: session.metadata.model.clone(), |
| 125 | mode: session |
| 126 | .metadata |
| 127 | .mode |
| 128 | .clone() |
| 129 | .unwrap_or_else(|| "agent".to_string()), |
| 130 | archived: session.metadata.archived, |
| 131 | message_count: total, |
| 132 | updated_at: session.metadata.updated_at, |
| 133 | entries, |
| 134 | omitted_before: start, |
| 135 | live: false, |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | fn entry_for_message( |
| 140 | default_kind: PeekEntryKind, |
| 141 | message: &codewhale_models::Message, |
| 142 | ) -> PeekEntry { |
| 143 | let mut kind = default_kind; |
| 144 | let mut parts: Vec<String> = Vec::new(); |
| 145 | |
| 146 | for (index, block) in message.content.iter().enumerate() { |
| 147 | match block { |
| 148 | ContentBlock::Text { text, .. } => { |
| 149 | if crate::runtime_handoff::is_turn_metadata_block(message, index, text) { |
| 150 | continue; |
| 151 | } |
| 152 | parts.push(text.trim().to_string()); |
| 153 | } |
| 154 | ContentBlock::Thinking { thinking, .. } => { |
| 155 | kind = PeekEntryKind::Reasoning; |
| 156 | parts.push(thinking.trim().to_string()); |
| 157 | } |
| 158 | // Tool traffic is summarised, never inlined: it is the most |
| 159 | // likely carrier of both bulk output and credentials. |
| 160 | ContentBlock::ToolUse { name, .. } | ContentBlock::ServerToolUse { name, .. } => { |
| 161 | kind = PeekEntryKind::Tool; |
| 162 | parts.push(format!("Ran {name}")); |
| 163 | } |
| 164 | ContentBlock::ToolResult { content, .. } => { |
| 165 | kind = PeekEntryKind::Tool; |
| 166 | parts.push(format!("Result, {} chars", content.chars().count())); |
| 167 | } |
| 168 | // Structured tool results are JSON. Report their serialized size |
| 169 | // rather than their shape: the size is the honest number, and any |
| 170 | // field of the payload could be a credential. |
| 171 | ContentBlock::ToolSearchToolResult { content, .. } |
| 172 | | ContentBlock::CodeExecutionToolResult { content, .. } |
| 173 | | ContentBlock::WebSearchToolResult { content, .. } |
| 174 | | ContentBlock::WebFetchToolResult { content, .. } => { |
| 175 | kind = PeekEntryKind::Tool; |
| 176 | parts.push(format!("Result, {} chars", content.to_string().len())); |
| 177 | } |
| 178 | ContentBlock::WebSearchCall { |
| 179 | kind: call_kind, .. |
| 180 | } => { |
| 181 | kind = PeekEntryKind::Tool; |
| 182 | parts.push(format!( |
| 183 | "Ran web search ({})", |
| 184 | call_kind.as_deref().unwrap_or("search") |
| 185 | )); |
| 186 | } |
| 187 | ContentBlock::ServerToolCalls { steps } => { |
| 188 | kind = PeekEntryKind::Tool; |
| 189 | parts.push(format!("Ran {} server tool steps", steps.len())); |
| 190 | } |
| 191 | ContentBlock::File { file_id } => { |
| 192 | parts.push(format!("[file: {file_id}]")); |
| 193 | } |
| 194 | ContentBlock::ImageUrl { .. } => { |
| 195 | kind = PeekEntryKind::Tool; |
| 196 | parts.push("[image]".to_string()); |
| 197 | } |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | let joined = parts |
| 202 | .into_iter() |
| 203 | .filter(|part| !part.is_empty()) |
| 204 | .collect::<Vec<_>>() |
| 205 | .join(" "); |
| 206 | let (text, redacted) = redact(&joined); |
| 207 | let (text, truncated) = bound(&text, MAX_ENTRY_CHARS); |
| 208 | |
| 209 | PeekEntry { |
| 210 | kind, |
| 211 | text, |
| 212 | truncated, |
| 213 | redacted, |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | fn bound(text: &str, max_chars: usize) -> (String, bool) { |
| 218 | if text.chars().count() <= max_chars { |
| 219 | return (text.to_string(), false); |
| 220 | } |
| 221 | let kept: String = text.chars().take(max_chars.saturating_sub(1)).collect(); |
| 222 | (format!("{kept}…"), true) |
| 223 | } |
| 224 | |
| 225 | /// Placeholder substituted for anything that looks like a credential. |
| 226 | pub const REDACTED_PLACEHOLDER: &str = "[redacted]"; |
| 227 | |
| 228 | /// Mask credential-shaped substrings. |
| 229 | /// |
| 230 | /// The shared export sanitizer ([`codewhale_sanitize::sanitize::sanitize_text`], |
| 231 | /// also used by `/export`) runs first: it covers `Bearer <token>`, JWTs, |
| 232 | /// URL credentials, PEM blocks, and quoted JSON/TOML keyed secrets. A |
| 233 | /// token-level pass then masks the extra bare prefixes (AWS, Google, Hugging |
| 234 | /// Face) and long opaque runs a transcript tends to carry. Over-redacting a |
| 235 | /// peek line is cheap; leaking a key over a LAN is not. |
| 236 | #[must_use] |
| 237 | pub fn redact(text: &str) -> (String, bool) { |
| 238 | let sanitized = codewhale_sanitize::sanitize::sanitize_text(text); |
| 239 | // The sanitizer also strips control bytes and normalises URLs, so compare |
| 240 | // placeholder counts rather than bytes to decide whether it redacted. |
| 241 | let mut redacted = redaction_marks(&sanitized) > redaction_marks(text); |
| 242 | let mut out = String::with_capacity(sanitized.len()); |
| 243 | |
| 244 | for token in sanitized.split_inclusive(char::is_whitespace) { |
| 245 | let trimmed = token.trim_end(); |
| 246 | let trailing = &token[trimmed.len()..]; |
| 247 | // Keep closing quotes and punctuation outside the mask so a masked |
| 248 | // token inside `"…"` or `(…)` does not swallow its delimiter. |
| 249 | let core = trimmed.trim_end_matches(['"', '\'', '`', ',', ';', ')', ']', '}']); |
| 250 | let closing = &trimmed[core.len()..]; |
| 251 | if looks_like_secret(core) { |
| 252 | out.push_str(REDACTED_PLACEHOLDER); |
| 253 | out.push_str(closing); |
| 254 | out.push_str(trailing); |
| 255 | redacted = true; |
| 256 | } else if let Some(masked) = mask_assignment(core) { |
| 257 | out.push_str(&masked); |
| 258 | out.push_str(closing); |
| 259 | out.push_str(trailing); |
| 260 | redacted = true; |
| 261 | } else { |
| 262 | out.push_str(token); |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | (out, redacted) |
| 267 | } |
| 268 | |
| 269 | fn redaction_marks(text: &str) -> usize { |
| 270 | text.matches("[redacted").count() + text.matches("***").count() |
| 271 | } |
| 272 | |
| 273 | /// Known credential prefixes plus long opaque runs. |
| 274 | fn looks_like_secret(token: &str) -> bool { |
| 275 | const PREFIXES: &[&str] = &[ |
| 276 | "sk-", |
| 277 | "sk_", |
| 278 | "pk_", |
| 279 | "ghp_", |
| 280 | "gho_", |
| 281 | "ghu_", |
| 282 | "ghs_", |
| 283 | "github_pat_", |
| 284 | "xoxb-", |
| 285 | "xoxp-", |
| 286 | "AKIA", |
| 287 | "ASIA", |
| 288 | "AIza", |
| 289 | "hf_", |
| 290 | "Bearer", |
| 291 | ]; |
| 292 | if PREFIXES |
| 293 | .iter() |
| 294 | .any(|prefix| token.len() > prefix.len() && token.starts_with(prefix)) |
| 295 | { |
| 296 | return true; |
| 297 | } |
| 298 | // A long unbroken run of base64/hex-ish characters is almost never prose. |
| 299 | token.len() >= 32 |
| 300 | && token |
| 301 | .chars() |
| 302 | .all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '/' || c == '=' || c == '_') |
| 303 | && token.chars().any(|c| c.is_ascii_digit()) |
| 304 | && token.chars().any(|c| c.is_ascii_alphabetic()) |
| 305 | } |
| 306 | |
| 307 | /// `key=value`, `token: value`, `--password value` style assignments. |
| 308 | fn mask_assignment(token: &str) -> Option<String> { |
| 309 | const KEYS: &[&str] = &[ |
| 310 | "api_key", |
| 311 | "apikey", |
| 312 | "api-key", |
| 313 | "token", |
| 314 | "secret", |
| 315 | "password", |
| 316 | "passwd", |
| 317 | "authorization", |
| 318 | "auth", |
| 319 | "credential", |
| 320 | ]; |
| 321 | let (name, sep_index) = token |
| 322 | .find('=') |
| 323 | .map(|i| (&token[..i], i)) |
| 324 | .or_else(|| token.find(':').map(|i| (&token[..i], i)))?; |
| 325 | let normalized = name.trim_start_matches('-').to_ascii_lowercase(); |
| 326 | if !KEYS.contains(&normalized.as_str()) { |
| 327 | return None; |
| 328 | } |
| 329 | if token[sep_index + 1..].trim().is_empty() { |
| 330 | return None; |
| 331 | } |
| 332 | Some(format!( |
| 333 | "{}{}{REDACTED_PLACEHOLDER}", |
| 334 | name, |
| 335 | &token[sep_index..=sep_index] |
| 336 | )) |
| 337 | } |
| 338 | |
| 339 | #[cfg(test)] |
| 340 | mod tests { |
| 341 | use super::*; |
| 342 | use crate::session_manager::create_saved_session_with_id_and_mode; |
| 343 | use codewhale_models::Message; |
| 344 | use codewhale_models::Role; |
| 345 | |
| 346 | fn text_block(text: &str) -> ContentBlock { |
| 347 | ContentBlock::Text { |
| 348 | text: text.to_string(), |
| 349 | cache_control: None, |
| 350 | } |
| 351 | } |
| 352 | |
| 353 | fn session_with(messages: Vec<Message>) -> SavedSession { |
| 354 | create_saved_session_with_id_and_mode( |
| 355 | "peek-session".to_string(), |
| 356 | &messages, |
| 357 | "deepseek-chat", |
| 358 | std::path::Path::new("/repo"), |
| 359 | 10, |
| 360 | None, |
| 361 | Some("agent"), |
| 362 | ) |
| 363 | } |
| 364 | |
| 365 | fn user(text: &str) -> Message { |
| 366 | Message { |
| 367 | role: Role::User, |
| 368 | content: vec![text_block(text)], |
| 369 | } |
| 370 | } |
| 371 | |
| 372 | #[test] |
| 373 | fn peek_is_bounded_in_entries_and_reports_what_it_dropped() { |
| 374 | let messages: Vec<Message> = (0..140).map(|i| user(&format!("message {i}"))).collect(); |
| 375 | let peek = build_peek(&session_with(messages), MAX_PEEK_ENTRIES); |
| 376 | |
| 377 | assert_eq!(peek.entries.len(), MAX_PEEK_ENTRIES); |
| 378 | assert_eq!(peek.message_count, 140); |
| 379 | assert_eq!(peek.omitted_before, 140 - MAX_PEEK_ENTRIES); |
| 380 | assert!( |
| 381 | peek.entries.last().expect("tail").text.contains("139"), |
| 382 | "the peek must be the tail, not the head" |
| 383 | ); |
| 384 | } |
| 385 | |
| 386 | #[test] |
| 387 | fn a_request_for_more_than_the_cap_still_gets_the_cap() { |
| 388 | let messages: Vec<Message> = (0..300).map(|i| user(&format!("m{i}"))).collect(); |
| 389 | let peek = build_peek(&session_with(messages), usize::MAX); |
| 390 | assert_eq!(peek.entries.len(), MAX_PEEK_ENTRIES); |
| 391 | } |
| 392 | |
| 393 | #[test] |
| 394 | fn long_entries_are_truncated_and_flagged() { |
| 395 | let peek = build_peek(&session_with(vec![user(&"x".repeat(5_000))]), 4); |
| 396 | let entry = &peek.entries[0]; |
| 397 | assert!(entry.truncated); |
| 398 | assert!(entry.text.chars().count() <= MAX_ENTRY_CHARS); |
| 399 | } |
| 400 | |
| 401 | #[test] |
| 402 | fn credentials_are_redacted_out_of_peek_text() { |
| 403 | for secret in [ |
| 404 | "sk-abcdefghijklmnopqrstuvwxyz123456", |
| 405 | "ghp_abcdefghijklmnopqrstuvwxyz1234", |
| 406 | "AKIAIOSFODNN7EXAMPLE", |
| 407 | ] { |
| 408 | let peek = build_peek(&session_with(vec![user(&format!("here: {secret}"))]), 4); |
| 409 | let entry = &peek.entries[0]; |
| 410 | assert!(entry.redacted, "{secret} should have been redacted"); |
| 411 | assert!( |
| 412 | !entry.text.contains(secret), |
| 413 | "peek leaked {secret}: {}", |
| 414 | entry.text |
| 415 | ); |
| 416 | assert!(entry.text.contains(REDACTED_PLACEHOLDER)); |
| 417 | } |
| 418 | } |
| 419 | |
| 420 | #[test] |
| 421 | fn assignment_style_secrets_are_masked_but_keep_their_key() { |
| 422 | let (masked, redacted) = redact("api_key=hunter2 and password:swordfish"); |
| 423 | assert!(redacted); |
| 424 | assert!(masked.contains("api_key=")); |
| 425 | assert!(!masked.contains("hunter2")); |
| 426 | assert!(!masked.contains("swordfish")); |
| 427 | } |
| 428 | |
| 429 | #[test] |
| 430 | fn bearer_jwt_and_quoted_json_secrets_are_redacted() { |
| 431 | let jwt = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.c2lnbmF0dXJlLXZhbHVl"; |
| 432 | let bearer = format!("Authorization: Bearer {jwt}"); |
| 433 | let json_key = r#"{"api_key": "sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123456789"}"#; |
| 434 | for (input, secret) in [ |
| 435 | (bearer.as_str(), jwt), |
| 436 | ( |
| 437 | json_key, |
| 438 | "sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123456789", |
| 439 | ), |
| 440 | ( |
| 441 | "run: curl https://user:hunter2pass@api.example/v1 now", |
| 442 | "hunter2pass", |
| 443 | ), |
| 444 | ] { |
| 445 | let (out, redacted) = redact(input); |
| 446 | assert!(redacted, "{input} should have been redacted: {out}"); |
| 447 | assert!(!out.contains(secret), "peek leaked {secret}: {out}"); |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | #[test] |
| 452 | fn a_masked_token_keeps_its_closing_quote() { |
| 453 | let (out, redacted) = |
| 454 | redact(r#"curl -H "X-Key: ghp_abcdefghijklmnopqrstuvwxyz1234" https://api.example"#); |
| 455 | assert!(redacted); |
| 456 | assert!(!out.contains("ghp_abcdefghijklmnopqrstuvwxyz1234"), "{out}"); |
| 457 | assert!(out.contains(r#"[redacted]" https://api.example"#), "{out}"); |
| 458 | } |
| 459 | |
| 460 | #[test] |
| 461 | fn ordinary_prose_is_not_redacted() { |
| 462 | let (out, redacted) = redact("Please refactor the lane registry and update the docs."); |
| 463 | assert!(!redacted); |
| 464 | assert_eq!( |
| 465 | out, |
| 466 | "Please refactor the lane registry and update the docs." |
| 467 | ); |
| 468 | } |
| 469 | |
| 470 | #[test] |
| 471 | fn tool_payloads_are_summarised_never_inlined() { |
| 472 | let message = Message { |
| 473 | role: Role::Assistant, |
| 474 | content: vec![ |
| 475 | ContentBlock::ToolUse { |
| 476 | execution_id: None, |
| 477 | id: "call-1".to_string(), |
| 478 | name: "read_file".to_string(), |
| 479 | input: serde_json::json!({ "path": "/etc/shadow" }), |
| 480 | caller: None, |
| 481 | thought_signature: None, |
| 482 | }, |
| 483 | ContentBlock::ToolResult { |
| 484 | execution_id: None, |
| 485 | tool_use_id: "call-1".to_string(), |
| 486 | content: "root:$6$verysecrethash".to_string(), |
| 487 | is_error: None, |
| 488 | content_blocks: None, |
| 489 | }, |
| 490 | ], |
| 491 | }; |
| 492 | let peek = build_peek(&session_with(vec![message]), 4); |
| 493 | let entry = &peek.entries[0]; |
| 494 | |
| 495 | assert_eq!(entry.kind, PeekEntryKind::Tool); |
| 496 | assert!(entry.text.contains("Ran read_file")); |
| 497 | assert!(entry.text.contains("Result, 22 chars")); |
| 498 | assert!(!entry.text.contains('[')); |
| 499 | assert!( |
| 500 | !entry.text.contains("verysecrethash"), |
| 501 | "tool output must never be inlined into a peek: {}", |
| 502 | entry.text |
| 503 | ); |
| 504 | assert!( |
| 505 | !entry.text.contains("/etc/shadow"), |
| 506 | "tool input must not be inlined either: {}", |
| 507 | entry.text |
| 508 | ); |
| 509 | } |
| 510 | |
| 511 | #[test] |
| 512 | fn turn_meta_envelope_is_stripped_from_user_entries() { |
| 513 | let message = Message { |
| 514 | role: Role::User, |
| 515 | content: vec![ |
| 516 | text_block("fix the build"), |
| 517 | text_block("<turn_meta>\nCurrent approval mode: on-request\n</turn_meta>"), |
| 518 | ], |
| 519 | }; |
| 520 | let peek = build_peek(&session_with(vec![message]), 4); |
| 521 | assert_eq!(peek.entries[0].text, "fix the build"); |
| 522 | assert!(!peek.entries[0].text.contains("turn_meta")); |
| 523 | } |
| 524 | |
| 525 | #[test] |
| 526 | fn a_peek_never_claims_to_be_live() { |
| 527 | let peek = build_peek(&session_with(vec![user("hello")]), 4); |
| 528 | assert!(!peek.live, "a saved session is a recording, never live"); |
| 529 | let json = serde_json::to_value(&peek).expect("serialize"); |
| 530 | for forbidden in ["status", "running", "active", "turn"] { |
| 531 | assert!( |
| 532 | json.get(forbidden).is_none(), |
| 533 | "peek payload must not carry a `{forbidden}` field a client could read as live state" |
| 534 | ); |
| 535 | } |
| 536 | } |
| 537 | |
| 538 | #[test] |
| 539 | fn archive_state_rides_along_so_the_dashboard_need_not_guess() { |
| 540 | let mut session = session_with(vec![user("hello")]); |
| 541 | session.metadata.archived = true; |
| 542 | assert!(build_peek(&session, 4).archived); |
| 543 | } |
| 544 | |
| 545 | /// Every runtime handoff shape that can reach a saved session, including |
| 546 | /// the restore checkpoints a post-resume save persists. |
| 547 | fn runtime_handoffs() -> Vec<(&'static str, Message)> { |
| 548 | let waiting = crate::runtime_handoff::waiting_for_subagents_runtime_message(2); |
| 549 | let restored = |
| 550 | crate::runtime_handoff::project_owned_messages_for_restore(vec![waiting.clone()]); |
| 551 | vec![ |
| 552 | ("waiting_for_subagents", waiting), |
| 553 | ( |
| 554 | "background_shell_completion", |
| 555 | crate::runtime_handoff::shell_completion_runtime_message(&[]), |
| 556 | ), |
| 557 | ( |
| 558 | "restored_checkpoint", |
| 559 | restored.into_iter().next().expect("projected"), |
| 560 | ), |
| 561 | ] |
| 562 | } |
| 563 | |
| 564 | #[test] |
| 565 | fn internal_runtime_events_are_absent_from_a_peek() { |
| 566 | for (kind, handoff) in runtime_handoffs() { |
| 567 | let peek = build_peek( |
| 568 | &session_with(vec![user("ship the release"), handoff]), |
| 569 | MAX_PEEK_ENTRIES, |
| 570 | ); |
| 571 | |
| 572 | assert_eq!( |
| 573 | peek.entries.len(), |
| 574 | 1, |
| 575 | "{kind} was rendered as conversation: {:?}", |
| 576 | peek.entries |
| 577 | ); |
| 578 | assert_eq!(peek.entries[0].text, "ship the release"); |
| 579 | for entry in &peek.entries { |
| 580 | assert!( |
| 581 | !entry.text.contains("<codewhale:runtime_event"), |
| 582 | "{kind} leaked its envelope into a peek entry: {}", |
| 583 | entry.text |
| 584 | ); |
| 585 | assert!( |
| 586 | !entry.text.contains("[Codewhale restored"), |
| 587 | "{kind} leaked a restore checkpoint into a peek entry: {}", |
| 588 | entry.text |
| 589 | ); |
| 590 | } |
| 591 | } |
| 592 | } |
| 593 | |
| 594 | #[test] |
| 595 | fn real_user_messages_survive_the_runtime_filter() { |
| 596 | let mut messages = vec![user("first")]; |
| 597 | for (_, handoff) in runtime_handoffs() { |
| 598 | messages.push(handoff); |
| 599 | } |
| 600 | messages.push(user("second")); |
| 601 | |
| 602 | let peek = build_peek(&session_with(messages), MAX_PEEK_ENTRIES); |
| 603 | |
| 604 | let texts: Vec<&str> = peek.entries.iter().map(|e| e.text.as_str()).collect(); |
| 605 | assert_eq!(texts, vec!["first", "second"]); |
| 606 | assert!(peek.entries.iter().all(|e| e.kind == PeekEntryKind::User)); |
| 607 | } |
| 608 | |
| 609 | #[test] |
| 610 | fn a_person_who_pastes_a_runtime_envelope_is_still_the_person_talking() { |
| 611 | // The filter keys on runtime provenance, never on the envelope text. |
| 612 | // A composer turn is `ExternalUser`, whose authority is implicit, so |
| 613 | // its metadata carries no provenance line — which is what keeps the |
| 614 | // second shape here visible even though it is block-for-block what a |
| 615 | // handoff looks like. |
| 616 | let question = "why did I get <codewhale:runtime_event \ |
| 617 | kind=\"waiting_for_subagents\" visibility=\"internal\"> \ |
| 618 | in my transcript?"; |
| 619 | let pastes = [ |
| 620 | user(question), |
| 621 | Message { |
| 622 | role: Role::User, |
| 623 | content: vec![ |
| 624 | text_block(question), |
| 625 | text_block(concat!( |
| 626 | "<turn_meta>\n", |
| 627 | "Current approval mode: on-request\n", |
| 628 | "</turn_meta>", |
| 629 | )), |
| 630 | ], |
| 631 | }, |
| 632 | ]; |
| 633 | |
| 634 | for paste in pastes { |
| 635 | let peek = build_peek(&session_with(vec![paste]), MAX_PEEK_ENTRIES); |
| 636 | |
| 637 | assert_eq!(peek.entries.len(), 1); |
| 638 | assert_eq!(peek.entries[0].kind, PeekEntryKind::User); |
| 639 | assert!(peek.entries[0].text.contains("why did I get")); |
| 640 | } |
| 641 | } |
| 642 | |
| 643 | /// Rebuild a handoff the way the engine's ordinary send path does, with |
| 644 | /// the blocks `user_content_blocks` inserts for an `[Attached image: …]` |
| 645 | /// line in the payload. Idle completions take that path rather than |
| 646 | /// `runtime_handoff_message_with_meta`, so this shape reaches saved |
| 647 | /// sessions too. |
| 648 | fn with_attachment_blocks(handoff: &Message) -> Message { |
| 649 | let ( |
| 650 | ContentBlock::Text { text: envelope, .. }, |
| 651 | Some(ContentBlock::Text { text: meta, .. }), |
| 652 | ) = (&handoff.content[0], handoff.content.last()) |
| 653 | else { |
| 654 | panic!("handoff should be text-anchored"); |
| 655 | }; |
| 656 | Message { |
| 657 | role: handoff.role.clone(), |
| 658 | content: vec![ |
| 659 | text_block(envelope), |
| 660 | text_block("<image path=\"/tmp/shot.png\">"), |
| 661 | ContentBlock::ImageUrl { |
| 662 | image_url: codewhale_models::ImageUrlContent { |
| 663 | url: "data:image/png;base64,iVBORw0KGgo=".to_string(), |
| 664 | }, |
| 665 | }, |
| 666 | text_block("</image>"), |
| 667 | text_block(meta), |
| 668 | ], |
| 669 | } |
| 670 | } |
| 671 | |
| 672 | #[test] |
| 673 | fn a_handoff_that_carried_an_attachment_is_still_recognized() { |
| 674 | for (kind, handoff) in runtime_handoffs() { |
| 675 | let expanded = with_attachment_blocks(&handoff); |
| 676 | let peek = build_peek( |
| 677 | &session_with(vec![user("look at this"), expanded]), |
| 678 | MAX_PEEK_ENTRIES, |
| 679 | ); |
| 680 | |
| 681 | assert_eq!( |
| 682 | peek.entries.len(), |
| 683 | 1, |
| 684 | "{kind} leaked once its payload mentioned an attachment: {:?}", |
| 685 | peek.entries |
| 686 | ); |
| 687 | assert_eq!(peek.entries[0].text, "look at this"); |
| 688 | } |
| 689 | } |
| 690 | |
| 691 | #[test] |
| 692 | fn runtime_traffic_does_not_spend_the_entry_budget() { |
| 693 | // Filtering after the tail was taken would leave a session with chatty |
| 694 | // sub-agents showing two or three lines of conversation out of twelve. |
| 695 | let mut messages = Vec::new(); |
| 696 | for i in 0..MAX_PEEK_ENTRIES { |
| 697 | messages.push(user(&format!("message {i}"))); |
| 698 | messages.push(crate::runtime_handoff::shell_completion_runtime_message(&[])); |
| 699 | } |
| 700 | |
| 701 | let peek = build_peek(&session_with(messages), MAX_PEEK_ENTRIES); |
| 702 | |
| 703 | assert_eq!(peek.entries.len(), MAX_PEEK_ENTRIES); |
| 704 | assert!(peek.entries[0].text.contains("message 0")); |
| 705 | assert!( |
| 706 | peek.entries |
| 707 | .last() |
| 708 | .expect("tail") |
| 709 | .text |
| 710 | .contains(&format!("message {}", MAX_PEEK_ENTRIES - 1)) |
| 711 | ); |
| 712 | } |
| 713 | |
| 714 | #[test] |
| 715 | fn the_counters_describe_what_the_pane_can_show() { |
| 716 | // The dashboard prints both numbers next to the rows it rendered, so a |
| 717 | // count that included hidden runtime traffic would not add up. |
| 718 | let mut messages = Vec::new(); |
| 719 | for i in 0..130 { |
| 720 | messages.push(user(&format!("m{i}"))); |
| 721 | messages.push(crate::runtime_handoff::waiting_for_subagents_runtime_message(1)); |
| 722 | } |
| 723 | |
| 724 | let peek = build_peek(&session_with(messages), MAX_PEEK_ENTRIES); |
| 725 | |
| 726 | assert_eq!(peek.message_count, 130); |
| 727 | assert_eq!( |
| 728 | peek.omitted_before + peek.entries.len(), |
| 729 | peek.message_count, |
| 730 | "omitted + shown must account for every message the peek claims" |
| 731 | ); |
| 732 | } |
| 733 | } |
| 734 |