| 1 | //! `@`-mention parsing, completion, and expansion for the composer. |
| 2 | //! |
| 3 | //! Two responsibilities live here: |
| 4 | //! |
| 5 | //! 1. **Tab-completion** at the cursor — `try_autocomplete_file_mention` is |
| 6 | //! called by the composer's Tab handler. Walks the workspace, ranks |
| 7 | //! candidates by prefix-then-substring match, and either splices the |
| 8 | //! completion in directly (single match), extends to a shared prefix, or |
| 9 | //! surfaces options in the status line. |
| 10 | //! 2. **Expansion before send** — when the user hits Enter on a message that |
| 11 | //! contains `@<path>` references, `user_request_with_file_mentions` |
| 12 | //! appends a "Local context from @mentions" block with the file contents |
| 13 | //! (or directory listings, or media-attachment hints) so the model can see |
| 14 | //! what the user pointed at. Capped per-message and per-file. |
| 15 | //! |
| 16 | //! The module is deliberately self-contained: nothing inside reaches into UI |
| 17 | //! widgets or rendering, so it stays unit-testable from `ui/tests.rs` and |
| 18 | //! from its own module-level tests. |
| 19 | //! |
| 20 | //! Pulled out of `ui.rs` to shrink the 5,500-line monolith and to give the |
| 21 | //! mention logic a single home that future maintainers can find without |
| 22 | //! grepping for `@` across half the codebase. |
| 23 | |
| 24 | use std::fmt::Write; |
| 25 | use std::io::Read; |
| 26 | use std::path::{Path, PathBuf}; |
| 27 | |
| 28 | use crate::tui::app::{App, MentionCompletionCache}; |
| 29 | use crate::tui::git_mention::{self, GitMentionCache, GitMentionKind}; |
| 30 | use crate::tui::mention_completion::{MentionDiscoveryBehavior, MentionDiscoveryKey}; |
| 31 | use codewhale_core::{ |
| 32 | ContextReference, ContextReferenceKind, ContextReferenceSource, MediaAttachmentReference, |
| 33 | media_attachment_references, |
| 34 | }; |
| 35 | use codewhale_localization::{Locale, MessageId, tr}; |
| 36 | use codewhale_runtime::working_set::Workspace; |
| 37 | |
| 38 | /// Maximum number of `@`-mentions whose contents are inlined into one user |
| 39 | /// message. Beyond this we stop appending blocks but the raw `@token` text |
| 40 | /// remains in the message. |
| 41 | pub const MAX_FILE_MENTIONS_PER_MESSAGE: usize = 8; |
| 42 | /// Per-file byte ceiling when inlining mention contents. |
| 43 | pub const MAX_MENTION_FILE_BYTES: u64 = 128 * 1024; |
| 44 | /// Per-directory entry ceiling when inlining a directory listing. |
| 45 | pub const MAX_DIRECTORY_MENTION_ENTRIES: usize = 80; |
| 46 | const MAX_DIRECTORY_MENTION_SCAN: usize = 10_000; |
| 47 | const MAX_MENTION_RANGE_SCAN_BYTES: u64 = 64 * 1024 * 1024; |
| 48 | |
| 49 | /// Maximum file-mention completion candidates to consider per keypress. Caps |
| 50 | /// the cost of walking large workspaces; subsequent keystrokes narrow further. |
| 51 | const FILE_MENTION_COMPLETION_LIMIT: usize = 64; |
| 52 | |
| 53 | /// Compact composer preview row for local context. `included=false` also |
| 54 | /// covers lexical `@` mentions whose exact inclusion is resolved on send. |
| 55 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 56 | pub struct FileMentionPreview { |
| 57 | pub kind: String, |
| 58 | pub label: String, |
| 59 | pub detail: Option<String>, |
| 60 | pub included: bool, |
| 61 | pub removable: bool, |
| 62 | } |
| 63 | |
| 64 | // --------------------------------------------------------------------------- |
| 65 | // Tab-completion |
| 66 | // --------------------------------------------------------------------------- |
| 67 | |
| 68 | /// If the cursor sits inside a `@<partial>` token in the input, return the |
| 69 | /// byte offset where the `@` starts (so we can splice in a completion) and |
| 70 | /// the partial path the user has typed so far. The token stops at whitespace |
| 71 | /// or the end of input. Returns `None` when the cursor is outside any mention |
| 72 | /// or the token is empty (`@` with nothing after it). |
| 73 | pub fn partial_file_mention_at_cursor(input: &str, cursor_chars: usize) -> Option<(usize, String)> { |
| 74 | let chars: Vec<char> = input.chars().collect(); |
| 75 | if cursor_chars > chars.len() { |
| 76 | return None; |
| 77 | } |
| 78 | // Walk left from the cursor until we find an `@` or a whitespace; if |
| 79 | // whitespace comes first the cursor isn't inside a mention. |
| 80 | let mut start_chars = cursor_chars; |
| 81 | while start_chars > 0 { |
| 82 | let prev = chars[start_chars - 1]; |
| 83 | if prev == '@' { |
| 84 | start_chars -= 1; |
| 85 | break; |
| 86 | } |
| 87 | if prev.is_whitespace() { |
| 88 | return None; |
| 89 | } |
| 90 | start_chars -= 1; |
| 91 | } |
| 92 | if start_chars == cursor_chars || chars.get(start_chars) != Some(&'@') { |
| 93 | return None; |
| 94 | } |
| 95 | // Confirm the `@` itself is at a valid mention boundary. |
| 96 | if !is_file_mention_start(&chars, start_chars) { |
| 97 | return None; |
| 98 | } |
| 99 | // Consume from the `@` to the next whitespace (the end of the token). |
| 100 | let mut end_chars = start_chars + 1; |
| 101 | while end_chars < chars.len() && !chars[end_chars].is_whitespace() { |
| 102 | end_chars += 1; |
| 103 | } |
| 104 | let partial: String = chars[start_chars + 1..end_chars].iter().collect(); |
| 105 | let byte_start: usize = chars[..start_chars].iter().map(|c| c.len_utf8()).sum(); |
| 106 | Some((byte_start, partial)) |
| 107 | } |
| 108 | |
| 109 | /// The mention body for `path`: bare when [`extract_file_mentions`] reads |
| 110 | /// it back unchanged, otherwise wrapped in the quoted form it also parses |
| 111 | /// (`@"My Docs/notes.md"`). A bare path with a space would split into a |
| 112 | /// missing-file mention for its first word. |
| 113 | pub(crate) fn file_mention_body(path: &str) -> String { |
| 114 | let bare_round_trips = !path.is_empty() |
| 115 | && !path.chars().any(char::is_whitespace) |
| 116 | && !path.starts_with(['"', '\'']) |
| 117 | && trim_unquoted_mention(path) == path; |
| 118 | if bare_round_trips { |
| 119 | path.to_string() |
| 120 | } else if !path.contains('"') { |
| 121 | format!("\"{path}\"") |
| 122 | } else if !path.contains('\'') { |
| 123 | format!("'{path}'") |
| 124 | } else { |
| 125 | path.to_string() |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | /// Cwd-aware completion entry point. Shares its walker with the future |
| 130 | /// Ctrl+P fuzzy picker (#97); see [`Workspace::completions`] for the |
| 131 | /// ranking + display rules. |
| 132 | #[cfg(test)] |
| 133 | pub fn find_file_mention_completions( |
| 134 | workspace: &Workspace, |
| 135 | partial: &str, |
| 136 | limit: usize, |
| 137 | ) -> Vec<String> { |
| 138 | let entries = workspace.completions(partial, limit); |
| 139 | // #441: re-rank by frecency so files the user mentions a lot float up. |
| 140 | // Never-mentioned candidates fall back to the workspace ranker's order. |
| 141 | let entries = super::file_frecency::rerank_by_frecency(&workspace.root, entries); |
| 142 | tracing::debug!( |
| 143 | target: "codewhale_tui::file_mention", |
| 144 | partial = %partial, |
| 145 | workspace = %workspace.root.display(), |
| 146 | cwd = ?std::env::current_dir().ok(), |
| 147 | match_count = entries.len(), |
| 148 | "file mention completion walk", |
| 149 | ); |
| 150 | entries |
| 151 | } |
| 152 | |
| 153 | /// Resolve the `@`-mention completion popup contents for the current |
| 154 | /// composer state. Returns an empty `Vec` when: |
| 155 | /// |
| 156 | /// - The popup is suppressed (`app.mention_menu_hidden`). |
| 157 | /// - The cursor is not inside an `@<partial>` token. |
| 158 | /// - The workspace walk produced no candidates. |
| 159 | /// |
| 160 | /// Mirrors `visible_slash_menu_entries` so the composer widget can treat |
| 161 | /// both menus identically (one `Vec<String>` of entries, one selected index). |
| 162 | /// |
| 163 | /// Once the composer widget is extended to render this as a popup, it will |
| 164 | /// pair with `apply_mention_menu_selection` for the Up/Down/Enter flow. |
| 165 | #[must_use] |
| 166 | pub fn visible_mention_menu_entries(app: &mut App, limit: usize) -> Vec<String> { |
| 167 | if app.mention_menu_hidden { |
| 168 | app.composer.mention_discovery.cancel(); |
| 169 | return Vec::new(); |
| 170 | } |
| 171 | let Some((_byte_start, partial)) = |
| 172 | partial_file_mention_at_cursor(&app.input, app.cursor_position) |
| 173 | else { |
| 174 | app.composer.mention_discovery.cancel(); |
| 175 | return Vec::new(); |
| 176 | }; |
| 177 | if limit == 0 { |
| 178 | app.composer.mention_discovery.cancel(); |
| 179 | return Vec::new(); |
| 180 | } |
| 181 | |
| 182 | mention_menu_entries(app, &partial, limit).0 |
| 183 | } |
| 184 | |
| 185 | /// Drain a completed discovery result without waiting. The event loop calls |
| 186 | /// this once per tick so a finished scan repaints the popup even when the user |
| 187 | /// has stopped typing. |
| 188 | pub(crate) fn poll_background_mention_discovery(app: &mut App) -> bool { |
| 189 | let discovered = app.composer.mention_discovery.poll(); |
| 190 | let frecency_loaded = super::file_frecency::poll_loaded(); |
| 191 | if discovered || frecency_loaded { |
| 192 | app.composer.mention_completion_cache = None; |
| 193 | return true; |
| 194 | } |
| 195 | false |
| 196 | } |
| 197 | |
| 198 | /// Return `(entries, ready)`. `ready = false` means discovery is still in the |
| 199 | /// background; callers must not misreport that temporary empty result as "no |
| 200 | /// matches". |
| 201 | fn mention_menu_entries(app: &mut App, partial: &str, limit: usize) -> (Vec<String>, bool) { |
| 202 | if poll_background_mention_discovery(app) { |
| 203 | app.needs_redraw = true; |
| 204 | } |
| 205 | |
| 206 | let workspace = app.workspace.clone(); |
| 207 | let cwd = app.composer.mention_cwd.clone(); |
| 208 | let walk_depth = app.mention_walk_depth; |
| 209 | let behavior = app.mention_menu_behavior.clone(); |
| 210 | let follow_links = app.workspace_follow_symlinks; |
| 211 | let discovery_key = if behavior == "browser" { |
| 212 | MentionDiscoveryKey::browser( |
| 213 | workspace.clone(), |
| 214 | cwd.clone(), |
| 215 | walk_depth, |
| 216 | follow_links, |
| 217 | partial.to_string(), |
| 218 | ) |
| 219 | } else { |
| 220 | MentionDiscoveryKey::fuzzy(workspace.clone(), cwd.clone(), walk_depth, follow_links) |
| 221 | }; |
| 222 | app.composer |
| 223 | .mention_discovery |
| 224 | .ensure_requested(discovery_key.clone()); |
| 225 | |
| 226 | if let Some(ref cache) = app.composer.mention_completion_cache |
| 227 | && cache.workspace == workspace |
| 228 | && cache.cwd == cwd |
| 229 | && cache.partial == partial |
| 230 | && cache.limit == limit |
| 231 | && cache.walk_depth == walk_depth |
| 232 | && cache.behavior == behavior |
| 233 | && cache.follow_links == follow_links |
| 234 | { |
| 235 | return (cache.entries.clone(), true); |
| 236 | } |
| 237 | |
| 238 | let Some(candidates) = app |
| 239 | .composer |
| 240 | .mention_discovery |
| 241 | .cached_entries(&discovery_key) |
| 242 | else { |
| 243 | return (Vec::new(), false); |
| 244 | }; |
| 245 | let entries = match &discovery_key.behavior { |
| 246 | MentionDiscoveryBehavior::Fuzzy => { |
| 247 | let ranked = codewhale_runtime::working_set::rank_completion_candidates( |
| 248 | candidates, partial, limit, |
| 249 | ); |
| 250 | super::file_frecency::rerank_by_frecency(&workspace, ranked) |
| 251 | } |
| 252 | MentionDiscoveryBehavior::Browser { .. } => { |
| 253 | candidates.iter().take(limit).cloned().collect() |
| 254 | } |
| 255 | }; |
| 256 | |
| 257 | let entries = with_git_mention_entries(entries, partial, limit); |
| 258 | |
| 259 | app.composer.mention_completion_cache = Some(MentionCompletionCache { |
| 260 | workspace, |
| 261 | cwd, |
| 262 | partial: partial.to_string(), |
| 263 | limit, |
| 264 | walk_depth, |
| 265 | behavior, |
| 266 | follow_links, |
| 267 | entries: entries.clone(), |
| 268 | }); |
| 269 | |
| 270 | (entries, true) |
| 271 | } |
| 272 | |
| 273 | /// Prepend the `@git` / `@diff` tokens that prefix-match `partial` to the path |
| 274 | /// completions, so curated git context is discoverable from the same menu as |
| 275 | /// files (#4067). They lead because a two-entry prefix match is what the user |
| 276 | /// meant when they typed `gi` or `di`, and paths still fill the rest. |
| 277 | /// |
| 278 | /// A bare `@` is deliberately left alone: that menu is the file picker, and |
| 279 | /// pushing two fixed tokens above every path would cost a slot on every |
| 280 | /// mention the user makes. The tokens appear as soon as a matching character |
| 281 | /// is typed. |
| 282 | fn with_git_mention_entries(entries: Vec<String>, partial: &str, limit: usize) -> Vec<String> { |
| 283 | // `mention_menu_limit = 0` is a documented way to disable the popup |
| 284 | // entirely. The git tokens are menu entries like any other and must |
| 285 | // respect the same cap, or setting 0 would still pop a one-entry menu. |
| 286 | if limit == 0 { |
| 287 | return Vec::new(); |
| 288 | } |
| 289 | let needle = partial.trim().to_lowercase(); |
| 290 | if needle.is_empty() { |
| 291 | return entries; |
| 292 | } |
| 293 | let matching: Vec<String> = GitMentionKind::iter_all() |
| 294 | .filter(|kind| kind.token().starts_with(&needle)) |
| 295 | .map(|kind| kind.token().to_string()) |
| 296 | .collect(); |
| 297 | if matching.is_empty() { |
| 298 | return entries; |
| 299 | } |
| 300 | let mut combined = matching; |
| 301 | combined.truncate(limit); |
| 302 | for entry in entries { |
| 303 | if combined.len() >= limit { |
| 304 | break; |
| 305 | } |
| 306 | if !combined.contains(&entry) { |
| 307 | combined.push(entry); |
| 308 | } |
| 309 | } |
| 310 | combined |
| 311 | } |
| 312 | |
| 313 | /// Apply the currently selected `@`-mention popup entry to the composer |
| 314 | /// input, splicing it in place of the `@<partial>` token at the cursor. |
| 315 | /// Returns `true` if a substitution occurred. |
| 316 | /// |
| 317 | /// Designed to be invoked by the same keybinding that drives |
| 318 | /// `apply_slash_menu_selection` (Enter / Tab); the caller is responsible |
| 319 | /// for choosing which menu is "active" based on cursor context. |
| 320 | pub fn apply_mention_menu_selection(app: &mut App, entries: &[String]) -> bool { |
| 321 | if entries.is_empty() { |
| 322 | return false; |
| 323 | } |
| 324 | let Some((byte_start, partial)) = |
| 325 | partial_file_mention_at_cursor(&app.input, app.cursor_position) |
| 326 | else { |
| 327 | return false; |
| 328 | }; |
| 329 | let selected_idx = app |
| 330 | .mention_menu_selected |
| 331 | .min(entries.len().saturating_sub(1)); |
| 332 | let replacement = &entries[selected_idx]; |
| 333 | // #441: bump this path's frecency before we splice it in. The store |
| 334 | // persists asynchronously, so this never blocks input handling. |
| 335 | super::file_frecency::record_mention(&app.workspace, replacement); |
| 336 | replace_file_mention(app, byte_start, &partial, &file_mention_body(replacement)); |
| 337 | app.mention_menu_hidden = false; |
| 338 | app.show_input_hint( |
| 339 | tr(app.ui_locale, MessageId::MentionAttached).replace("{path}", replacement), |
| 340 | ); |
| 341 | true |
| 342 | } |
| 343 | |
| 344 | /// Tab-completion handler for `@file` mentions. Mirrors the slash-command |
| 345 | /// flow: a single match is applied directly; multiple matches with a longer |
| 346 | /// shared prefix extend the partial; otherwise the first few candidates are |
| 347 | /// surfaced via the status line. Returns true when the input was modified or |
| 348 | /// a suggestion was offered, so the caller can short-circuit other handlers. |
| 349 | pub fn try_autocomplete_file_mention(app: &mut App) -> bool { |
| 350 | let Some((byte_start, partial)) = |
| 351 | partial_file_mention_at_cursor(&app.input, app.cursor_position) |
| 352 | else { |
| 353 | return false; |
| 354 | }; |
| 355 | let (candidates, ready) = mention_menu_entries(app, &partial, FILE_MENTION_COMPLETION_LIMIT); |
| 356 | if !ready { |
| 357 | return true; |
| 358 | } |
| 359 | if candidates.is_empty() { |
| 360 | app.show_input_hint(no_file_mention_matches_status( |
| 361 | app.ui_locale, |
| 362 | &partial, |
| 363 | app.mention_walk_depth, |
| 364 | )); |
| 365 | return true; |
| 366 | } |
| 367 | if candidates.len() == 1 { |
| 368 | // #441: a unique-match completion is also a "mention" for ranking. |
| 369 | super::file_frecency::record_mention(&app.workspace, &candidates[0]); |
| 370 | replace_file_mention( |
| 371 | app, |
| 372 | byte_start, |
| 373 | &partial, |
| 374 | &file_mention_body(&candidates[0]), |
| 375 | ); |
| 376 | app.show_input_hint( |
| 377 | tr(app.ui_locale, MessageId::MentionAttached).replace("{path}", &candidates[0]), |
| 378 | ); |
| 379 | return true; |
| 380 | } |
| 381 | let candidate_refs: Vec<&str> = candidates.iter().map(String::as_str).collect(); |
| 382 | // Extend only up to the first whitespace: the partial token ends there, |
| 383 | // so `@My Do` would leave a missing `@My` mention and a dead next Tab. |
| 384 | // Paths with spaces are completed whole (and quoted) by the unique-match |
| 385 | // branch or the mention menu. |
| 386 | let shared = longest_common_prefix(&candidate_refs); |
| 387 | let shared = shared |
| 388 | .find(char::is_whitespace) |
| 389 | .map_or(shared, |idx| &shared[..idx]); |
| 390 | if shared.len() > partial.len() { |
| 391 | replace_file_mention(app, byte_start, &partial, shared); |
| 392 | app.show_input_hint(format!("@{shared}…")); |
| 393 | return true; |
| 394 | } |
| 395 | let preview = candidates |
| 396 | .iter() |
| 397 | .take(5) |
| 398 | .map(|c| format!("@{c}")) |
| 399 | .collect::<Vec<_>>() |
| 400 | .join(", "); |
| 401 | app.show_input_hint( |
| 402 | tr(app.ui_locale, MessageId::MentionMatches).replace("{preview}", &preview), |
| 403 | ); |
| 404 | true |
| 405 | } |
| 406 | |
| 407 | fn no_file_mention_matches_status(locale: Locale, partial: &str, walk_depth: usize) -> String { |
| 408 | let id = if path_partial_reaches_walk_depth(partial, walk_depth) { |
| 409 | MessageId::MentionNoMatchesDepth |
| 410 | } else { |
| 411 | MessageId::MentionNoMatches |
| 412 | }; |
| 413 | tr(locale, id) |
| 414 | .replace("{partial}", partial) |
| 415 | .replace("{walk_depth}", &walk_depth.to_string()) |
| 416 | } |
| 417 | |
| 418 | fn path_partial_reaches_walk_depth(partial: &str, walk_depth: usize) -> bool { |
| 419 | if walk_depth == 0 { |
| 420 | return false; |
| 421 | } |
| 422 | let component_count = partial |
| 423 | .split(['/', '\\']) |
| 424 | .filter(|component| !component.is_empty()) |
| 425 | .count(); |
| 426 | component_count >= walk_depth |
| 427 | } |
| 428 | |
| 429 | /// Splice a completion into the input, replacing the `@<partial>` token at |
| 430 | /// `byte_start` with `@<replacement>`. Cursor moves to the end of the new |
| 431 | /// token so further keystrokes extend (or escape via space) naturally. |
| 432 | fn replace_file_mention(app: &mut App, byte_start: usize, partial: &str, replacement: &str) { |
| 433 | let original_token_len = '@'.len_utf8() + partial.len(); |
| 434 | let original_token_end = byte_start + original_token_len; |
| 435 | let mut new_input = |
| 436 | String::with_capacity(app.input.len() - original_token_len + 1 + replacement.len()); |
| 437 | new_input.push_str(&app.input[..byte_start]); |
| 438 | new_input.push('@'); |
| 439 | new_input.push_str(replacement); |
| 440 | if original_token_end < app.input.len() { |
| 441 | new_input.push_str(&app.input[original_token_end..]); |
| 442 | } |
| 443 | let new_cursor_chars = |
| 444 | app.input[..byte_start].chars().count() + 1 + replacement.chars().count(); |
| 445 | app.input = new_input; |
| 446 | app.cursor_position = new_cursor_chars; |
| 447 | } |
| 448 | |
| 449 | pub fn longest_common_prefix<'a>(values: &[&'a str]) -> &'a str { |
| 450 | let Some(first) = values.first().copied() else { |
| 451 | return ""; |
| 452 | }; |
| 453 | let mut end = first.len(); |
| 454 | |
| 455 | for value in values.iter().skip(1) { |
| 456 | while end > 0 && !value.starts_with(&first[..end]) { |
| 457 | end -= 1; |
| 458 | // Ensure we land on a valid UTF-8 char boundary. |
| 459 | while end > 0 && !first.is_char_boundary(end) { |
| 460 | end -= 1; |
| 461 | } |
| 462 | } |
| 463 | if end == 0 { |
| 464 | return ""; |
| 465 | } |
| 466 | } |
| 467 | |
| 468 | &first[..end] |
| 469 | } |
| 470 | |
| 471 | // --------------------------------------------------------------------------- |
| 472 | // Expansion at send-time |
| 473 | // --------------------------------------------------------------------------- |
| 474 | |
| 475 | /// Append a "Local context from @mentions" block to the user's message when |
| 476 | /// any `@path` references are present. Returns the input unchanged when |
| 477 | /// there are none. |
| 478 | /// |
| 479 | /// `cwd` carries the user's launch directory and drives the second |
| 480 | /// resolution pass (issue #101): relative `@<path>` mentions resolve under |
| 481 | /// `cwd` when `workspace.join(path)` doesn't exist, so the user's mental |
| 482 | /// anchor (their shell's pwd) wins when it diverges from `--workspace`. |
| 483 | /// Pass `None` to disable the cwd pass entirely (workspace-only). |
| 484 | /// |
| 485 | /// Resolution here never walks the tree on submit (#4365). A miss on the |
| 486 | /// exact two-pass lookup falls back to a bounded, unique-match-only search of |
| 487 | /// the composer's already-built background completion index |
| 488 | /// (`completion_index`, when the caller has one cached); the winning |
| 489 | /// candidate must still exist on disk. Ambiguous, stale, or absent matches |
| 490 | /// stay an honest `<missing-file>` that names only what the user typed — |
| 491 | /// never a fabricated workspace-root path. |
| 492 | /// |
| 493 | /// Convenience wrapper that allocates a throwaway cache. Test-only: the real |
| 494 | /// send paths share one cache across the references and payload passes. |
| 495 | #[cfg(test)] |
| 496 | pub fn user_request_with_file_mentions( |
| 497 | input: &str, |
| 498 | workspace: &Path, |
| 499 | cwd: Option<PathBuf>, |
| 500 | ) -> String { |
| 501 | user_request_with_file_mentions_cached( |
| 502 | input, |
| 503 | workspace, |
| 504 | cwd, |
| 505 | &mut GitMentionCache::default(), |
| 506 | None, |
| 507 | ) |
| 508 | } |
| 509 | |
| 510 | pub fn user_request_with_file_mentions_cached( |
| 511 | input: &str, |
| 512 | workspace: &Path, |
| 513 | cwd: Option<PathBuf>, |
| 514 | git_cache: &mut GitMentionCache, |
| 515 | completion_index: Option<&[String]>, |
| 516 | ) -> String { |
| 517 | let Some(context) = |
| 518 | local_context_from_file_mentions(input, workspace, cwd, git_cache, completion_index) |
| 519 | else { |
| 520 | return input.to_string(); |
| 521 | }; |
| 522 | format!("{input}\n\n---\n\nLocal context from @mentions:\n{context}") |
| 523 | } |
| 524 | |
| 525 | #[must_use] |
| 526 | pub fn pending_context_previews(input: &str, locale: Locale) -> Vec<FileMentionPreview> { |
| 527 | let mut previews = Vec::new(); |
| 528 | let mut seen = std::collections::HashSet::new(); |
| 529 | let resolved_on_send = tr(locale, MessageId::ComposerContextResolvedOnSend); |
| 530 | for mention in extract_file_mentions(input) |
| 531 | .into_iter() |
| 532 | .take(MAX_FILE_MENTIONS_PER_MESSAGE) |
| 533 | { |
| 534 | if !seen.insert(mention.clone()) { |
| 535 | continue; |
| 536 | } |
| 537 | // Composer previews stay lexical (no git subprocess from the render |
| 538 | // loop, same rule as #4365 for path stats); the payload is resolved |
| 539 | // once at submit time. |
| 540 | if let Some(kind) = git_mention::git_mention_kind(&mention) { |
| 541 | previews.push(FileMentionPreview { |
| 542 | kind: "git".to_string(), |
| 543 | label: kind.label().to_string(), |
| 544 | detail: Some(resolved_on_send.to_string()), |
| 545 | included: false, |
| 546 | removable: false, |
| 547 | }); |
| 548 | continue; |
| 549 | } |
| 550 | let media = is_media_path(Path::new(&mention)); |
| 551 | previews.push(FileMentionPreview { |
| 552 | kind: if media { "media" } else { "mention" }.to_string(), |
| 553 | label: mention, |
| 554 | detail: Some(if media { |
| 555 | "use /attach for media bytes".to_string() |
| 556 | } else { |
| 557 | resolved_on_send.to_string() |
| 558 | }), |
| 559 | // Lexical preview deliberately does not stat the path while the |
| 560 | // user types. Exact inclusion/missing metadata is resolved once, |
| 561 | // at submit time, rather than from the render loop (#4365). |
| 562 | included: false, |
| 563 | removable: false, |
| 564 | }); |
| 565 | } |
| 566 | |
| 567 | for attachment in extract_media_attachment_references(input) { |
| 568 | previews.push(FileMentionPreview { |
| 569 | kind: attachment.kind, |
| 570 | label: attachment.path, |
| 571 | detail: Some("attached media".to_string()), |
| 572 | included: true, |
| 573 | removable: true, |
| 574 | }); |
| 575 | } |
| 576 | previews |
| 577 | } |
| 578 | |
| 579 | /// Convenience wrapper that allocates a throwaway cache. Test-only, as above. |
| 580 | #[cfg(test)] |
| 581 | #[must_use] |
| 582 | pub fn context_references_from_input( |
| 583 | input: &str, |
| 584 | workspace: &Path, |
| 585 | cwd: Option<PathBuf>, |
| 586 | ) -> Vec<ContextReference> { |
| 587 | context_references_from_input_cached( |
| 588 | input, |
| 589 | workspace, |
| 590 | cwd, |
| 591 | &mut GitMentionCache::default(), |
| 592 | None, |
| 593 | ) |
| 594 | } |
| 595 | |
| 596 | #[must_use] |
| 597 | pub fn context_references_from_input_cached( |
| 598 | input: &str, |
| 599 | workspace: &Path, |
| 600 | cwd: Option<PathBuf>, |
| 601 | git_cache: &mut GitMentionCache, |
| 602 | completion_index: Option<&[String]>, |
| 603 | ) -> Vec<ContextReference> { |
| 604 | let mut references = Vec::new(); |
| 605 | let mut seen = std::collections::HashSet::new(); |
| 606 | let ws = Workspace::with_cwd(workspace.to_path_buf(), cwd); |
| 607 | |
| 608 | for mention in extract_file_mentions(input) |
| 609 | .into_iter() |
| 610 | .take(MAX_FILE_MENTIONS_PER_MESSAGE) |
| 611 | { |
| 612 | // Git mentions resolve against the working tree, not the path index, |
| 613 | // so the inspector reports their real size and budget (#4067). |
| 614 | if let Some(kind) = git_mention::git_mention_kind(&mention) { |
| 615 | let payload = git_cache.resolve(kind, workspace).clone(); |
| 616 | let detail = match payload.unavailable_reason.as_deref() { |
| 617 | Some(reason) => format!("{}, {reason}", kind.label()), |
| 618 | None if payload.truncated => format!( |
| 619 | "{}, {} bytes truncated at {} budget", |
| 620 | kind.label(), |
| 621 | payload.bytes, |
| 622 | kind.byte_budget() |
| 623 | ), |
| 624 | None => format!("{}, {} bytes", kind.label(), payload.bytes), |
| 625 | }; |
| 626 | let reference = ContextReference { |
| 627 | kind: ContextReferenceKind::GitContext, |
| 628 | source: ContextReferenceSource::AtMention, |
| 629 | badge: "git".to_string(), |
| 630 | label: kind.token().to_string(), |
| 631 | target: workspace.display().to_string(), |
| 632 | included: payload.unavailable_reason.is_none(), |
| 633 | expanded: false, |
| 634 | detail: Some(detail), |
| 635 | }; |
| 636 | if seen.insert(format!("git-mention:{}", kind.token())) { |
| 637 | references.push(reference); |
| 638 | } |
| 639 | continue; |
| 640 | } |
| 641 | |
| 642 | let (path, display_path, exists) = |
| 643 | resolve_mention_for_send(&ws, &mention, completion_index); |
| 644 | let reference = context_reference_for_mention(&mention, &path, &display_path, exists); |
| 645 | if !seen.insert(format!( |
| 646 | "{:?}:{:?}:{}:{}", |
| 647 | reference.source, reference.kind, reference.target, reference.label |
| 648 | )) { |
| 649 | continue; |
| 650 | } |
| 651 | references.push(reference); |
| 652 | } |
| 653 | |
| 654 | for reference in extract_media_attachment_references(input) { |
| 655 | let context_reference = ContextReference { |
| 656 | kind: ContextReferenceKind::MediaAttachment, |
| 657 | source: ContextReferenceSource::Attachment, |
| 658 | badge: reference.kind, |
| 659 | label: reference.path.clone(), |
| 660 | target: reference.path, |
| 661 | included: true, |
| 662 | expanded: false, |
| 663 | detail: Some("attached media".to_string()), |
| 664 | }; |
| 665 | if !seen.insert(format!( |
| 666 | "{:?}:{:?}:{}:{}", |
| 667 | context_reference.source, |
| 668 | context_reference.kind, |
| 669 | context_reference.target, |
| 670 | context_reference.label |
| 671 | )) { |
| 672 | continue; |
| 673 | } |
| 674 | references.push(context_reference); |
| 675 | } |
| 676 | |
| 677 | references |
| 678 | } |
| 679 | |
| 680 | fn context_reference_for_mention( |
| 681 | raw: &str, |
| 682 | path: &Path, |
| 683 | display_path: &str, |
| 684 | exists: bool, |
| 685 | ) -> ContextReference { |
| 686 | if !exists { |
| 687 | return ContextReference { |
| 688 | kind: ContextReferenceKind::Missing, |
| 689 | source: ContextReferenceSource::AtMention, |
| 690 | badge: "missing".to_string(), |
| 691 | label: raw.to_string(), |
| 692 | // No resolved target exists; naming the workspace-root guess here |
| 693 | // would present a path we already know is wrong. |
| 694 | target: raw.to_string(), |
| 695 | included: false, |
| 696 | expanded: false, |
| 697 | detail: Some("not found".to_string()), |
| 698 | }; |
| 699 | } |
| 700 | if path.is_dir() { |
| 701 | return ContextReference { |
| 702 | kind: ContextReferenceKind::Directory, |
| 703 | source: ContextReferenceSource::AtMention, |
| 704 | badge: "dir".to_string(), |
| 705 | label: raw.to_string(), |
| 706 | target: display_path.to_string(), |
| 707 | included: true, |
| 708 | expanded: true, |
| 709 | detail: Some("directory listing".to_string()), |
| 710 | }; |
| 711 | } |
| 712 | if !path.is_file() { |
| 713 | return ContextReference { |
| 714 | kind: ContextReferenceKind::Unsupported, |
| 715 | source: ContextReferenceSource::AtMention, |
| 716 | badge: "skipped".to_string(), |
| 717 | label: raw.to_string(), |
| 718 | target: display_path.to_string(), |
| 719 | included: false, |
| 720 | expanded: false, |
| 721 | detail: Some("unsupported path".to_string()), |
| 722 | }; |
| 723 | } |
| 724 | if is_media_path(path) { |
| 725 | return ContextReference { |
| 726 | kind: ContextReferenceKind::MediaMention, |
| 727 | source: ContextReferenceSource::AtMention, |
| 728 | badge: "media".to_string(), |
| 729 | label: raw.to_string(), |
| 730 | target: display_path.to_string(), |
| 731 | included: false, |
| 732 | expanded: false, |
| 733 | detail: Some("use /attach for media bytes".to_string()), |
| 734 | }; |
| 735 | } |
| 736 | |
| 737 | let detail = match std::fs::metadata(path) { |
| 738 | Ok(metadata) if metadata.len() > MAX_MENTION_FILE_BYTES => { |
| 739 | Some("included truncated".to_string()) |
| 740 | } |
| 741 | Ok(_) => Some("included".to_string()), |
| 742 | Err(err) => Some(format!("metadata: {err}")), |
| 743 | }; |
| 744 | |
| 745 | ContextReference { |
| 746 | kind: ContextReferenceKind::File, |
| 747 | source: ContextReferenceSource::AtMention, |
| 748 | badge: "file".to_string(), |
| 749 | label: raw.to_string(), |
| 750 | target: display_path.to_string(), |
| 751 | included: true, |
| 752 | expanded: true, |
| 753 | detail: detail.or_else(|| Some(display_path.to_string())), |
| 754 | } |
| 755 | } |
| 756 | |
| 757 | fn extract_media_attachment_references(input: &str) -> Vec<MediaAttachmentReference> { |
| 758 | media_attachment_references(input) |
| 759 | } |
| 760 | |
| 761 | // --------------------------------------------------------------------------- |
| 762 | // macOS screencapture-temp stabilization |
| 763 | // --------------------------------------------------------------------------- |
| 764 | // |
| 765 | // macOS parks dragged-out screenshots under a per-capture temp directory like |
| 766 | // `/var/folders/…/T/Temporary Items/NSIRD_screencaptureui_XXXX/` (recent |
| 767 | // releases spell it `TemporaryItems`, without the space) and deletes |
| 768 | // it minutes later. Inbound references to such files are copied to a stable |
| 769 | // directory the moment the message is received, so the agent later reads a |
| 770 | // path that still exists. |
| 771 | |
| 772 | /// Marker fragments of the macOS screencapture temp directory layout. |
| 773 | const SCREENCAPTURE_TEMP_DIR_MARKERS: [&str; 2] = ["Temporary Items", "screencaptureui"]; |
| 774 | |
| 775 | /// The `Temporary Items` component as recent macOS releases spell it. |
| 776 | const SCREENCAPTURE_TEMP_DIR_COMPACT: &str = "TemporaryItems"; |
| 777 | |
| 778 | /// Stable per-session directory for stabilized screencapture files. Follows |
| 779 | /// the same home-first convention as `clipboard.rs`'s clipboard-images dir. |
| 780 | pub(crate) fn screenshot_stabilization_dir(workspace: &Path) -> PathBuf { |
| 781 | match codewhale_paths::user_home() { |
| 782 | Some(home) => home.join(".codewhale").join("attachments"), |
| 783 | None => workspace.join("attachments"), |
| 784 | } |
| 785 | } |
| 786 | |
| 787 | /// Whether a path lives under a macOS screencapture "Temporary Items" dir: |
| 788 | /// it must have a `Temporary Items` component and a `screencaptureui`-named |
| 789 | /// component (e.g. `NSIRD_screencaptureui_XXXX`), so ordinary user paths are |
| 790 | /// never touched even when their names contain either fragment. |
| 791 | fn is_screencapture_temp_path(path: &Path) -> bool { |
| 792 | let components: Vec<String> = path |
| 793 | .components() |
| 794 | .map(|c| c.as_os_str().to_string_lossy().into_owned()) |
| 795 | .collect(); |
| 796 | components |
| 797 | .iter() |
| 798 | .any(|c| c == SCREENCAPTURE_TEMP_DIR_MARKERS[0] || c == SCREENCAPTURE_TEMP_DIR_COMPACT) |
| 799 | && components |
| 800 | .iter() |
| 801 | .any(|c| c.contains(SCREENCAPTURE_TEMP_DIR_MARKERS[1])) |
| 802 | } |
| 803 | |
| 804 | /// Keep " at " out of a stable copy's name: `[Attached …: <desc> at <path>]` |
| 805 | /// uses it as the separator, and older parsers split at its last occurrence. |
| 806 | fn stable_attachment_name(file_name: &std::ffi::OsStr) -> String { |
| 807 | file_name.to_string_lossy().replace(" at ", "-") |
| 808 | } |
| 809 | |
| 810 | /// Largest screenshot copied to a stable location. |
| 811 | const MAX_STABLE_ATTACHMENT_BYTES: u64 = 64 * 1024 * 1024; |
| 812 | |
| 813 | /// Copy a screencapture temp file to `artifact_dir` and return the stable |
| 814 | /// destination. Returns `None` when the path is not a screencapture temp |
| 815 | /// file, not a regular file, or the copy fails — callers keep the original |
| 816 | /// reference then. Idempotent: an existing destination is reused without a |
| 817 | /// second copy. |
| 818 | /// |
| 819 | /// `artifact_dir` is `<root>/<name>`: the destination is written through the |
| 820 | /// pinned no-follow writer anchored at `root`, so a linked `artifact_dir`, a |
| 821 | /// linked destination, or a dangling link at the destination name is refused |
| 822 | /// instead of being written through. `root` itself may be a user-selected link |
| 823 | /// (a relocated `~/.codewhale`). |
| 824 | fn stabilize_screencapture_file(path: &Path, artifact_dir: &Path) -> Option<PathBuf> { |
| 825 | if !is_screencapture_temp_path(path) || !path.is_file() { |
| 826 | return None; |
| 827 | } |
| 828 | let name = stable_attachment_name(path.file_name()?); |
| 829 | let dest = artifact_dir.join(&name); |
| 830 | let relative = Path::new(artifact_dir.file_name()?).join(&name); |
| 831 | let root = artifact_dir.parent()?; |
| 832 | // `artifact_dir` sits under the user's own state root unless no home was |
| 833 | // available and it fell back to the workspace |
| 834 | // (`screenshot_stabilization_dir`). Only the state root may be a link the |
| 835 | // user made to relocate `~/.codewhale`. |
| 836 | let state_root = codewhale_paths::user_home() |
| 837 | .is_some_and(|home| root == home.join(codewhale_paths::CODEWHALE_APP_DIR)); |
| 838 | let open = if state_root { |
| 839 | codewhale_util::files::WorkspaceFile::open_resolved_root |
| 840 | } else { |
| 841 | codewhale_util::files::WorkspaceFile::open |
| 842 | }; |
| 843 | let target = match open(root, &relative, true) { |
| 844 | Ok(target) => target, |
| 845 | Err(error) => { |
| 846 | tracing::warn!(%error, "screenshot stabilization target unavailable"); |
| 847 | return None; |
| 848 | } |
| 849 | }; |
| 850 | // An existing regular destination is reused; a link there fails to open. |
| 851 | if target.open_file().is_ok() { |
| 852 | return Some(dest); |
| 853 | } |
| 854 | let bytes = match std::fs::metadata(path) { |
| 855 | Ok(metadata) if metadata.len() > MAX_STABLE_ATTACHMENT_BYTES => { |
| 856 | tracing::warn!(path = %path.display(), "screenshot too large to stabilize"); |
| 857 | return None; |
| 858 | } |
| 859 | Ok(_) => match std::fs::read(path) { |
| 860 | Ok(bytes) => bytes, |
| 861 | Err(error) => { |
| 862 | tracing::warn!(%error, path = %path.display(), "screenshot read failed"); |
| 863 | return None; |
| 864 | } |
| 865 | }, |
| 866 | Err(error) => { |
| 867 | tracing::warn!(%error, path = %path.display(), "screenshot metadata failed"); |
| 868 | return None; |
| 869 | } |
| 870 | }; |
| 871 | match target.publish(&bytes) { |
| 872 | Ok(()) => Some(dest), |
| 873 | // Lost a race to another writer of the same name: reuse only if what |
| 874 | // is there is a regular file we may open. |
| 875 | Err(error) |
| 876 | if error.kind() == std::io::ErrorKind::AlreadyExists && target.open_file().is_ok() => |
| 877 | { |
| 878 | Some(dest) |
| 879 | } |
| 880 | Err(error) => { |
| 881 | tracing::warn!(%error, "screenshot stabilization publish failed"); |
| 882 | None |
| 883 | } |
| 884 | } |
| 885 | } |
| 886 | |
| 887 | /// A path reference found in inbound text: its byte span, the path text, and |
| 888 | /// how it was carried (`@`-mention prefix and/or surrounding quotes). |
| 889 | struct ScreencaptureCandidate { |
| 890 | byte_start: usize, |
| 891 | byte_end: usize, |
| 892 | path: String, |
| 893 | quote: Option<char>, |
| 894 | mention: bool, |
| 895 | } |
| 896 | |
| 897 | /// Reconstruct a path that an unquoted paste split across whitespace tokens |
| 898 | /// (the "Temporary Items" component contains a space). Returns the char span |
| 899 | /// and joined path of the window that names an existing screencapture temp |
| 900 | /// file, bounded to a handful of tokens either side of `seed`. |
| 901 | fn screencapture_window( |
| 902 | chars: &[char], |
| 903 | tokens: &[(usize, usize)], |
| 904 | seed: usize, |
| 905 | ) -> Option<(usize, usize, String)> { |
| 906 | let max_span = tokens.len().min(12); |
| 907 | for left in 0..=seed.min(max_span) { |
| 908 | for right in 0..=max_span { |
| 909 | let end = (seed + right).min(tokens.len() - 1); |
| 910 | let (mut ws, mut we) = (tokens[seed - left].0, tokens[end].1); |
| 911 | let raw: String = chars[ws..we].iter().collect(); |
| 912 | // Trim leading delimiters and trailing punctuation against the |
| 913 | // raw span (advancing both ends), then collapse interior |
| 914 | // whitespace runs so the probe path matches the file. |
| 915 | let lead = raw |
| 916 | .chars() |
| 917 | .take_while(|&ch| matches!(ch, '(' | '[' | '{' | '<' | '"' | '\'' | '@')) |
| 918 | .count(); |
| 919 | let trimmed = trim_unquoted_mention(&raw); |
| 920 | ws += lead; |
| 921 | we -= raw.chars().count() - trimmed.chars().count(); |
| 922 | let joined = trimmed |
| 923 | .chars() |
| 924 | .skip(lead) |
| 925 | .collect::<String>() |
| 926 | .split_whitespace() |
| 927 | .collect::<Vec<_>>() |
| 928 | .join(" "); |
| 929 | let path = Path::new(&joined); |
| 930 | if is_screencapture_temp_path(path) && path.is_file() { |
| 931 | return Some((ws, we, joined)); |
| 932 | } |
| 933 | } |
| 934 | } |
| 935 | None |
| 936 | } |
| 937 | |
| 938 | /// Rewrite every inbound reference to a macOS screencapture temp file to a |
| 939 | /// stable copy under `artifact_dir`. Non-matching references — not a |
| 940 | /// screencapture path, missing, or an unresolvable copy — are left untouched; |
| 941 | /// the function never fails and never changes the message otherwise. |
| 942 | pub(crate) fn stabilize_screenshot_references(input: &str, artifact_dir: &Path) -> String { |
| 943 | let chars: Vec<char> = input.chars().collect(); |
| 944 | let offsets: Vec<usize> = input.char_indices().map(|(i, _)| i).collect(); |
| 945 | let mut candidates: Vec<ScreencaptureCandidate> = Vec::new(); |
| 946 | let mut i = 0; |
| 947 | while i < chars.len() { |
| 948 | match chars[i] { |
| 949 | // `@"quoted path"` / `@bare/path` mentions (mirror `extract_file_mentions`). |
| 950 | '@' if is_file_mention_start(&chars, i) => { |
| 951 | let byte_start = offsets[i]; |
| 952 | if let Some(quote @ ('"' | '\'')) = chars.get(i + 1).copied() |
| 953 | && let Some(rel) = chars[i + 2..].iter().position(|&ch| ch == quote) |
| 954 | { |
| 955 | let end = i + 2 + rel; |
| 956 | let path: String = chars[i + 2..end].iter().collect(); |
| 957 | if !path.trim().is_empty() { |
| 958 | candidates.push(ScreencaptureCandidate { |
| 959 | byte_start, |
| 960 | byte_end: offsets.get(end + 1).copied().unwrap_or(input.len()), |
| 961 | path: path.trim().to_string(), |
| 962 | quote: Some(quote), |
| 963 | mention: true, |
| 964 | }); |
| 965 | } |
| 966 | i = end + 1; |
| 967 | } else { |
| 968 | let mut end = i + 1; |
| 969 | while end < chars.len() && !chars[end].is_whitespace() { |
| 970 | end += 1; |
| 971 | } |
| 972 | let raw: String = chars[i + 1..end].iter().collect(); |
| 973 | let trimmed = trim_unquoted_mention(&raw); |
| 974 | if !trimmed.is_empty() { |
| 975 | candidates.push(ScreencaptureCandidate { |
| 976 | byte_start, |
| 977 | byte_end: offsets.get(end).copied().unwrap_or(input.len()), |
| 978 | path: trimmed.to_string(), |
| 979 | quote: None, |
| 980 | mention: true, |
| 981 | }); |
| 982 | } |
| 983 | i = end; |
| 984 | } |
| 985 | } |
| 986 | // Quoted strings: terminals quote drag-dropped paths with spaces. |
| 987 | // A closing quote is only sought on the same line, so a lone |
| 988 | // apostrophe in prose never swallows the rest of the message. |
| 989 | quote @ ('"' | '\'') => { |
| 990 | if let Some(rel) = chars[i + 1..] |
| 991 | .iter() |
| 992 | .take_while(|&&ch| ch != '\n') |
| 993 | .position(|&ch| ch == quote) |
| 994 | { |
| 995 | let end = i + 1 + rel; |
| 996 | let path: String = chars[i + 1..end].iter().collect(); |
| 997 | if !path.trim().is_empty() { |
| 998 | candidates.push(ScreencaptureCandidate { |
| 999 | byte_start: offsets[i], |
| 1000 | byte_end: offsets.get(end + 1).copied().unwrap_or(input.len()), |
| 1001 | path: path.trim().to_string(), |
| 1002 | quote: Some(quote), |
| 1003 | mention: false, |
| 1004 | }); |
| 1005 | } |
| 1006 | i = end + 1; |
| 1007 | } else { |
| 1008 | i += 1; |
| 1009 | } |
| 1010 | } |
| 1011 | _ => i += 1, |
| 1012 | } |
| 1013 | } |
| 1014 | |
| 1015 | // Bare unquoted pastes: rebuild the path across whitespace tokens. |
| 1016 | let tokens: Vec<(usize, usize)> = { |
| 1017 | let mut tokens = Vec::new(); |
| 1018 | let mut start = None; |
| 1019 | for (idx, ch) in chars.iter().enumerate() { |
| 1020 | match (ch.is_whitespace(), start) { |
| 1021 | (true, Some(s)) => { |
| 1022 | tokens.push((s, idx)); |
| 1023 | start = None; |
| 1024 | } |
| 1025 | (false, None) => start = Some(idx), |
| 1026 | _ => {} |
| 1027 | } |
| 1028 | } |
| 1029 | if let Some(s) = start { |
| 1030 | tokens.push((s, chars.len())); |
| 1031 | } |
| 1032 | tokens |
| 1033 | }; |
| 1034 | for (seed, &(token_start, token_end)) in tokens.iter().enumerate() { |
| 1035 | let token: String = chars[token_start..token_end].iter().collect(); |
| 1036 | if !(token.contains("screencaptureui") |
| 1037 | || token.contains("Temporary") |
| 1038 | || token.contains("Items")) |
| 1039 | { |
| 1040 | continue; |
| 1041 | } |
| 1042 | let Some((ws, we, path)) = screencapture_window(&chars, &tokens, seed) else { |
| 1043 | continue; |
| 1044 | }; |
| 1045 | let byte_end = offsets.get(we).copied().unwrap_or(input.len()); |
| 1046 | // Only suppress the window when it overlaps a candidate that is |
| 1047 | // itself a confirmed screencapture temp file (that candidate will |
| 1048 | // rewrite it); prose quoted with `'` never blocks a real reference. |
| 1049 | let confirmed = |c: &ScreencaptureCandidate| { |
| 1050 | is_screencapture_temp_path(Path::new(&c.path)) && Path::new(&c.path).is_file() |
| 1051 | }; |
| 1052 | let blocked = candidates |
| 1053 | .iter() |
| 1054 | .any(|c| c.byte_start < byte_end && offsets[ws] < c.byte_end && confirmed(c)); |
| 1055 | if !blocked { |
| 1056 | candidates.push(ScreencaptureCandidate { |
| 1057 | byte_start: offsets[ws], |
| 1058 | byte_end, |
| 1059 | path, |
| 1060 | quote: None, |
| 1061 | mention: false, |
| 1062 | }); |
| 1063 | } |
| 1064 | } |
| 1065 | |
| 1066 | // Apply last-to-first so byte spans stay valid. |
| 1067 | candidates.sort_by_key(|c| c.byte_start); |
| 1068 | let mut output = input.to_string(); |
| 1069 | for candidate in candidates.iter().rev() { |
| 1070 | let Some(dest) = stabilize_screencapture_file(Path::new(&candidate.path), artifact_dir) |
| 1071 | else { |
| 1072 | continue; |
| 1073 | }; |
| 1074 | let stable = dest.to_string_lossy(); |
| 1075 | let mut replacement = String::new(); |
| 1076 | if candidate.mention { |
| 1077 | replacement.push('@'); |
| 1078 | } |
| 1079 | if let Some(quote) = candidate.quote { |
| 1080 | replacement.push(quote); |
| 1081 | } |
| 1082 | replacement.push_str(stable.as_ref()); |
| 1083 | if let Some(quote) = candidate.quote { |
| 1084 | replacement.push(quote); |
| 1085 | } |
| 1086 | output.replace_range(candidate.byte_start..candidate.byte_end, &replacement); |
| 1087 | } |
| 1088 | output |
| 1089 | } |
| 1090 | |
| 1091 | fn local_context_from_file_mentions( |
| 1092 | input: &str, |
| 1093 | workspace: &Path, |
| 1094 | cwd: Option<PathBuf>, |
| 1095 | git_cache: &mut GitMentionCache, |
| 1096 | completion_index: Option<&[String]>, |
| 1097 | ) -> Option<String> { |
| 1098 | let mentions = extract_file_mentions(input); |
| 1099 | if mentions.is_empty() { |
| 1100 | return None; |
| 1101 | } |
| 1102 | |
| 1103 | let mut blocks = Vec::new(); |
| 1104 | let mut seen = std::collections::HashSet::new(); |
| 1105 | let ws = Workspace::with_cwd(workspace.to_path_buf(), cwd); |
| 1106 | |
| 1107 | for mention in mentions.into_iter().take(MAX_FILE_MENTIONS_PER_MESSAGE) { |
| 1108 | // `@git` / `@diff` resolve to curated git context, not to a path, so |
| 1109 | // they short-circuit before any workspace path resolution (#4067). |
| 1110 | if let Some(kind) = git_mention::git_mention_kind(&mention) { |
| 1111 | if !seen.insert(format!("git-mention:{}", kind.token())) { |
| 1112 | continue; |
| 1113 | } |
| 1114 | blocks.push(git_cache.resolve(kind, workspace).block.clone()); |
| 1115 | continue; |
| 1116 | } |
| 1117 | |
| 1118 | // `@path:START-END` attaches a line range of a file (issue #5550). |
| 1119 | // Exact resolution wins first: a file that literally contains a colon |
| 1120 | // is treated as its full self. Only a genuine miss re-reads the token |
| 1121 | // as `path:START-END`. |
| 1122 | let mut range = None; |
| 1123 | let mut mention_path = mention.as_str(); |
| 1124 | // `Workspace::resolve_exact` already returns absolute paths when the root |
| 1125 | // is absolute (TUI always runs from an absolute workspace), so we |
| 1126 | // skip `canonicalize()` here — it's per-mention I/O on the |
| 1127 | // message-send hot path. Accept the rare symlink-aliasing dedup |
| 1128 | // miss as the cost of avoiding a syscall (Gemini code-review). |
| 1129 | let (mut path, mut display_path, mut exists) = |
| 1130 | resolve_mention_for_send(&ws, mention_path, completion_index); |
| 1131 | if !exists && let Some((path_part, parsed)) = split_mention_range(&mention) { |
| 1132 | let (ranged_path, ranged_display, ranged_exists) = |
| 1133 | resolve_mention_for_send(&ws, path_part, completion_index); |
| 1134 | if ranged_exists { |
| 1135 | range = Some(parsed); |
| 1136 | mention_path = path_part; |
| 1137 | (path, display_path, exists) = (ranged_path, ranged_display, ranged_exists); |
| 1138 | } |
| 1139 | } |
| 1140 | tracing::debug!( |
| 1141 | target: "codewhale_tui::file_mention", |
| 1142 | raw_typed = %mention, |
| 1143 | workspace = %workspace.display(), |
| 1144 | cwd = ?std::env::current_dir().ok(), |
| 1145 | resolved = %display_path, |
| 1146 | exists, |
| 1147 | "file mention resolution", |
| 1148 | ); |
| 1149 | |
| 1150 | // Gate every block — including <missing-file> — through the dedup |
| 1151 | // set so a user typing the same non-existent file twice doesn't |
| 1152 | // waste tokens on duplicate missing-file blocks (Devin code-review). |
| 1153 | // Missing mentions dedup on the typed token: there is no resolved |
| 1154 | // path to key on, and the workspace-root guess must not become one. |
| 1155 | let dedup_key = if exists { |
| 1156 | match range { |
| 1157 | Some(FileRange { start, end }) => format!("{display_path}\0{start}-{end}"), |
| 1158 | None => display_path.clone(), |
| 1159 | } |
| 1160 | } else { |
| 1161 | format!("missing:{mention}") |
| 1162 | }; |
| 1163 | if !seen.insert(dedup_key) { |
| 1164 | continue; |
| 1165 | } |
| 1166 | |
| 1167 | if exists { |
| 1168 | blocks.push(render_file_mention_context( |
| 1169 | mention_path, |
| 1170 | &path, |
| 1171 | &display_path, |
| 1172 | range, |
| 1173 | )); |
| 1174 | } else { |
| 1175 | // Honest miss: name only what the user typed. Emitting the |
| 1176 | // workspace-root join as `path=` presented a non-existent file |
| 1177 | // as if it were the resolved target. |
| 1178 | blocks.push(format!("<missing-file mention=\"@{mention}\" />")); |
| 1179 | } |
| 1180 | } |
| 1181 | |
| 1182 | if blocks.is_empty() { |
| 1183 | None |
| 1184 | } else { |
| 1185 | Some(blocks.join("\n\n")) |
| 1186 | } |
| 1187 | } |
| 1188 | |
| 1189 | /// Endpoints of a `@path:START-END` mention (1-based, inclusive). |
| 1190 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 1191 | pub(crate) struct FileRange { |
| 1192 | pub start: u32, |
| 1193 | pub end: u32, |
| 1194 | } |
| 1195 | |
| 1196 | /// Split a trailing `:START-END` range off a mention token. |
| 1197 | /// |
| 1198 | /// Only an exact `digits-digits` suffix after a non-empty path part is |
| 1199 | /// treated as a range, so `notes.txt`, `x:1`, `x:a-b`, `:1-2`, and Windows |
| 1200 | /// `C:\\dir\\file` (digits requirement) all stay whole. The caller must have |
| 1201 | /// already failed an exact path resolution for the full token before calling. |
| 1202 | fn split_mention_range(raw: &str) -> Option<(&str, FileRange)> { |
| 1203 | let (path_part, range_part) = raw.rsplit_once(':')?; |
| 1204 | if path_part.is_empty() { |
| 1205 | return None; |
| 1206 | } |
| 1207 | let (start, end) = range_part.split_once('-')?; |
| 1208 | if start.is_empty() |
| 1209 | || end.is_empty() |
| 1210 | || !start.bytes().all(|b| b.is_ascii_digit()) |
| 1211 | || !end.bytes().all(|b| b.is_ascii_digit()) |
| 1212 | || start.len() > 5 |
| 1213 | || end.len() > 5 |
| 1214 | { |
| 1215 | return None; |
| 1216 | } |
| 1217 | let start: u32 = start.parse().ok()?; |
| 1218 | let end: u32 = end.parse().ok()?; |
| 1219 | if start == 0 || end < start { |
| 1220 | return None; |
| 1221 | } |
| 1222 | Some((path_part, FileRange { start, end })) |
| 1223 | } |
| 1224 | |
| 1225 | /// Send-time mention resolution: exact two-pass lookup first (workspace root, |
| 1226 | /// then launch cwd), then a bounded fallback against the composer's cached |
| 1227 | /// background completion index. Returns the path, its display form, and |
| 1228 | /// whether it exists. On a miss the returned path is the workspace-root guess |
| 1229 | /// — callers must not present it as resolved when `exists` is false. |
| 1230 | fn resolve_mention_for_send( |
| 1231 | ws: &Workspace, |
| 1232 | mention: &str, |
| 1233 | completion_index: Option<&[String]>, |
| 1234 | ) -> (PathBuf, String, bool) { |
| 1235 | let guess = match ws.resolve_exact(mention) { |
| 1236 | Ok(path) => { |
| 1237 | let display = path.display().to_string(); |
| 1238 | return (path, display, true); |
| 1239 | } |
| 1240 | Err(guess) => guess, |
| 1241 | }; |
| 1242 | if let Some(resolved) = completion_index |
| 1243 | .and_then(|candidates| resolve_mention_in_completion_index(mention, candidates, ws)) |
| 1244 | { |
| 1245 | let display = resolved.display().to_string(); |
| 1246 | return (resolved, display, true); |
| 1247 | } |
| 1248 | let display = guess.display().to_string(); |
| 1249 | (guess, display, false) |
| 1250 | } |
| 1251 | |
| 1252 | /// Bounded send-time fallback for `@`-mention misses. |
| 1253 | /// |
| 1254 | /// #4365 keeps filesystem walks off the submit path, so instead of walking we |
| 1255 | /// match the typed token against the composer's already-built background |
| 1256 | /// completion index (workspace- or cwd-relative display strings). A candidate |
| 1257 | /// wins only when it is the *unique* path-suffix or basename match and the |
| 1258 | /// winning path still resolves on disk — the index may be a few seconds |
| 1259 | /// stale. Anything else (no hit, ambiguous hit, stale hit) returns `None` so |
| 1260 | /// the caller emits an honest `<missing-file>` instead of attaching an |
| 1261 | /// arbitrary same-name file from a nested directory. |
| 1262 | fn resolve_mention_in_completion_index( |
| 1263 | mention: &str, |
| 1264 | candidates: &[String], |
| 1265 | ws: &Workspace, |
| 1266 | ) -> Option<PathBuf> { |
| 1267 | // Absolute and home-anchored mentions name an exact location; a basename |
| 1268 | // lookalike elsewhere in the tree would be a different file, not a fix-up. |
| 1269 | // A leading separator is rooted on every platform, but `Path::is_absolute` |
| 1270 | // is false for `/foo` on Windows (no drive prefix), which would otherwise |
| 1271 | // let a rooted miss fall through to the index and attach an unrelated |
| 1272 | // same-name file. Test the root marker directly so the guard holds there. |
| 1273 | // `\` is a root marker only on Windows; on Unix it is an ordinary |
| 1274 | // (if unusual) leading filename character, so leave that case alone. |
| 1275 | let rooted = mention.starts_with('/') || (cfg!(windows) && mention.starts_with('\\')); |
| 1276 | if mention.starts_with('~') || rooted || Path::new(mention).is_absolute() { |
| 1277 | return None; |
| 1278 | } |
| 1279 | let needle = mention.replace('\\', "/"); |
| 1280 | let needle = needle.trim_matches('/'); |
| 1281 | if needle.is_empty() { |
| 1282 | return None; |
| 1283 | } |
| 1284 | let needle_lower = needle.to_lowercase(); |
| 1285 | let basename_lower = needle_lower.rsplit('/').next()?; |
| 1286 | |
| 1287 | let normalized = |candidate: &str| candidate.replace('\\', "/"); |
| 1288 | let suffix_match = |candidate: &str| { |
| 1289 | let cand = normalized(candidate); |
| 1290 | let cand = cand.trim_end_matches('/').to_lowercase(); |
| 1291 | !cand.is_empty() && (cand == needle_lower || cand.ends_with(&format!("/{needle_lower}"))) |
| 1292 | }; |
| 1293 | let basename_match = |candidate: &str| { |
| 1294 | let cand = normalized(candidate); |
| 1295 | let cand = cand.trim_end_matches('/').to_lowercase(); |
| 1296 | !cand.is_empty() && cand.rsplit('/').next() == Some(basename_lower) |
| 1297 | }; |
| 1298 | |
| 1299 | // Prefer path-suffix hits: they carry the user's typed directory context. |
| 1300 | // Fall back to basename hits only when no suffix hit exists. Either way, |
| 1301 | // more than one distinct winner is ambiguous and resolves nothing. |
| 1302 | let predicates: [&dyn Fn(&str) -> bool; 2] = [&suffix_match, &basename_match]; |
| 1303 | for predicate in predicates { |
| 1304 | let mut winner: Option<&str> = None; |
| 1305 | for candidate in candidates { |
| 1306 | if !predicate(candidate) { |
| 1307 | continue; |
| 1308 | } |
| 1309 | match winner { |
| 1310 | None => winner = Some(candidate.as_str()), |
| 1311 | Some(existing) if existing == candidate.as_str() => {} |
| 1312 | Some(_) => return None, |
| 1313 | } |
| 1314 | } |
| 1315 | if let Some(winner) = winner { |
| 1316 | // The index can be stale; only a path that still resolves exists. |
| 1317 | // Display strings are workspace- or cwd-relative, which |
| 1318 | // `resolve_exact` re-anchors exactly like a typed path. |
| 1319 | // |
| 1320 | // Rejoin the components with this platform's separator first. |
| 1321 | // Index strings are `/`-separated, and `root.join("ops/f.md")` |
| 1322 | // keeps that slash verbatim on Windows, yielding a mixed |
| 1323 | // `C:\ws\ops/f.md` that we then hand to the model and print in |
| 1324 | // the context inspector. Same path, inconsistent rendering. |
| 1325 | let native: PathBuf = winner.split('/').filter(|part| !part.is_empty()).collect(); |
| 1326 | return ws.resolve_exact(&native.to_string_lossy()).ok(); |
| 1327 | } |
| 1328 | } |
| 1329 | None |
| 1330 | } |
| 1331 | |
| 1332 | fn extract_file_mentions(input: &str) -> Vec<String> { |
| 1333 | let chars: Vec<char> = input.chars().collect(); |
| 1334 | let mut mentions = Vec::new(); |
| 1335 | let mut idx = 0; |
| 1336 | |
| 1337 | while idx < chars.len() { |
| 1338 | if chars[idx] != '@' || !is_file_mention_start(&chars, idx) { |
| 1339 | idx += 1; |
| 1340 | continue; |
| 1341 | } |
| 1342 | |
| 1343 | let Some(next) = chars.get(idx + 1).copied() else { |
| 1344 | break; |
| 1345 | }; |
| 1346 | if next.is_whitespace() { |
| 1347 | idx += 1; |
| 1348 | continue; |
| 1349 | } |
| 1350 | |
| 1351 | if matches!(next, '"' | '\'') { |
| 1352 | let quote = next; |
| 1353 | let mut end = idx + 2; |
| 1354 | let mut raw = String::new(); |
| 1355 | while end < chars.len() && chars[end] != quote { |
| 1356 | raw.push(chars[end]); |
| 1357 | end += 1; |
| 1358 | } |
| 1359 | if !raw.trim().is_empty() { |
| 1360 | mentions.push(raw.trim().to_string()); |
| 1361 | } |
| 1362 | idx = end.saturating_add(1); |
| 1363 | continue; |
| 1364 | } |
| 1365 | |
| 1366 | let mut end = idx + 1; |
| 1367 | let mut raw = String::new(); |
| 1368 | while end < chars.len() && !chars[end].is_whitespace() { |
| 1369 | raw.push(chars[end]); |
| 1370 | end += 1; |
| 1371 | } |
| 1372 | let trimmed = trim_unquoted_mention(&raw); |
| 1373 | if !trimmed.is_empty() { |
| 1374 | mentions.push(trimmed.to_string()); |
| 1375 | } |
| 1376 | idx = end; |
| 1377 | } |
| 1378 | |
| 1379 | mentions |
| 1380 | } |
| 1381 | |
| 1382 | fn is_file_mention_start(chars: &[char], idx: usize) -> bool { |
| 1383 | if idx == 0 { |
| 1384 | return true; |
| 1385 | } |
| 1386 | chars.get(idx.saturating_sub(1)).is_some_and(|ch| { |
| 1387 | ch.is_whitespace() |
| 1388 | || matches!(ch, '(' | '[' | '{' | '<' | '"' | '\'') |
| 1389 | || codewhale_tui_kit::translation::is_cjk(*ch) |
| 1390 | }) |
| 1391 | } |
| 1392 | |
| 1393 | fn trim_unquoted_mention(raw: &str) -> &str { |
| 1394 | let mut trimmed = raw.trim(); |
| 1395 | while trimmed.chars().count() > 1 |
| 1396 | && trimmed |
| 1397 | .chars() |
| 1398 | .last() |
| 1399 | .is_some_and(|ch| ",;:!?)]},。、;:!?)]}」』】》〉".contains(ch)) |
| 1400 | { |
| 1401 | trimmed = &trimmed[..trimmed.len() - trimmed.chars().last().unwrap().len_utf8()]; |
| 1402 | } |
| 1403 | trimmed |
| 1404 | } |
| 1405 | |
| 1406 | fn render_file_mention_context( |
| 1407 | raw: &str, |
| 1408 | path: &Path, |
| 1409 | display_path: &str, |
| 1410 | range: Option<FileRange>, |
| 1411 | ) -> String { |
| 1412 | if !path.exists() { |
| 1413 | return format!("<missing-file mention=\"@{raw}\" path=\"{display_path}\" />"); |
| 1414 | } |
| 1415 | if path.is_dir() { |
| 1416 | return render_directory_mention_context(raw, path, display_path); |
| 1417 | } |
| 1418 | if !path.is_file() { |
| 1419 | return format!("<unsupported-path mention=\"@{raw}\" path=\"{display_path}\" />"); |
| 1420 | } |
| 1421 | if is_media_path(path) { |
| 1422 | return format!( |
| 1423 | "<media-file mention=\"@{raw}\" path=\"{display_path}\">\nUse /attach {raw} when the intent is to attach this image or video to the next message.\n</media-file>" |
| 1424 | ); |
| 1425 | } |
| 1426 | |
| 1427 | let range_attr = match range { |
| 1428 | Some(FileRange { start, end }) => format!(r#" lines="{start}-{end}""#), |
| 1429 | None => String::new(), |
| 1430 | }; |
| 1431 | match read_file_content(path, range) { |
| 1432 | Ok((text, truncated, beyond_eof)) => { |
| 1433 | let truncated_attr = if truncated { " truncated=\"true\"" } else { "" }; |
| 1434 | let beyond_attr = if beyond_eof { |
| 1435 | " beyond-eof=\"true\"" |
| 1436 | } else { |
| 1437 | "" |
| 1438 | }; |
| 1439 | format!( |
| 1440 | "<file mention=\"@{raw}\" path=\"{display_path}\"{range_attr}{truncated_attr}{beyond_attr}>\n{text}\n</file>" |
| 1441 | ) |
| 1442 | } |
| 1443 | Err(err) => { |
| 1444 | format!( |
| 1445 | "<unreadable-file mention=\"@{raw}\" path=\"{display_path}\">\n{err}\n</unreadable-file>" |
| 1446 | ) |
| 1447 | } |
| 1448 | } |
| 1449 | } |
| 1450 | |
| 1451 | fn render_directory_mention_context(raw: &str, path: &Path, display_path: &str) -> String { |
| 1452 | match directory_listing( |
| 1453 | path, |
| 1454 | MAX_DIRECTORY_MENTION_ENTRIES, |
| 1455 | MAX_DIRECTORY_MENTION_SCAN, |
| 1456 | ) { |
| 1457 | Ok((body, false)) => { |
| 1458 | format!("<directory mention=\"@{raw}\" path=\"{display_path}\">\n{body}\n</directory>") |
| 1459 | } |
| 1460 | Ok((body, true)) => format!( |
| 1461 | "<directory mention=\"@{raw}\" path=\"{display_path}\" truncated=\"true\">\n{body}\n</directory>" |
| 1462 | ), |
| 1463 | Err(err) => format!( |
| 1464 | "<unreadable-directory mention=\"@{raw}\" path=\"{display_path}\">\n{err}\n</unreadable-directory>" |
| 1465 | ), |
| 1466 | } |
| 1467 | } |
| 1468 | |
| 1469 | /// The first `keep` entry names of `path` in sort order (directories marked |
| 1470 | /// `/`) and whether enumeration stopped at `scan_limit` with entries left. |
| 1471 | /// A max-heap of `keep` names bounds memory (U07-03); the scan limit bounds |
| 1472 | /// work, so a partial listing's names are the first among those examined. |
| 1473 | fn directory_listing( |
| 1474 | path: &Path, |
| 1475 | keep: usize, |
| 1476 | scan_limit: usize, |
| 1477 | ) -> std::io::Result<(String, bool)> { |
| 1478 | let mut entries = std::fs::read_dir(path)?; |
| 1479 | let mut scanned = 0usize; |
| 1480 | let mut kept = std::collections::BinaryHeap::with_capacity(keep.saturating_add(1)); |
| 1481 | let mut partial = false; |
| 1482 | loop { |
| 1483 | if scanned == scan_limit { |
| 1484 | partial = entries.next().is_some(); |
| 1485 | break; |
| 1486 | } |
| 1487 | let Some(entry) = entries.next() else { |
| 1488 | break; |
| 1489 | }; |
| 1490 | scanned += 1; |
| 1491 | let Ok(entry) = entry else { |
| 1492 | continue; |
| 1493 | }; |
| 1494 | let marker = entry |
| 1495 | .file_type() |
| 1496 | .ok() |
| 1497 | .filter(|ty| ty.is_dir()) |
| 1498 | .map_or("", |_| "/"); |
| 1499 | kept.push(format!("{}{}", entry.file_name().to_string_lossy(), marker)); |
| 1500 | if kept.len() > keep { |
| 1501 | kept.pop(); |
| 1502 | } |
| 1503 | } |
| 1504 | let names = kept.into_sorted_vec(); |
| 1505 | let mut body = names.join("\n"); |
| 1506 | let omitted = scanned.saturating_sub(names.len()); |
| 1507 | if partial { |
| 1508 | let _ = write!( |
| 1509 | body, |
| 1510 | "\n... listing stopped after {scanned} entries; more exist" |
| 1511 | ); |
| 1512 | } else if omitted > 0 { |
| 1513 | let _ = write!(body, "\n... {omitted} more entries"); |
| 1514 | } |
| 1515 | Ok((body, partial)) |
| 1516 | } |
| 1517 | |
| 1518 | /// Bounded read of a mention's file content, optionally sliced to a line |
| 1519 | /// range. Returns `(text, truncated, beyond_eof)`: `truncated` mirrors the |
| 1520 | /// full-file byte bound, except for a range that starts past that bound, |
| 1521 | /// where it says whether the streamed range itself was cut; `beyond_eof` is |
| 1522 | /// set only when the requested range starts past the end of the file. A range |
| 1523 | /// whose scan budget runs out first is `truncated` with no `beyond_eof`. |
| 1524 | fn read_file_content( |
| 1525 | path: &Path, |
| 1526 | range: Option<FileRange>, |
| 1527 | ) -> std::io::Result<(String, bool, bool)> { |
| 1528 | let mut file = std::fs::File::open(path)?; |
| 1529 | let (text, truncated) = read_text_prefix(&mut file)?; |
| 1530 | let Some(FileRange { start, end }) = range else { |
| 1531 | return Ok((text, truncated, false)); |
| 1532 | }; |
| 1533 | let mut lines: Vec<&str> = text.split('\n').collect(); |
| 1534 | if lines.last().copied() == Some("") { |
| 1535 | lines.pop(); |
| 1536 | } |
| 1537 | let start_idx = usize::try_from(start.saturating_sub(1)).unwrap_or(usize::MAX); |
| 1538 | if start_idx >= lines.len() { |
| 1539 | if truncated { |
| 1540 | // The prefix ended, not the file: read the range from the file |
| 1541 | // itself instead of calling it past EOF (U07-04). |
| 1542 | std::io::Seek::rewind(&mut file)?; |
| 1543 | return read_line_range_past_prefix( |
| 1544 | file, |
| 1545 | u64::from(start), |
| 1546 | u64::from(end), |
| 1547 | MAX_MENTION_RANGE_SCAN_BYTES, |
| 1548 | ); |
| 1549 | } |
| 1550 | return Ok((String::new(), truncated, true)); |
| 1551 | } |
| 1552 | let end_idx = usize::try_from(end).unwrap_or(usize::MAX).min(lines.len()); |
| 1553 | Ok((lines[start_idx..end_idx].join("\n"), truncated, false)) |
| 1554 | } |
| 1555 | |
| 1556 | /// Stream a 1-based inclusive line range that starts beyond the bounded |
| 1557 | /// prefix. Skipped lines are scanned, never stored; the range text itself is |
| 1558 | /// held to the same byte budget as a whole-file mention. At most `scan_limit` |
| 1559 | /// bytes are consumed; running out before the first line yields no text and |
| 1560 | /// `truncated`, and only a real end of file reads as beyond EOF. |
| 1561 | fn read_line_range_past_prefix( |
| 1562 | file: impl Read, |
| 1563 | start: u64, |
| 1564 | end: u64, |
| 1565 | scan_limit: u64, |
| 1566 | ) -> std::io::Result<(String, bool, bool)> { |
| 1567 | use std::io::BufRead; |
| 1568 | let mut reader = std::io::BufReader::new(file); |
| 1569 | let mut line = 1u64; |
| 1570 | let mut scanned = 0u64; |
| 1571 | while line < start { |
| 1572 | let buf = reader.fill_buf()?; |
| 1573 | if buf.is_empty() { |
| 1574 | return Ok((String::new(), false, true)); |
| 1575 | } |
| 1576 | if scanned >= scan_limit { |
| 1577 | return Ok((String::new(), true, false)); |
| 1578 | } |
| 1579 | let consumed = match buf.iter().position(|byte| *byte == b'\n') { |
| 1580 | Some(newline) => { |
| 1581 | line += 1; |
| 1582 | newline + 1 |
| 1583 | } |
| 1584 | None => buf.len(), |
| 1585 | }; |
| 1586 | scanned += consumed as u64; |
| 1587 | reader.consume(consumed); |
| 1588 | } |
| 1589 | if reader.fill_buf()?.is_empty() { |
| 1590 | return Ok((String::new(), false, true)); |
| 1591 | } |
| 1592 | let budget = usize::try_from(MAX_MENTION_FILE_BYTES).unwrap_or(usize::MAX); |
| 1593 | let mut buffer = Vec::new(); |
| 1594 | let mut truncated = false; |
| 1595 | while line <= end { |
| 1596 | let buf = reader.fill_buf()?; |
| 1597 | if buf.is_empty() { |
| 1598 | break; |
| 1599 | } |
| 1600 | let (take, newline) = match buf.iter().position(|byte| *byte == b'\n') { |
| 1601 | Some(newline) => (newline + 1, true), |
| 1602 | None => (buf.len(), false), |
| 1603 | }; |
| 1604 | if scanned >= scan_limit { |
| 1605 | truncated = true; |
| 1606 | break; |
| 1607 | } |
| 1608 | let room = budget - buffer.len(); |
| 1609 | if take > room { |
| 1610 | buffer.extend_from_slice(&buf[..room]); |
| 1611 | truncated = true; |
| 1612 | break; |
| 1613 | } |
| 1614 | buffer.extend_from_slice(&buf[..take]); |
| 1615 | scanned += take as u64; |
| 1616 | reader.consume(take); |
| 1617 | if newline { |
| 1618 | line += 1; |
| 1619 | } |
| 1620 | } |
| 1621 | let mut text = decode_bounded_text(buffer, truncated)?; |
| 1622 | if text.ends_with('\n') { |
| 1623 | text.pop(); |
| 1624 | } |
| 1625 | Ok((text, truncated, false)) |
| 1626 | } |
| 1627 | |
| 1628 | fn read_text_prefix(file: &mut impl Read) -> std::io::Result<(String, bool)> { |
| 1629 | let mut buffer = Vec::new(); |
| 1630 | file.by_ref() |
| 1631 | .take(MAX_MENTION_FILE_BYTES + 1) |
| 1632 | .read_to_end(&mut buffer)?; |
| 1633 | let truncated = buffer.len() as u64 > MAX_MENTION_FILE_BYTES; |
| 1634 | if truncated { |
| 1635 | buffer.truncate(MAX_MENTION_FILE_BYTES as usize); |
| 1636 | } |
| 1637 | Ok((decode_bounded_text(buffer, truncated)?, truncated)) |
| 1638 | } |
| 1639 | |
| 1640 | /// Decode a budget-bounded read as UTF-8 text, rejecting binary content. |
| 1641 | fn decode_bounded_text(mut buffer: Vec<u8>, truncated: bool) -> std::io::Result<String> { |
| 1642 | if truncated { |
| 1643 | // Round down to the nearest valid UTF-8 character boundary so a |
| 1644 | // multi-byte sequence (CJK, emoji, etc.) is never split at the cut point. |
| 1645 | // Only adjust when error_len() is None — that means truncation landed |
| 1646 | // mid-sequence (incomplete tail). A Some(_) error_len means the file |
| 1647 | // genuinely contains invalid UTF-8 bytes; leave the buffer intact so |
| 1648 | // the from_utf8 call below returns the correct "file is not UTF-8" error. |
| 1649 | if let Err(e) = std::str::from_utf8(&buffer) |
| 1650 | && e.error_len().is_none() |
| 1651 | { |
| 1652 | buffer.truncate(e.valid_up_to()); |
| 1653 | } |
| 1654 | } |
| 1655 | if buffer.contains(&0) { |
| 1656 | return Err(std::io::Error::new( |
| 1657 | std::io::ErrorKind::InvalidData, |
| 1658 | "file appears to be binary", |
| 1659 | )); |
| 1660 | } |
| 1661 | let text = std::str::from_utf8(&buffer) |
| 1662 | .map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidData, "file is not UTF-8"))? |
| 1663 | .to_string(); |
| 1664 | Ok(text) |
| 1665 | } |
| 1666 | |
| 1667 | fn is_media_path(path: &Path) -> bool { |
| 1668 | let Some(ext) = path.extension().and_then(|ext| ext.to_str()) else { |
| 1669 | return false; |
| 1670 | }; |
| 1671 | matches!( |
| 1672 | ext.to_ascii_lowercase().as_str(), |
| 1673 | "png" |
| 1674 | | "jpg" |
| 1675 | | "jpeg" |
| 1676 | | "gif" |
| 1677 | | "webp" |
| 1678 | | "bmp" |
| 1679 | | "tif" |
| 1680 | | "tiff" |
| 1681 | | "ppm" |
| 1682 | | "mp4" |
| 1683 | | "mov" |
| 1684 | | "m4v" |
| 1685 | | "webm" |
| 1686 | | "avi" |
| 1687 | | "mkv" |
| 1688 | ) |
| 1689 | } |
| 1690 | |
| 1691 | // --------------------------------------------------------------------------- |
| 1692 | // #101 regression repros |
| 1693 | // --------------------------------------------------------------------------- |
| 1694 | // |
| 1695 | // The bug being guarded: typing `@<some/file>` resolved under `--workspace`, |
| 1696 | // not the user's launch CWD. When the two diverged (the canonical case is |
| 1697 | // `--workspace=/repo` with `pwd=/repo/sub`), every relative `@` token routed |
| 1698 | // to the wrong root and the prompt got `<missing-file>` blocks. |
| 1699 | #[cfg(test)] |
| 1700 | mod tests { |
| 1701 | use super::*; |
| 1702 | use tempfile::TempDir; |
| 1703 | |
| 1704 | #[test] |
| 1705 | fn inserted_mention_bodies_parse_back_to_the_whole_path() { |
| 1706 | for path in [ |
| 1707 | "src/main.rs", |
| 1708 | "My Docs/notes.md", |
| 1709 | "Screenshot 2026-09-28 at 10.00.00.png", |
| 1710 | "notes)", |
| 1711 | "say \"hi\" now.md", |
| 1712 | ] { |
| 1713 | let input = format!("look at @{} please", file_mention_body(path)); |
| 1714 | assert_eq!( |
| 1715 | extract_file_mentions(&input), |
| 1716 | vec![path.to_string()], |
| 1717 | "{input}" |
| 1718 | ); |
| 1719 | } |
| 1720 | assert_eq!(file_mention_body("src/main.rs"), "src/main.rs"); |
| 1721 | } |
| 1722 | |
| 1723 | #[test] |
| 1724 | fn mention_directly_after_cjk_text_is_recognized() { |
| 1725 | assert_eq!( |
| 1726 | extract_file_mentions("请看@src/main.rs 讲了什么"), |
| 1727 | vec!["src/main.rs".to_string()] |
| 1728 | ); |
| 1729 | assert_eq!( |
| 1730 | partial_file_mention_at_cursor("请看@src/ma", 9), |
| 1731 | Some(("请看".len(), "src/ma".to_string())) |
| 1732 | ); |
| 1733 | assert!(extract_file_mentions("mail me at a@b.com").is_empty()); |
| 1734 | assert_eq!( |
| 1735 | extract_file_mentions("(@a.rs) 「@b.rs」 看@c.rs。"), |
| 1736 | vec!["a.rs".to_string(), "b.rs".to_string(), "c.rs".to_string()] |
| 1737 | ); |
| 1738 | } |
| 1739 | |
| 1740 | /// #101 regression — workspace-vs-cwd divergence: `@bar.txt` typed from |
| 1741 | /// the cwd `<root>/sub` MUST resolve to `<root>/sub/bar.txt`, never to |
| 1742 | /// `<root>/bar.txt` (which doesn't exist). |
| 1743 | #[test] |
| 1744 | fn cwd_pass_resolves_when_workspace_pass_misses() { |
| 1745 | let tmp = TempDir::new().expect("tempdir"); |
| 1746 | let sub = tmp.path().join("sub"); |
| 1747 | std::fs::create_dir_all(&sub).expect("mkdir"); |
| 1748 | let bar = sub.join("bar.txt"); |
| 1749 | std::fs::write(&bar, "hello bar").expect("write bar"); |
| 1750 | |
| 1751 | let content = |
| 1752 | user_request_with_file_mentions("look at @bar.txt", tmp.path(), Some(sub.clone())); |
| 1753 | |
| 1754 | // The block must reference the cwd-rooted path with the file's body — |
| 1755 | // and crucially it must NOT collapse to <missing-file>. |
| 1756 | assert!( |
| 1757 | content.contains("hello bar"), |
| 1758 | "expected file body to be inlined; got: {content}", |
| 1759 | ); |
| 1760 | assert!( |
| 1761 | !content.contains("<missing-file"), |
| 1762 | "must not surface <missing-file> for a path that exists under cwd; got: {content}", |
| 1763 | ); |
| 1764 | let bar_disp = bar.display().to_string(); |
| 1765 | assert!( |
| 1766 | content.contains(&bar_disp), |
| 1767 | "expected resolved path {bar_disp} in content; got: {content}", |
| 1768 | ); |
| 1769 | // Belt-and-suspenders: the workspace-rooted path doesn't exist and |
| 1770 | // must not appear in the rendered <file path="..."> attribute. |
| 1771 | let wrong = tmp.path().join("bar.txt").display().to_string(); |
| 1772 | assert!( |
| 1773 | !content.contains(&format!("path=\"{wrong}\"")), |
| 1774 | "should NOT have routed to {wrong}; got: {content}", |
| 1775 | ); |
| 1776 | } |
| 1777 | |
| 1778 | /// #101 regression — nested workspace path: `@nested/deep/file.md` with |
| 1779 | /// the file at workspace root resolves through the workspace pass. |
| 1780 | #[test] |
| 1781 | fn workspace_pass_resolves_nested_path() { |
| 1782 | let tmp = TempDir::new().expect("tempdir"); |
| 1783 | let nested = tmp.path().join("nested/deep"); |
| 1784 | std::fs::create_dir_all(&nested).expect("mkdir"); |
| 1785 | let file_md = nested.join("file.md"); |
| 1786 | std::fs::write(&file_md, "# nested deep").expect("write file_md"); |
| 1787 | |
| 1788 | // Cwd is irrelevant; an unrelated tempdir would do. Pass `None` so we |
| 1789 | // are unambiguously testing the workspace-pass path. |
| 1790 | let content = user_request_with_file_mentions("see @nested/deep/file.md", tmp.path(), None); |
| 1791 | |
| 1792 | assert!(content.contains("# nested deep"), "got: {content}"); |
| 1793 | assert!(!content.contains("<missing-file"), "got: {content}"); |
| 1794 | // Path-separator-portable check: the resolved path's filename is the |
| 1795 | // most reliable cross-platform anchor (Windows mixes `/` and `\` when |
| 1796 | // join() preserves user-typed separators). |
| 1797 | let basename = file_md |
| 1798 | .file_name() |
| 1799 | .and_then(|n| n.to_str()) |
| 1800 | .expect("file_name utf-8"); |
| 1801 | assert!( |
| 1802 | content.contains(basename), |
| 1803 | "basename {basename} not in path; got: {content}", |
| 1804 | ); |
| 1805 | } |
| 1806 | |
| 1807 | /// Snapshot-style check: the rendered `<file>` block for a resolvable |
| 1808 | /// mention must include the expected attributes and contents, and must |
| 1809 | /// NOT contain `<missing-file>`. |
| 1810 | #[test] |
| 1811 | fn resolvable_mention_renders_file_block_not_missing_file() { |
| 1812 | let tmp = TempDir::new().expect("tempdir"); |
| 1813 | std::fs::write(tmp.path().join("guide.md"), "# Guide\nUse the fast path.\n") |
| 1814 | .expect("write"); |
| 1815 | |
| 1816 | let content = user_request_with_file_mentions("read @guide.md", tmp.path(), None); |
| 1817 | |
| 1818 | // Header + tag presence. |
| 1819 | assert!(content.contains("Local context from @mentions:")); |
| 1820 | assert!(content.contains("<file mention=\"@guide.md\"")); |
| 1821 | assert!(content.contains("# Guide\nUse the fast path.")); |
| 1822 | assert!(content.ends_with("</file>"), "got: {content}"); |
| 1823 | // The bug fingerprint MUST be absent. |
| 1824 | assert!(!content.contains("<missing-file"), "got: {content}"); |
| 1825 | } |
| 1826 | |
| 1827 | #[test] |
| 1828 | fn two_ranges_of_one_file_are_both_attached() { |
| 1829 | let tmp = TempDir::new().expect("tempdir"); |
| 1830 | std::fs::write(tmp.path().join("notes.txt"), "one\ntwo\nthree\nfour\n").expect("write"); |
| 1831 | |
| 1832 | let content = user_request_with_file_mentions( |
| 1833 | "compare @notes.txt:1-1 with @notes.txt:4-4", |
| 1834 | tmp.path(), |
| 1835 | None, |
| 1836 | ); |
| 1837 | |
| 1838 | assert!(content.contains("lines=\"1-1\">\none\n"), "got: {content}"); |
| 1839 | assert!(content.contains("lines=\"4-4\">\nfour\n"), "got: {content}"); |
| 1840 | |
| 1841 | if cfg!(unix) { |
| 1842 | std::fs::write(tmp.path().join("notes.txt:1-1"), "literal\n").expect("write"); |
| 1843 | let content = user_request_with_file_mentions( |
| 1844 | "@notes.txt:01-01 @notes.txt:1-1", |
| 1845 | tmp.path(), |
| 1846 | None, |
| 1847 | ); |
| 1848 | assert!(content.contains("lines=\"1-1\">\none\n"), "got: {content}"); |
| 1849 | assert!(content.contains("literal\n"), "got: {content}"); |
| 1850 | } |
| 1851 | } |
| 1852 | |
| 1853 | /// Negative test: a truly missing path still produces `<missing-file>` |
| 1854 | /// so the user gets an explicit signal instead of silent failure. |
| 1855 | #[test] |
| 1856 | fn truly_missing_mention_still_renders_missing_file() { |
| 1857 | let tmp = TempDir::new().expect("tempdir"); |
| 1858 | |
| 1859 | let content = user_request_with_file_mentions( |
| 1860 | "huh @does/not/exist.txt", |
| 1861 | tmp.path(), |
| 1862 | Some(tmp.path().to_path_buf()), |
| 1863 | ); |
| 1864 | |
| 1865 | assert!( |
| 1866 | content.contains("<missing-file mention=\"@does/not/exist.txt\""), |
| 1867 | "got: {content}", |
| 1868 | ); |
| 1869 | } |
| 1870 | |
| 1871 | #[test] |
| 1872 | fn pending_context_preview_is_lexical_and_does_not_probe_paths() { |
| 1873 | let previews = pending_context_previews("read @guide.md and @missing.md", Locale::En); |
| 1874 | |
| 1875 | assert_eq!(previews.len(), 2); |
| 1876 | assert_eq!(previews[0].kind, "mention"); |
| 1877 | assert_eq!(previews[0].label, "guide.md"); |
| 1878 | assert!(!previews[0].included); |
| 1879 | assert_eq!(previews[0].detail.as_deref(), Some("resolved on send")); |
| 1880 | assert_eq!(previews[1].kind, "mention"); |
| 1881 | assert_eq!(previews[1].label, "missing.md"); |
| 1882 | assert!(!previews[1].included); |
| 1883 | assert_eq!(previews[1].detail.as_deref(), Some("resolved on send")); |
| 1884 | } |
| 1885 | |
| 1886 | #[test] |
| 1887 | fn pending_context_preview_distinguishes_attach_media_from_at_media() { |
| 1888 | let tmp = TempDir::new().expect("tempdir"); |
| 1889 | std::fs::write(tmp.path().join("photo.png"), b"png").expect("write"); |
| 1890 | let attached = tmp.path().join("photo.png").display().to_string(); |
| 1891 | let input = format!("inspect @photo.png\n[Attached image: {attached}]"); |
| 1892 | |
| 1893 | let previews = pending_context_previews(&input, Locale::En); |
| 1894 | |
| 1895 | assert!( |
| 1896 | previews |
| 1897 | .iter() |
| 1898 | .any(|item| item.kind == "media" && !item.included), |
| 1899 | "at-mention media should be hint-only: {previews:?}" |
| 1900 | ); |
| 1901 | assert!( |
| 1902 | previews |
| 1903 | .iter() |
| 1904 | .any(|item| item.kind == "image" && item.included), |
| 1905 | "/attach media should be included: {previews:?}" |
| 1906 | ); |
| 1907 | } |
| 1908 | |
| 1909 | #[test] |
| 1910 | fn manually_typed_basename_does_not_fuzzy_attach_nested_file() { |
| 1911 | let tmp = TempDir::new().expect("tempdir"); |
| 1912 | let nested = tmp.path().join("nested"); |
| 1913 | std::fs::create_dir_all(&nested).expect("mkdir"); |
| 1914 | std::fs::write(nested.join("guide.md"), "nested secret").expect("write"); |
| 1915 | |
| 1916 | // With no completion index on hand there is no send-time fallback: |
| 1917 | // the miss stays an explicit <missing-file> rather than attaching an |
| 1918 | // arbitrary same-name file from a nested directory (#4365). |
| 1919 | let content = user_request_with_file_mentions("read @guide.md", tmp.path(), None); |
| 1920 | |
| 1921 | assert!( |
| 1922 | content.contains("<missing-file mention=\"@guide.md\""), |
| 1923 | "a manually typed basename should remain exact: {content}", |
| 1924 | ); |
| 1925 | assert!( |
| 1926 | !content.contains("nested secret"), |
| 1927 | "exact resolution must not silently attach a fuzzy nested match: {content}", |
| 1928 | ); |
| 1929 | } |
| 1930 | |
| 1931 | // --------------------------------------------------------------------- |
| 1932 | // Send-time completion-index fallback |
| 1933 | // --------------------------------------------------------------------- |
| 1934 | // |
| 1935 | // The dogfood failure this guards: `@FINISH-0.9.4.md` typed at the |
| 1936 | // workspace root resolved "not found" and injected a <missing-file> block |
| 1937 | // carrying the wrong (workspace-root) path, even though the file sat one |
| 1938 | // directory down. Misses now fall back to a bounded unique-match search |
| 1939 | // of the composer's background completion index; unresolvable misses emit |
| 1940 | // an honest block that names only what the user typed. |
| 1941 | |
| 1942 | fn expand_with_index( |
| 1943 | input: &str, |
| 1944 | workspace: &Path, |
| 1945 | cwd: Option<PathBuf>, |
| 1946 | index: &[String], |
| 1947 | ) -> String { |
| 1948 | user_request_with_file_mentions_cached( |
| 1949 | input, |
| 1950 | workspace, |
| 1951 | cwd, |
| 1952 | &mut GitMentionCache::default(), |
| 1953 | Some(index), |
| 1954 | ) |
| 1955 | } |
| 1956 | |
| 1957 | /// A unique basename hit in the completion index resolves a nested file |
| 1958 | /// and injects its real path. |
| 1959 | #[test] |
| 1960 | fn mention_miss_resolves_via_unique_index_basename() { |
| 1961 | let tmp = TempDir::new().expect("tempdir"); |
| 1962 | let nested = tmp.path().join("ops"); |
| 1963 | std::fs::create_dir_all(&nested).expect("mkdir"); |
| 1964 | std::fs::write(nested.join("FINISH-0.9.4.md"), "ship list").expect("write"); |
| 1965 | |
| 1966 | let index = vec!["ops/FINISH-0.9.4.md".to_string(), "README.md".to_string()]; |
| 1967 | let content = expand_with_index("finish @FINISH-0.9.4.md", tmp.path(), None, &index); |
| 1968 | |
| 1969 | assert!(content.contains("ship list"), "got: {content}"); |
| 1970 | assert!(!content.contains("<missing-file"), "got: {content}"); |
| 1971 | let real = nested.join("FINISH-0.9.4.md").display().to_string(); |
| 1972 | assert!( |
| 1973 | content.contains(&real), |
| 1974 | "expected resolved path {real} in content; got: {content}", |
| 1975 | ); |
| 1976 | } |
| 1977 | |
| 1978 | /// A typed partial path resolves through a unique path-suffix hit. |
| 1979 | #[test] |
| 1980 | fn mention_miss_resolves_via_unique_index_suffix() { |
| 1981 | let tmp = TempDir::new().expect("tempdir"); |
| 1982 | let nested = tmp.path().join("nested/deep"); |
| 1983 | std::fs::create_dir_all(&nested).expect("mkdir"); |
| 1984 | std::fs::write(nested.join("file.md"), "deep body").expect("write"); |
| 1985 | // A same-basename file elsewhere must not make the suffix hit |
| 1986 | // ambiguous: the typed directory context disambiguates. |
| 1987 | let other = tmp.path().join("other"); |
| 1988 | std::fs::create_dir_all(&other).expect("mkdir"); |
| 1989 | std::fs::write(other.join("file.md"), "other body").expect("write"); |
| 1990 | |
| 1991 | let index = vec![ |
| 1992 | "nested/deep/file.md".to_string(), |
| 1993 | "other/file.md".to_string(), |
| 1994 | ]; |
| 1995 | let content = expand_with_index("see @deep/file.md", tmp.path(), None, &index); |
| 1996 | |
| 1997 | assert!(content.contains("deep body"), "got: {content}"); |
| 1998 | assert!(!content.contains("other body"), "got: {content}"); |
| 1999 | assert!(!content.contains("<missing-file"), "got: {content}"); |
| 2000 | } |
| 2001 | |
| 2002 | /// Two same-basename candidates with no typed directory context are |
| 2003 | /// ambiguous: nothing is attached and the miss stays explicit. |
| 2004 | #[test] |
| 2005 | fn ambiguous_index_basename_stays_missing() { |
| 2006 | let tmp = TempDir::new().expect("tempdir"); |
| 2007 | for dir in ["a", "b"] { |
| 2008 | std::fs::create_dir_all(tmp.path().join(dir)).expect("mkdir"); |
| 2009 | std::fs::write(tmp.path().join(dir).join("guide.md"), format!("body {dir}")) |
| 2010 | .expect("write"); |
| 2011 | } |
| 2012 | |
| 2013 | let index = vec!["a/guide.md".to_string(), "b/guide.md".to_string()]; |
| 2014 | let content = expand_with_index("read @guide.md", tmp.path(), None, &index); |
| 2015 | |
| 2016 | assert!( |
| 2017 | content.contains("<missing-file mention=\"@guide.md\""), |
| 2018 | "an ambiguous basename must not attach an arbitrary winner: {content}", |
| 2019 | ); |
| 2020 | assert!(!content.contains("body a"), "got: {content}"); |
| 2021 | assert!(!content.contains("body b"), "got: {content}"); |
| 2022 | } |
| 2023 | |
| 2024 | /// A stale index entry (file deleted after the scan) must not attach. |
| 2025 | #[test] |
| 2026 | fn stale_index_entry_stays_missing() { |
| 2027 | let tmp = TempDir::new().expect("tempdir"); |
| 2028 | |
| 2029 | let index = vec!["ghost.md".to_string()]; |
| 2030 | let content = expand_with_index("boo @ghost.md", tmp.path(), None, &index); |
| 2031 | |
| 2032 | assert!( |
| 2033 | content.contains("<missing-file mention=\"@ghost.md\" />"), |
| 2034 | "got: {content}", |
| 2035 | ); |
| 2036 | } |
| 2037 | |
| 2038 | /// Absolute mentions name an exact location; the index must never |
| 2039 | /// substitute a same-basename file from inside the workspace. |
| 2040 | #[test] |
| 2041 | fn absolute_mention_miss_never_uses_index() { |
| 2042 | let tmp = TempDir::new().expect("tempdir"); |
| 2043 | std::fs::write(tmp.path().join("guide.md"), "workspace guide").expect("write"); |
| 2044 | |
| 2045 | let index = vec!["guide.md".to_string()]; |
| 2046 | let content = expand_with_index( |
| 2047 | "read @/definitely/absent/guide.md", |
| 2048 | tmp.path(), |
| 2049 | None, |
| 2050 | &index, |
| 2051 | ); |
| 2052 | |
| 2053 | assert!( |
| 2054 | content.contains("<missing-file mention=\"@/definitely/absent/guide.md\" />"), |
| 2055 | "got: {content}", |
| 2056 | ); |
| 2057 | assert!(!content.contains("workspace guide"), "got: {content}"); |
| 2058 | } |
| 2059 | |
| 2060 | /// The honest miss format: the block names only the typed mention and |
| 2061 | /// never the non-existent workspace-root join. |
| 2062 | #[test] |
| 2063 | fn missing_file_block_names_only_the_typed_mention() { |
| 2064 | let tmp = TempDir::new().expect("tempdir"); |
| 2065 | |
| 2066 | let content = user_request_with_file_mentions( |
| 2067 | "huh @does/not/exist.txt", |
| 2068 | tmp.path(), |
| 2069 | Some(tmp.path().to_path_buf()), |
| 2070 | ); |
| 2071 | |
| 2072 | assert!( |
| 2073 | content.contains("<missing-file mention=\"@does/not/exist.txt\" />"), |
| 2074 | "got: {content}", |
| 2075 | ); |
| 2076 | let wrong = tmp.path().join("does/not/exist.txt").display().to_string(); |
| 2077 | assert!( |
| 2078 | !content.contains(&wrong), |
| 2079 | "must not inject the wrong workspace-root path {wrong}; got: {content}", |
| 2080 | ); |
| 2081 | } |
| 2082 | |
| 2083 | /// The context inspector mirrors the payload: index-resolved mentions |
| 2084 | /// report their real path, unresolved ones report the typed token. |
| 2085 | #[test] |
| 2086 | fn context_references_reflect_index_resolution() { |
| 2087 | let tmp = TempDir::new().expect("tempdir"); |
| 2088 | let nested = tmp.path().join("ops"); |
| 2089 | std::fs::create_dir_all(&nested).expect("mkdir"); |
| 2090 | std::fs::write(nested.join("runbook.md"), "steps").expect("write"); |
| 2091 | |
| 2092 | let index = vec!["ops/runbook.md".to_string()]; |
| 2093 | let references = context_references_from_input_cached( |
| 2094 | "read @runbook.md and @absent.md", |
| 2095 | tmp.path(), |
| 2096 | None, |
| 2097 | &mut GitMentionCache::default(), |
| 2098 | Some(&index), |
| 2099 | ); |
| 2100 | |
| 2101 | let resolved = references |
| 2102 | .iter() |
| 2103 | .find(|r| r.label == "runbook.md") |
| 2104 | .expect("runbook reference"); |
| 2105 | assert_eq!(resolved.kind, ContextReferenceKind::File); |
| 2106 | assert!(resolved.included); |
| 2107 | let real = nested.join("runbook.md").display().to_string(); |
| 2108 | assert_eq!(resolved.target, real, "{resolved:?}"); |
| 2109 | |
| 2110 | let missing = references |
| 2111 | .iter() |
| 2112 | .find(|r| r.label == "absent.md") |
| 2113 | .expect("absent reference"); |
| 2114 | assert_eq!(missing.kind, ContextReferenceKind::Missing); |
| 2115 | assert!(!missing.included); |
| 2116 | assert_eq!( |
| 2117 | missing.target, "absent.md", |
| 2118 | "a missing mention must not report the workspace-root guess as its target: {missing:?}", |
| 2119 | ); |
| 2120 | } |
| 2121 | |
| 2122 | #[test] |
| 2123 | fn media_attachment_references_include_removable_line_ranges() { |
| 2124 | let input = "before\n[Attached image: 8x4 PNG at /tmp/pasted.png]\nafter"; |
| 2125 | |
| 2126 | let references = media_attachment_references(input); |
| 2127 | |
| 2128 | assert_eq!(references.len(), 1); |
| 2129 | let reference = &references[0]; |
| 2130 | assert_eq!(reference.kind, "image"); |
| 2131 | assert_eq!(reference.path, "/tmp/pasted.png"); |
| 2132 | assert_eq!( |
| 2133 | &input[reference.start_byte..reference.end_byte], |
| 2134 | "[Attached image: 8x4 PNG at /tmp/pasted.png]\n" |
| 2135 | ); |
| 2136 | } |
| 2137 | |
| 2138 | #[test] |
| 2139 | fn context_references_preserve_exact_targets_and_roundtrip() { |
| 2140 | let tmp = TempDir::new().expect("tempdir"); |
| 2141 | std::fs::create_dir_all(tmp.path().join("src")).expect("mkdir"); |
| 2142 | std::fs::write(tmp.path().join("src/main.rs"), "fn main() {}").expect("write"); |
| 2143 | let input = "read @src/main.rs"; |
| 2144 | |
| 2145 | let references = |
| 2146 | context_references_from_input(input, tmp.path(), Some(tmp.path().to_path_buf())); |
| 2147 | |
| 2148 | assert_eq!(references.len(), 1); |
| 2149 | let reference = &references[0]; |
| 2150 | assert_eq!(reference.kind, ContextReferenceKind::File); |
| 2151 | assert_eq!(reference.source, ContextReferenceSource::AtMention); |
| 2152 | assert_eq!(reference.label, "src/main.rs"); |
| 2153 | assert!(reference.target.ends_with("src/main.rs")); |
| 2154 | assert!(reference.included); |
| 2155 | assert!(reference.expanded); |
| 2156 | |
| 2157 | let encoded = serde_json::to_string(reference).expect("serialize"); |
| 2158 | let decoded: ContextReference = serde_json::from_str(&encoded).expect("deserialize"); |
| 2159 | assert_eq!(&decoded, reference); |
| 2160 | } |
| 2161 | |
| 2162 | /// Regression test for #1441: truncating at MAX_MENTION_FILE_BYTES must not |
| 2163 | /// split a multi-byte UTF-8 sequence, which previously produced U+FFFD |
| 2164 | /// replacement characters in the TUI output. |
| 2165 | #[test] |
| 2166 | fn read_text_prefix_truncation_respects_utf8_char_boundary() { |
| 2167 | use std::io::Write; |
| 2168 | |
| 2169 | // Build a file that is MAX_MENTION_FILE_BYTES - 1 ASCII bytes followed |
| 2170 | // by a 3-byte CJK character (U+4E2D, '中'). The naive truncate at |
| 2171 | // MAX_MENTION_FILE_BYTES cuts after the first byte of '中', producing |
| 2172 | // an invalid sequence. |
| 2173 | let tmp = TempDir::new().expect("tempdir"); |
| 2174 | let path = tmp.path().join("cjk.txt"); |
| 2175 | let mut f = std::fs::File::create(&path).expect("create"); |
| 2176 | let padding = vec![b'a'; MAX_MENTION_FILE_BYTES as usize - 1]; |
| 2177 | f.write_all(&padding).expect("write padding"); |
| 2178 | f.write_all("中".as_bytes()).expect("write CJK"); |
| 2179 | |
| 2180 | let (text, truncated, beyond_eof) = read_file_content(&path, None).expect("should succeed"); |
| 2181 | assert!(!beyond_eof); |
| 2182 | assert!( |
| 2183 | truncated, |
| 2184 | "file exceeds limit so should be marked truncated" |
| 2185 | ); |
| 2186 | assert!( |
| 2187 | !text.contains('\u{FFFD}'), |
| 2188 | "truncated text must not contain replacement characters; got: {text:?}", |
| 2189 | ); |
| 2190 | } |
| 2191 | |
| 2192 | #[test] |
| 2193 | fn mention_range_splitting_accepts_only_exact_digit_pairs() { |
| 2194 | assert_eq!( |
| 2195 | split_mention_range("src/lib.rs:120-160"), |
| 2196 | Some(( |
| 2197 | "src/lib.rs", |
| 2198 | FileRange { |
| 2199 | start: 120, |
| 2200 | end: 160 |
| 2201 | } |
| 2202 | )), |
| 2203 | ); |
| 2204 | assert_eq!( |
| 2205 | split_mention_range("x:1-2"), |
| 2206 | Some(("x", FileRange { start: 1, end: 2 })), |
| 2207 | ); |
| 2208 | for whole in [ |
| 2209 | "notes.txt", |
| 2210 | "x:1", |
| 2211 | "x:a-b", |
| 2212 | ":1-2", |
| 2213 | "x:1-a", |
| 2214 | "x:0-2", |
| 2215 | "x:2-1", |
| 2216 | ] { |
| 2217 | assert_eq!(split_mention_range(whole), None, "{whole} must stay whole"); |
| 2218 | } |
| 2219 | } |
| 2220 | |
| 2221 | /// U07-04: a range that starts past the bounded prefix is read from the |
| 2222 | /// file, not reported as past EOF; a range past the real end still is. |
| 2223 | #[test] |
| 2224 | fn ranged_file_mention_reads_past_the_bounded_prefix() { |
| 2225 | let tmp = TempDir::new().expect("tempdir"); |
| 2226 | let path = tmp.path().join("long.txt"); |
| 2227 | let body: String = (1..=20_000).map(|n| format!("line {n}\n")).collect(); |
| 2228 | assert!(body.len() as u64 > MAX_MENTION_FILE_BYTES); |
| 2229 | std::fs::write(&path, body).expect("write"); |
| 2230 | |
| 2231 | let (text, truncated, beyond_eof) = read_file_content( |
| 2232 | &path, |
| 2233 | Some(FileRange { |
| 2234 | start: 19_998, |
| 2235 | end: 20_000, |
| 2236 | }), |
| 2237 | ) |
| 2238 | .expect("range read"); |
| 2239 | assert!(!beyond_eof, "the file has these lines"); |
| 2240 | assert!(!truncated, "three short lines fit the budget"); |
| 2241 | assert_eq!(text, "line 19998\nline 19999\nline 20000"); |
| 2242 | |
| 2243 | let (_, _, beyond_eof) = read_file_content( |
| 2244 | &path, |
| 2245 | Some(FileRange { |
| 2246 | start: 20_001, |
| 2247 | end: 20_002, |
| 2248 | }), |
| 2249 | ) |
| 2250 | .expect("range read"); |
| 2251 | assert!(beyond_eof, "the file really ends at line 20000"); |
| 2252 | } |
| 2253 | |
| 2254 | #[test] |
| 2255 | fn mention_scan_bounds_report_partial_not_eof() { |
| 2256 | let tmp = TempDir::new().expect("tempdir"); |
| 2257 | let path = tmp.path().join("lines.txt"); |
| 2258 | std::fs::write(&path, "aaaa\nbbbb\ncccc\ndddd\n").expect("write"); |
| 2259 | let open = || std::fs::File::open(&path).expect("open"); |
| 2260 | |
| 2261 | let (text, truncated, beyond_eof) = |
| 2262 | read_line_range_past_prefix(open(), 4, 4, 7).expect("bounded read"); |
| 2263 | assert!(truncated && !beyond_eof && text.is_empty()); |
| 2264 | let (text, truncated, beyond_eof) = |
| 2265 | read_line_range_past_prefix(open(), 4, 4, 1 << 20).expect("unbounded read"); |
| 2266 | assert!(!truncated && !beyond_eof); |
| 2267 | assert_eq!(text, "dddd"); |
| 2268 | let (_, truncated, beyond_eof) = |
| 2269 | read_line_range_past_prefix(open(), 9, 9, 1 << 20).expect("past the end"); |
| 2270 | assert!(!truncated && beyond_eof); |
| 2271 | let (text, truncated, beyond_eof) = |
| 2272 | read_line_range_past_prefix(open(), 1, 4, 12).expect("cut short"); |
| 2273 | assert!(truncated && !beyond_eof, "{text:?}"); |
| 2274 | assert!(text.starts_with("aaaa\nbbbb"), "{text:?}"); |
| 2275 | |
| 2276 | let dir = tmp.path().join("many"); |
| 2277 | std::fs::create_dir(&dir).expect("mkdir"); |
| 2278 | for n in 0..30 { |
| 2279 | std::fs::write(dir.join(format!("f{n:02}")), "x").expect("write"); |
| 2280 | } |
| 2281 | let (body, partial) = directory_listing(&dir, 5, 100).expect("listing"); |
| 2282 | assert!(!partial); |
| 2283 | assert!(body.ends_with("... 25 more entries"), "{body}"); |
| 2284 | let (body, partial) = directory_listing(&dir, 5, 12).expect("listing"); |
| 2285 | assert!(partial); |
| 2286 | assert!( |
| 2287 | body.ends_with("listing stopped after 12 entries; more exist"), |
| 2288 | "{body}" |
| 2289 | ); |
| 2290 | let (_, partial) = directory_listing(&dir, 5, 30).expect("listing"); |
| 2291 | assert!( |
| 2292 | !partial, |
| 2293 | "exactly the scan limit with nothing left is complete" |
| 2294 | ); |
| 2295 | } |
| 2296 | |
| 2297 | #[test] |
| 2298 | fn ranged_file_mention_slices_lines_and_reports_beyond_eof() { |
| 2299 | let tmp = TempDir::new().expect("tempdir"); |
| 2300 | let path = tmp.path().join("lines.rs"); |
| 2301 | std::fs::write(&path, "one\ntwo\nthree\nfour\nfive\n").expect("write"); |
| 2302 | |
| 2303 | let (text, truncated, beyond_eof) = |
| 2304 | read_file_content(&path, Some(FileRange { start: 2, end: 4 })).expect("range read"); |
| 2305 | assert!(!truncated); |
| 2306 | assert!(!beyond_eof); |
| 2307 | assert_eq!(text, "two\nthree\nfour"); |
| 2308 | |
| 2309 | // An end past the file clamps to what exists. |
| 2310 | let (text, _, beyond_eof) = |
| 2311 | read_file_content(&path, Some(FileRange { start: 4, end: 99 })).expect("clamped range"); |
| 2312 | assert!(!beyond_eof); |
| 2313 | assert_eq!(text, "four\nfive"); |
| 2314 | |
| 2315 | // A start past the end is flagged honestly. |
| 2316 | let (text, _, beyond_eof) = |
| 2317 | read_file_content(&path, Some(FileRange { start: 9, end: 12 })).expect("beyond range"); |
| 2318 | assert!(beyond_eof); |
| 2319 | assert!(text.is_empty()); |
| 2320 | } |
| 2321 | |
| 2322 | #[test] |
| 2323 | fn ranged_mention_render_annotates_lines_and_honours_the_byte_bound() { |
| 2324 | let tmp = TempDir::new().expect("tempdir"); |
| 2325 | let path = tmp.path().join("notes.rs"); |
| 2326 | std::fs::write(&path, "a\nb\nc\nd\n").expect("write"); |
| 2327 | let rendered = render_file_mention_context( |
| 2328 | "notes.rs:2-3", |
| 2329 | &path, |
| 2330 | "notes.rs", |
| 2331 | Some(FileRange { start: 2, end: 3 }), |
| 2332 | ); |
| 2333 | assert!(rendered.contains(r#"lines="2-3""#), "{rendered}"); |
| 2334 | assert!(rendered.contains("\nb\nc\n")); |
| 2335 | |
| 2336 | let beyond = render_file_mention_context( |
| 2337 | "notes.rs:80-90", |
| 2338 | &path, |
| 2339 | "notes.rs", |
| 2340 | Some(FileRange { start: 80, end: 90 }), |
| 2341 | ); |
| 2342 | assert!(beyond.contains(r#"beyond-eof="true""#), "{beyond}"); |
| 2343 | } |
| 2344 | // --------------------------------------------------------------------- |
| 2345 | // #4067 — @git / @diff composer mentions |
| 2346 | // --------------------------------------------------------------------- |
| 2347 | |
| 2348 | fn init_test_repo(dir: &Path) { |
| 2349 | for args in [ |
| 2350 | vec!["init", "--initial-branch=main"], |
| 2351 | vec!["config", "user.email", "test@example.com"], |
| 2352 | vec!["config", "user.name", "Test"], |
| 2353 | ] { |
| 2354 | let out = std::process::Command::new("git") |
| 2355 | .args(&args) |
| 2356 | .current_dir(dir) |
| 2357 | .output() |
| 2358 | .expect("git available in tests"); |
| 2359 | assert!(out.status.success(), "git {args:?} failed"); |
| 2360 | } |
| 2361 | } |
| 2362 | |
| 2363 | fn commit_test_repo(dir: &Path) { |
| 2364 | for args in [vec!["add", "-A"], vec!["commit", "-m", "initial"]] { |
| 2365 | std::process::Command::new("git") |
| 2366 | .args(&args) |
| 2367 | .current_dir(dir) |
| 2368 | .output() |
| 2369 | .expect("git available in tests"); |
| 2370 | } |
| 2371 | } |
| 2372 | |
| 2373 | #[test] |
| 2374 | fn git_and_diff_mentions_inline_curated_context_not_paths() { |
| 2375 | let tmp = TempDir::new().expect("tempdir"); |
| 2376 | init_test_repo(tmp.path()); |
| 2377 | std::fs::write(tmp.path().join("a.txt"), "one\n").expect("write"); |
| 2378 | commit_test_repo(tmp.path()); |
| 2379 | std::fs::write(tmp.path().join("a.txt"), "two\n").expect("write"); |
| 2380 | |
| 2381 | let expanded = user_request_with_file_mentions( |
| 2382 | "look at @git and @diff", |
| 2383 | tmp.path(), |
| 2384 | Some(tmp.path().to_path_buf()), |
| 2385 | ); |
| 2386 | |
| 2387 | assert!(expanded.contains("<git-status"), "{expanded}"); |
| 2388 | assert!(expanded.contains("<git-diff"), "{expanded}"); |
| 2389 | assert!(expanded.contains("a.txt"), "{expanded}"); |
| 2390 | // The tokens are not treated as paths, so no missing-file block. |
| 2391 | assert!(!expanded.contains("<missing-file"), "{expanded}"); |
| 2392 | } |
| 2393 | |
| 2394 | #[test] |
| 2395 | fn git_mentions_outside_a_repository_say_so_explicitly() { |
| 2396 | let tmp = TempDir::new().expect("tempdir"); |
| 2397 | let expanded = user_request_with_file_mentions( |
| 2398 | "status? @git", |
| 2399 | tmp.path(), |
| 2400 | Some(tmp.path().to_path_buf()), |
| 2401 | ); |
| 2402 | assert!(expanded.contains("<git-unavailable"), "{expanded}"); |
| 2403 | assert!(expanded.contains("not a git repository"), "{expanded}"); |
| 2404 | } |
| 2405 | |
| 2406 | #[test] |
| 2407 | fn git_mention_is_deduplicated_within_one_message() { |
| 2408 | let tmp = TempDir::new().expect("tempdir"); |
| 2409 | init_test_repo(tmp.path()); |
| 2410 | std::fs::write(tmp.path().join("a.txt"), "one\n").expect("write"); |
| 2411 | commit_test_repo(tmp.path()); |
| 2412 | std::fs::write(tmp.path().join("a.txt"), "two\n").expect("write"); |
| 2413 | |
| 2414 | let expanded = user_request_with_file_mentions( |
| 2415 | "@diff and again @diff", |
| 2416 | tmp.path(), |
| 2417 | Some(tmp.path().to_path_buf()), |
| 2418 | ); |
| 2419 | assert_eq!(expanded.matches("<git-diff").count(), 1, "{expanded}"); |
| 2420 | } |
| 2421 | |
| 2422 | #[test] |
| 2423 | fn paths_that_merely_start_with_git_stay_file_mentions() { |
| 2424 | let tmp = TempDir::new().expect("tempdir"); |
| 2425 | std::fs::write(tmp.path().join("diff.txt"), "plain file").expect("write"); |
| 2426 | |
| 2427 | let expanded = user_request_with_file_mentions( |
| 2428 | "see @diff.txt", |
| 2429 | tmp.path(), |
| 2430 | Some(tmp.path().to_path_buf()), |
| 2431 | ); |
| 2432 | assert!(expanded.contains("plain file"), "{expanded}"); |
| 2433 | assert!(!expanded.contains("<git-diff"), "{expanded}"); |
| 2434 | } |
| 2435 | |
| 2436 | #[test] |
| 2437 | fn large_diff_is_truncated_and_the_inspector_reports_the_budget() { |
| 2438 | let tmp = TempDir::new().expect("tempdir"); |
| 2439 | init_test_repo(tmp.path()); |
| 2440 | std::fs::write(tmp.path().join("big.txt"), "seed\n").expect("write"); |
| 2441 | commit_test_repo(tmp.path()); |
| 2442 | let bulk: String = (0..40_000).map(|i| format!("line {i}\n")).collect(); |
| 2443 | std::fs::write(tmp.path().join("big.txt"), bulk).expect("write"); |
| 2444 | |
| 2445 | let expanded = |
| 2446 | user_request_with_file_mentions("@diff", tmp.path(), Some(tmp.path().to_path_buf())); |
| 2447 | assert!( |
| 2448 | expanded.contains("truncated=\"true\""), |
| 2449 | "expected truncation marker" |
| 2450 | ); |
| 2451 | |
| 2452 | let references = |
| 2453 | context_references_from_input("@diff", tmp.path(), Some(tmp.path().to_path_buf())); |
| 2454 | let git_ref = references |
| 2455 | .iter() |
| 2456 | .find(|r| r.kind == ContextReferenceKind::GitContext) |
| 2457 | .expect("git reference present in the inspector"); |
| 2458 | assert_eq!(git_ref.label, "diff"); |
| 2459 | assert!(git_ref.included); |
| 2460 | let detail = git_ref.detail.clone().unwrap_or_default(); |
| 2461 | assert!(detail.contains("truncated at"), "{detail}"); |
| 2462 | assert!( |
| 2463 | detail.contains(&crate::tui::git_mention::MAX_GIT_DIFF_MENTION_BYTES.to_string()), |
| 2464 | "{detail}" |
| 2465 | ); |
| 2466 | } |
| 2467 | |
| 2468 | #[test] |
| 2469 | fn empty_repository_reference_is_visible_but_not_included() { |
| 2470 | let tmp = TempDir::new().expect("tempdir"); |
| 2471 | init_test_repo(tmp.path()); |
| 2472 | std::fs::write(tmp.path().join("a.txt"), "one\n").expect("write"); |
| 2473 | commit_test_repo(tmp.path()); |
| 2474 | |
| 2475 | let references = |
| 2476 | context_references_from_input("@diff", tmp.path(), Some(tmp.path().to_path_buf())); |
| 2477 | let git_ref = references |
| 2478 | .iter() |
| 2479 | .find(|r| r.kind == ContextReferenceKind::GitContext) |
| 2480 | .expect("git reference present even when there is nothing to show"); |
| 2481 | assert!(!git_ref.included); |
| 2482 | assert!( |
| 2483 | git_ref |
| 2484 | .detail |
| 2485 | .as_deref() |
| 2486 | .is_some_and(|d| d.contains("no working-tree changes")), |
| 2487 | "{:?}", |
| 2488 | git_ref.detail |
| 2489 | ); |
| 2490 | } |
| 2491 | |
| 2492 | #[test] |
| 2493 | fn composer_preview_lists_git_mentions_without_running_git() { |
| 2494 | let previews = pending_context_previews("@git @diff", Locale::En); |
| 2495 | let kinds: Vec<&str> = previews.iter().map(|p| p.kind.as_str()).collect(); |
| 2496 | assert_eq!(kinds, vec!["git", "git"]); |
| 2497 | assert!(previews.iter().all(|p| !p.included)); |
| 2498 | let localized = pending_context_previews("@git @notes.md", Locale::ZhHans); |
| 2499 | assert!( |
| 2500 | localized |
| 2501 | .iter() |
| 2502 | .all(|p| p.detail.as_deref() == Some("发送时解析")), |
| 2503 | "{localized:?}" |
| 2504 | ); |
| 2505 | } |
| 2506 | |
| 2507 | /// #4067 review follow-up: `mention_menu_limit = 0` is a documented way to |
| 2508 | /// disable the popup. The git tokens are menu entries like any other and |
| 2509 | /// must respect the same cap — otherwise setting 0 still pops a one-entry |
| 2510 | /// menu the moment the user types `@g`. |
| 2511 | #[test] |
| 2512 | fn git_mention_entries_respect_a_zero_menu_limit() { |
| 2513 | let paths = vec!["src/main.rs".to_string()]; |
| 2514 | assert!(with_git_mention_entries(paths.clone(), "g", 0).is_empty()); |
| 2515 | assert!(with_git_mention_entries(paths.clone(), "d", 0).is_empty()); |
| 2516 | assert!(with_git_mention_entries(paths.clone(), "", 0).is_empty()); |
| 2517 | assert!(with_git_mention_entries(Vec::new(), "gi", 0).is_empty()); |
| 2518 | } |
| 2519 | |
| 2520 | /// A small non-zero limit must cap the token list this function builds. |
| 2521 | /// |
| 2522 | /// The empty-partial branch is pass-through by design — those entries were |
| 2523 | /// already capped upstream by `rank_completion_candidates`, and shrinking |
| 2524 | /// them here would silently drop paths the caller asked for. |
| 2525 | #[test] |
| 2526 | fn git_mention_entries_never_exceed_the_menu_limit() { |
| 2527 | let paths = vec!["a.rs".to_string(), "b.rs".to_string()]; |
| 2528 | for limit in 1..=4 { |
| 2529 | let matched = with_git_mention_entries(paths.clone(), "d", limit); |
| 2530 | assert!(matched.len() <= limit, "limit {limit}: {matched:?}"); |
| 2531 | // Both tokens match a bare prefix that hits `git` and `diff` |
| 2532 | // through separate entries; the cap still holds. |
| 2533 | let both = with_git_mention_entries(Vec::new(), "", limit); |
| 2534 | assert!(both.len() <= limit, "limit {limit}: {both:?}"); |
| 2535 | } |
| 2536 | // Pass-through: the caller's already-capped paths survive untouched. |
| 2537 | assert_eq!(with_git_mention_entries(paths.clone(), "", 1), paths); |
| 2538 | } |
| 2539 | |
| 2540 | /// #4067 review follow-up: one submit resolves a git mention once, not |
| 2541 | /// once per surface. `@diff` makes git compute the whole working-tree diff |
| 2542 | /// before the byte budget applies, so a repeat is real wasted work. |
| 2543 | #[test] |
| 2544 | fn a_submit_resolves_each_git_mention_only_once() { |
| 2545 | let tmp = TempDir::new().expect("tempdir"); |
| 2546 | init_test_repo(tmp.path()); |
| 2547 | std::fs::write(tmp.path().join("a.txt"), "one\n").expect("write"); |
| 2548 | commit_test_repo(tmp.path()); |
| 2549 | std::fs::write(tmp.path().join("a.txt"), "two\n").expect("write"); |
| 2550 | |
| 2551 | let mut cache = crate::tui::git_mention::GitMentionCache::default(); |
| 2552 | let references = context_references_from_input_cached( |
| 2553 | "@diff", |
| 2554 | tmp.path(), |
| 2555 | Some(tmp.path().to_path_buf()), |
| 2556 | &mut cache, |
| 2557 | None, |
| 2558 | ); |
| 2559 | let expanded = user_request_with_file_mentions_cached( |
| 2560 | "@diff", |
| 2561 | tmp.path(), |
| 2562 | Some(tmp.path().to_path_buf()), |
| 2563 | &mut cache, |
| 2564 | None, |
| 2565 | ); |
| 2566 | |
| 2567 | // Both surfaces describe the same resolution. |
| 2568 | let git_ref = references |
| 2569 | .iter() |
| 2570 | .find(|r| r.kind == ContextReferenceKind::GitContext) |
| 2571 | .expect("git reference"); |
| 2572 | assert!(git_ref.included); |
| 2573 | assert!(expanded.contains("<git-diff"), "{expanded}"); |
| 2574 | |
| 2575 | // And the shared cache holds exactly one entry for it. |
| 2576 | assert_eq!(cache.len(), 1, "the diff must be resolved once per submit"); |
| 2577 | } |
| 2578 | |
| 2579 | #[test] |
| 2580 | fn completion_offers_git_and_diff_alongside_paths() { |
| 2581 | let paths = vec!["src/main.rs".to_string(), "docs/guide.md".to_string()]; |
| 2582 | // A bare `@` stays the file picker. |
| 2583 | assert_eq!(with_git_mention_entries(paths.clone(), "", 8), paths); |
| 2584 | |
| 2585 | let narrowed = with_git_mention_entries(paths.clone(), "di", 8); |
| 2586 | assert_eq!(narrowed.first().map(String::as_str), Some("diff")); |
| 2587 | assert!(narrowed.contains(&"src/main.rs".to_string())); |
| 2588 | |
| 2589 | let git_only = with_git_mention_entries(paths.clone(), "g", 8); |
| 2590 | assert_eq!(git_only.first().map(String::as_str), Some("git")); |
| 2591 | |
| 2592 | // A partial that matches no token leaves path completion untouched. |
| 2593 | assert_eq!(with_git_mention_entries(paths.clone(), "src", 8), paths); |
| 2594 | } |
| 2595 | |
| 2596 | // ------------------------------------------------------------------ |
| 2597 | // macOS screencapture-temp stabilization |
| 2598 | // ------------------------------------------------------------------ |
| 2599 | |
| 2600 | /// A fake macOS screencapture temp tree. Returns the tempdir (alive for |
| 2601 | /// the test's duration), the screenshot source path, and the artifact dir |
| 2602 | /// stabilization should copy into. |
| 2603 | fn screencapture_fixture() -> (TempDir, PathBuf, PathBuf) { |
| 2604 | let tmp = TempDir::new().expect("tempdir"); |
| 2605 | let source_dir = tmp |
| 2606 | .path() |
| 2607 | .join("Temporary Items") |
| 2608 | .join("NSIRD_screencaptureui_7F3A"); |
| 2609 | std::fs::create_dir_all(&source_dir).expect("mkdir"); |
| 2610 | let source = source_dir.join("Screenshot 2026-08-10 at 01.09.39 截图.png"); |
| 2611 | std::fs::write(&source, b"fake screenshot bytes").expect("write"); |
| 2612 | let artifact_dir = tmp.path().join("attachments"); |
| 2613 | (tmp, source, artifact_dir) |
| 2614 | } |
| 2615 | |
| 2616 | #[test] |
| 2617 | fn detects_screencapture_temp_paths() { |
| 2618 | assert!(is_screencapture_temp_path(Path::new( |
| 2619 | "/var/folders/x/T/Temporary Items/NSIRD_screencaptureui_ABC/Shot.png" |
| 2620 | ))); |
| 2621 | // The spelling in the founder's failing drop (macOS 26). |
| 2622 | assert!(is_screencapture_temp_path(Path::new( |
| 2623 | "/var/folders/gc/x/T/TemporaryItems/NSIRD_screencaptureui_IqPorQ/Screenshot 2026-10-04 at 22.25.47.png" |
| 2624 | ))); |
| 2625 | assert!(!is_screencapture_temp_path(Path::new( |
| 2626 | "/tmp/TemporaryItems/Shot.png" |
| 2627 | ))); |
| 2628 | let (tmp, source, _) = screencapture_fixture(); |
| 2629 | assert!(is_screencapture_temp_path(&source)); |
| 2630 | // Only one marker is not a screencapture temp location. |
| 2631 | assert!(!is_screencapture_temp_path(Path::new( |
| 2632 | "/tmp/Temporary Items/Shot.png" |
| 2633 | ))); |
| 2634 | assert!(!is_screencapture_temp_path(Path::new("/tmp/Shot.png"))); |
| 2635 | assert!(!is_screencapture_temp_path(tmp.path())); |
| 2636 | } |
| 2637 | |
| 2638 | #[test] |
| 2639 | fn stabilizes_a_quoted_paste_with_spaces_and_unicode() { |
| 2640 | let (tmp, source, artifact_dir) = screencapture_fixture(); |
| 2641 | let input = format!("take a look at \"{}\" please", source.display()); |
| 2642 | let out = stabilize_screenshot_references(&input, &artifact_dir); |
| 2643 | |
| 2644 | let stable = artifact_dir.join("Screenshot 2026-08-10-01.09.39 截图.png"); |
| 2645 | assert_eq!( |
| 2646 | std::fs::read(&stable).expect("stable copy"), |
| 2647 | b"fake screenshot bytes" |
| 2648 | ); |
| 2649 | assert!(out.contains(&stable.display().to_string()), "got: {out}"); |
| 2650 | assert!(!out.contains(&source.display().to_string()), "got: {out}"); |
| 2651 | assert!(source.is_file(), "source must be left in place"); |
| 2652 | // Idempotent: the stable path is not a screencapture reference, and a |
| 2653 | // second pass over the rewritten text changes nothing. |
| 2654 | assert_eq!(stabilize_screenshot_references(&out, &artifact_dir), out); |
| 2655 | let _ = tmp; |
| 2656 | } |
| 2657 | |
| 2658 | #[test] |
| 2659 | fn stabilizes_mention_attached_and_unquoted_references() { |
| 2660 | let (tmp, source, artifact_dir) = screencapture_fixture(); |
| 2661 | let disp = source.display().to_string(); |
| 2662 | let input = format!("see @\"{disp}\", also [Attached image: {disp}] and bare {disp} here"); |
| 2663 | let out = stabilize_screenshot_references(&input, &artifact_dir); |
| 2664 | |
| 2665 | let stable = artifact_dir.join("Screenshot 2026-08-10-01.09.39 截图.png"); |
| 2666 | let stable_disp = stable.display().to_string(); |
| 2667 | // Three different carriers, one stable destination each time, and |
| 2668 | // exactly one physical copy despite the duplicates. |
| 2669 | assert_eq!(out.matches(&stable_disp).count(), 3, "got: {out}"); |
| 2670 | assert!(!out.contains(&disp), "got: {out}"); |
| 2671 | assert_eq!( |
| 2672 | std::fs::read_dir(&artifact_dir).expect("artifacts").count(), |
| 2673 | 1 |
| 2674 | ); |
| 2675 | let _ = tmp; |
| 2676 | } |
| 2677 | |
| 2678 | #[test] |
| 2679 | fn leaves_missing_and_non_screencapture_paths_alone() { |
| 2680 | let (tmp, source, artifact_dir) = screencapture_fixture(); |
| 2681 | let ghost = source.with_file_name("Screenshot 1999-01-01 at 00.00.00.png"); |
| 2682 | let input = format!( |
| 2683 | "missing {} regular /tmp/notes.txt mention @README.md quote \"no file\"", |
| 2684 | ghost.display() |
| 2685 | ); |
| 2686 | let out = stabilize_screenshot_references(&input, &artifact_dir); |
| 2687 | assert_eq!(out, input); |
| 2688 | assert!(std::fs::read_dir(&artifact_dir).is_err()); |
| 2689 | let _ = tmp; |
| 2690 | } |
| 2691 | |
| 2692 | #[test] |
| 2693 | fn single_quoted_prose_does_not_block_a_real_reference() { |
| 2694 | let (tmp, source, artifact_dir) = screencapture_fixture(); |
| 2695 | let disp = source.display().to_string(); |
| 2696 | // The `'` pair encloses the path but is prose, not a quoted path. |
| 2697 | let input = format!("'check {disp} is here' please"); |
| 2698 | let out = stabilize_screenshot_references(&input, &artifact_dir); |
| 2699 | let stable = artifact_dir.join("Screenshot 2026-08-10-01.09.39 截图.png"); |
| 2700 | assert!(out.contains(&stable.display().to_string()), "got: {out}"); |
| 2701 | assert!(!out.contains(&disp), "got: {out}"); |
| 2702 | let _ = tmp; |
| 2703 | } |
| 2704 | |
| 2705 | #[test] |
| 2706 | fn handles_leading_delimiters_on_unquoted_pastes() { |
| 2707 | let (tmp, source, artifact_dir) = screencapture_fixture(); |
| 2708 | let disp = source.display().to_string(); |
| 2709 | // Paren-wrapped paste: the `(` rides on the first path token, and an |
| 2710 | // unquoted `@`-prefixed paste keeps its `@` in the rewritten text. |
| 2711 | let input = format!("see ({disp}) and also @{disp} thanks"); |
| 2712 | let out = stabilize_screenshot_references(&input, &artifact_dir); |
| 2713 | let stable = artifact_dir.join("Screenshot 2026-08-10-01.09.39 截图.png"); |
| 2714 | let stable_disp = stable.display().to_string(); |
| 2715 | assert_eq!(out.matches(&stable_disp).count(), 2, "got: {out}"); |
| 2716 | assert!(out.contains(&format!("({stable_disp})")), "got: {out}"); |
| 2717 | assert!(out.contains(&format!("@{stable_disp}")), "got: {out}"); |
| 2718 | assert!(!out.contains(&disp), "got: {out}"); |
| 2719 | let _ = tmp; |
| 2720 | } |
| 2721 | |
| 2722 | #[test] |
| 2723 | fn stabilizes_a_dropped_attachment_under_compact_temporary_items() { |
| 2724 | let tmp = TempDir::new().expect("tempdir"); |
| 2725 | let source_dir = tmp |
| 2726 | .path() |
| 2727 | .join("TemporaryItems") |
| 2728 | .join("NSIRD_screencaptureui_IqPorQ"); |
| 2729 | std::fs::create_dir_all(&source_dir).expect("mkdir"); |
| 2730 | let source = source_dir.join("Screenshot 2026-10-04 at 22.25.47.png"); |
| 2731 | std::fs::write(&source, b"screenshot").expect("write"); |
| 2732 | let artifact_dir = tmp.path().join("attachments"); |
| 2733 | let input = format!("what is this?\n[Attached image: {}]\n", source.display()); |
| 2734 | |
| 2735 | let out = stabilize_screenshot_references(&input, &artifact_dir); |
| 2736 | |
| 2737 | let stable = artifact_dir.join("Screenshot 2026-10-04-22.25.47.png"); |
| 2738 | assert!(stable.is_file(), "stable copy must exist"); |
| 2739 | assert!( |
| 2740 | out.contains(&format!("[Attached image: {}]", stable.display())), |
| 2741 | "got: {out}" |
| 2742 | ); |
| 2743 | let _ = tmp; |
| 2744 | } |
| 2745 | |
| 2746 | #[test] |
| 2747 | fn handles_a_multibyte_final_filename_char() { |
| 2748 | let tmp = TempDir::new().expect("tempdir"); |
| 2749 | let source_dir = tmp |
| 2750 | .path() |
| 2751 | .join("Temporary Items") |
| 2752 | .join("NSIRD_screencaptureui_9B2C"); |
| 2753 | std::fs::create_dir_all(&source_dir).expect("mkdir"); |
| 2754 | // No ASCII extension: the reference span ends on a CJK code point. |
| 2755 | let source = source_dir.join("截图"); |
| 2756 | std::fs::write(&source, b"screenshot").expect("write"); |
| 2757 | let artifact_dir = tmp.path().join("attachments"); |
| 2758 | let input = format!("here {} it is", source.display()); |
| 2759 | let out = stabilize_screenshot_references(&input, &artifact_dir); |
| 2760 | let stable = artifact_dir.join("截图"); |
| 2761 | assert!(out.contains(&stable.display().to_string()), "got: {out}"); |
| 2762 | assert!(!out.contains(&source.display().to_string()), "got: {out}"); |
| 2763 | let _ = tmp; |
| 2764 | } |
| 2765 | |
| 2766 | /// The stable copy is written through a no-follow writer: a dangling link |
| 2767 | /// at the destination name, a linked destination, and a linked directory |
| 2768 | /// are all refused, and nothing is created behind them. |
| 2769 | #[cfg(unix)] |
| 2770 | #[test] |
| 2771 | fn stable_copies_are_never_written_through_a_link() { |
| 2772 | use std::os::unix::fs::symlink; |
| 2773 | let (tmp, source, artifact_dir) = screencapture_fixture(); |
| 2774 | let outside = TempDir::new().expect("outside"); |
| 2775 | let input = format!("see \"{}\"", source.display()); |
| 2776 | let name = "Screenshot 2026-08-10-01.09.39 截图.png"; |
| 2777 | |
| 2778 | // Dangling link at the destination name. |
| 2779 | std::fs::create_dir_all(&artifact_dir).expect("mkdir"); |
| 2780 | let behind = outside.path().join("created-by-the-link"); |
| 2781 | symlink(&behind, artifact_dir.join(name)).expect("link"); |
| 2782 | assert_eq!( |
| 2783 | stabilize_screenshot_references(&input, &artifact_dir), |
| 2784 | input |
| 2785 | ); |
| 2786 | assert!( |
| 2787 | !behind.exists(), |
| 2788 | "a dangling link must not be written through" |
| 2789 | ); |
| 2790 | |
| 2791 | // A linked destination directory. |
| 2792 | let linked_dir = tmp.path().join("linked-attachments"); |
| 2793 | symlink(outside.path(), &linked_dir).expect("link"); |
| 2794 | assert_eq!(stabilize_screenshot_references(&input, &linked_dir), input); |
| 2795 | assert_eq!(std::fs::read_dir(outside.path()).unwrap().count(), 0); |
| 2796 | let _ = tmp; |
| 2797 | } |
| 2798 | |
| 2799 | #[test] |
| 2800 | fn keeps_the_original_reference_when_the_copy_fails() { |
| 2801 | let (tmp, source, _) = screencapture_fixture(); |
| 2802 | let blocker = tmp.path().join("blocker"); |
| 2803 | std::fs::write(&blocker, b"x").expect("write"); |
| 2804 | // create_dir_all under a regular file must fail. |
| 2805 | let bad_artifact_dir = blocker.join("attachments"); |
| 2806 | let input = format!("see \"{}\"", source.display()); |
| 2807 | let out = stabilize_screenshot_references(&input, &bad_artifact_dir); |
| 2808 | assert_eq!(out, input); |
| 2809 | assert!(source.is_file()); |
| 2810 | let _ = tmp; |
| 2811 | } |
| 2812 | } |
| 2813 |