deepseek-tui 0.6.5

Terminal UI for DeepSeek
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
//! `@`-mention parsing, completion, and expansion for the composer.
//!
//! Two responsibilities live here:
//!
//! 1. **Tab-completion** at the cursor — `try_autocomplete_file_mention` is
//!    called by the composer's Tab handler. Walks the workspace, ranks
//!    candidates by prefix-then-substring match, and either splices the
//!    completion in directly (single match), extends to a shared prefix, or
//!    surfaces options in the status line.
//! 2. **Expansion before send** — when the user hits Enter on a message that
//!    contains `@<path>` references, `user_request_with_file_mentions`
//!    appends a "Local context from @mentions" block with the file contents
//!    (or directory listings, or media-attachment hints) so the model can see
//!    what the user pointed at. Capped per-message and per-file.
//!
//! The module is deliberately self-contained: nothing inside reaches into UI
//! widgets or rendering, so it stays unit-testable from `ui/tests.rs` and
//! from its own module-level tests.
//!
//! Pulled out of `ui.rs` to shrink the 5,500-line monolith and to give the
//! mention logic a single home that future maintainers can find without
//! grepping for `@` across half the codebase.

use std::fmt::Write;
use std::io::Read;
use std::path::Path;

use ignore::WalkBuilder;

use crate::tui::app::App;
use crate::working_set::Workspace;

/// Maximum number of `@`-mentions whose contents are inlined into one user
/// message. Beyond this we stop appending blocks but the raw `@token` text
/// remains in the message.
pub const MAX_FILE_MENTIONS_PER_MESSAGE: usize = 8;
/// Per-file byte ceiling when inlining mention contents.
pub const MAX_MENTION_FILE_BYTES: u64 = 128 * 1024;
/// Per-directory entry ceiling when inlining a directory listing.
pub const MAX_DIRECTORY_MENTION_ENTRIES: usize = 80;

/// Maximum file-mention completion candidates to consider per keypress. Caps
/// the cost of walking large workspaces; subsequent keystrokes narrow further.
const FILE_MENTION_COMPLETION_LIMIT: usize = 64;

/// Maximum directory depth walked when completing a file mention. Mirrors the
/// existing `project_tree` cutoff and keeps Tab snappy in deep monorepos.
const FILE_MENTION_COMPLETION_DEPTH: usize = 6;

// ---------------------------------------------------------------------------
//  Tab-completion
// ---------------------------------------------------------------------------

/// If the cursor sits inside a `@<partial>` token in the input, return the
/// byte offset where the `@` starts (so we can splice in a completion) and
/// the partial path the user has typed so far. The token stops at whitespace
/// or the end of input. Returns `None` when the cursor is outside any mention
/// or the token is empty (`@` with nothing after it).
pub fn partial_file_mention_at_cursor(input: &str, cursor_chars: usize) -> Option<(usize, String)> {
    let chars: Vec<char> = input.chars().collect();
    if cursor_chars > chars.len() {
        return None;
    }
    // Walk left from the cursor until we find an `@` or a whitespace; if
    // whitespace comes first the cursor isn't inside a mention.
    let mut start_chars = cursor_chars;
    while start_chars > 0 {
        let prev = chars[start_chars - 1];
        if prev == '@' {
            start_chars -= 1;
            break;
        }
        if prev.is_whitespace() {
            return None;
        }
        start_chars -= 1;
    }
    if start_chars == cursor_chars || chars.get(start_chars) != Some(&'@') {
        return None;
    }
    // Confirm the `@` itself is at a valid mention boundary.
    if !is_file_mention_start(&chars, start_chars) {
        return None;
    }
    // Consume from the `@` to the next whitespace (the end of the token).
    let mut end_chars = start_chars + 1;
    while end_chars < chars.len() && !chars[end_chars].is_whitespace() {
        end_chars += 1;
    }
    let partial: String = chars[start_chars + 1..end_chars].iter().collect();
    let byte_start: usize = chars[..start_chars].iter().map(|c| c.len_utf8()).sum();
    Some((byte_start, partial))
}

/// Walk the workspace and return relative paths whose representation matches
/// the partial mention. A file matches when its case-insensitive relative
/// path either starts with the partial or contains it as a substring; the
/// former rank earlier so a partial like `docs/de` resolves to
/// `docs/deepseek_v4.pdf` before any path that merely contains those bytes.
pub fn find_file_mention_completions(workspace: &Path, partial: &str, limit: usize) -> Vec<String> {
    if limit == 0 {
        return Vec::new();
    }
    let needle = partial.to_lowercase();
    let mut prefix_hits: Vec<String> = Vec::new();
    let mut substring_hits: Vec<String> = Vec::new();

    let mut builder = WalkBuilder::new(workspace);
    builder
        .hidden(true)
        .follow_links(false)
        .max_depth(Some(FILE_MENTION_COMPLETION_DEPTH));

    for entry in builder.build().flatten() {
        if prefix_hits.len() + substring_hits.len() >= limit {
            break;
        }
        let path = entry.path();
        let Ok(rel) = path.strip_prefix(workspace) else {
            continue;
        };
        let rel_str = rel.to_string_lossy().replace('\\', "/");
        if rel_str.is_empty() {
            continue;
        }
        let is_dir = entry.file_type().is_some_and(|ft| ft.is_dir());
        let candidate = if is_dir {
            format!("{rel_str}/")
        } else {
            rel_str.clone()
        };
        let lower = candidate.to_lowercase();
        if needle.is_empty() || lower.starts_with(&needle) {
            prefix_hits.push(candidate);
        } else if lower.contains(&needle) {
            substring_hits.push(candidate);
        }
    }

    prefix_hits.sort();
    substring_hits.sort();
    prefix_hits.extend(substring_hits);
    prefix_hits.truncate(limit);
    prefix_hits
}

/// Resolve the `@`-mention completion popup contents for the current
/// composer state. Returns an empty `Vec` when:
///
/// - The popup is suppressed (`app.mention_menu_hidden`).
/// - The cursor is not inside an `@<partial>` token.
/// - The workspace walk produced no candidates.
///
/// Mirrors `visible_slash_menu_entries` so the composer widget can treat
/// both menus identically (one `Vec<String>` of entries, one selected index).
///
/// Once the composer widget is extended to render this as a popup, it will
/// pair with `apply_mention_menu_selection` for the Up/Down/Enter flow.
#[must_use]
pub fn visible_mention_menu_entries(app: &App, limit: usize) -> Vec<String> {
    if app.mention_menu_hidden {
        return Vec::new();
    }
    let Some((_byte_start, partial)) =
        partial_file_mention_at_cursor(&app.input, app.cursor_position)
    else {
        return Vec::new();
    };
    if limit == 0 {
        return Vec::new();
    }
    find_file_mention_completions(&app.workspace, &partial, limit)
}

/// Apply the currently selected `@`-mention popup entry to the composer
/// input, splicing it in place of the `@<partial>` token at the cursor.
/// Returns `true` if a substitution occurred.
///
/// Designed to be invoked by the same keybinding that drives
/// `apply_slash_menu_selection` (Enter / Tab); the caller is responsible
/// for choosing which menu is "active" based on cursor context.
pub fn apply_mention_menu_selection(app: &mut App, entries: &[String]) -> bool {
    if entries.is_empty() {
        return false;
    }
    let Some((byte_start, partial)) =
        partial_file_mention_at_cursor(&app.input, app.cursor_position)
    else {
        return false;
    };
    let selected_idx = app
        .mention_menu_selected
        .min(entries.len().saturating_sub(1));
    let replacement = &entries[selected_idx];
    replace_file_mention(app, byte_start, &partial, replacement);
    app.mention_menu_hidden = false;
    app.status_message = Some(format!("Attached @{replacement}"));
    true
}

/// Tab-completion handler for `@file` mentions. Mirrors the slash-command
/// flow: a single match is applied directly; multiple matches with a longer
/// shared prefix extend the partial; otherwise the first few candidates are
/// surfaced via the status line. Returns true when the input was modified or
/// a suggestion was offered, so the caller can short-circuit other handlers.
pub fn try_autocomplete_file_mention(app: &mut App) -> bool {
    let Some((byte_start, partial)) =
        partial_file_mention_at_cursor(&app.input, app.cursor_position)
    else {
        return false;
    };
    let workspace = app.workspace.clone();
    let candidates =
        find_file_mention_completions(&workspace, &partial, FILE_MENTION_COMPLETION_LIMIT);
    if candidates.is_empty() {
        app.status_message = Some(format!("No files match @{partial}"));
        return true;
    }
    if candidates.len() == 1 {
        replace_file_mention(app, byte_start, &partial, &candidates[0]);
        app.status_message = Some(format!("Attached @{}", candidates[0]));
        return true;
    }
    let candidate_refs: Vec<&str> = candidates.iter().map(String::as_str).collect();
    let shared = longest_common_prefix(&candidate_refs);
    if shared.len() > partial.len() {
        replace_file_mention(app, byte_start, &partial, shared);
        app.status_message = Some(format!("@{shared}"));
        return true;
    }
    let preview = candidates
        .iter()
        .take(5)
        .map(|c| format!("@{c}"))
        .collect::<Vec<_>>()
        .join(", ");
    app.status_message = Some(format!("Matches: {preview}"));
    true
}

/// Splice a completion into the input, replacing the `@<partial>` token at
/// `byte_start` with `@<replacement>`. Cursor moves to the end of the new
/// token so further keystrokes extend (or escape via space) naturally.
fn replace_file_mention(app: &mut App, byte_start: usize, partial: &str, replacement: &str) {
    let original_token_len = '@'.len_utf8() + partial.len();
    let original_token_end = byte_start + original_token_len;
    let mut new_input =
        String::with_capacity(app.input.len() - original_token_len + 1 + replacement.len());
    new_input.push_str(&app.input[..byte_start]);
    new_input.push('@');
    new_input.push_str(replacement);
    if original_token_end < app.input.len() {
        new_input.push_str(&app.input[original_token_end..]);
    }
    let new_cursor_chars =
        app.input[..byte_start].chars().count() + 1 + replacement.chars().count();
    app.input = new_input;
    app.cursor_position = new_cursor_chars;
}

pub fn longest_common_prefix<'a>(values: &[&'a str]) -> &'a str {
    let Some(first) = values.first().copied() else {
        return "";
    };
    let mut end = first.len();

    for value in values.iter().skip(1) {
        while end > 0 && !value.starts_with(&first[..end]) {
            end -= 1;
            // Ensure we land on a valid UTF-8 char boundary.
            while end > 0 && !first.is_char_boundary(end) {
                end -= 1;
            }
        }
        if end == 0 {
            return "";
        }
    }

    &first[..end]
}

// ---------------------------------------------------------------------------
//  Expansion at send-time
// ---------------------------------------------------------------------------

/// Append a "Local context from @mentions" block to the user's message when
/// any `@path` references are present. Returns the input unchanged when
/// there are none.
pub fn user_request_with_file_mentions(input: &str, workspace: &Path) -> String {
    let Some(context) = local_context_from_file_mentions(input, workspace) else {
        return input.to_string();
    };
    format!("{input}\n\n---\n\nLocal context from @mentions:\n{context}")
}

fn local_context_from_file_mentions(input: &str, workspace: &Path) -> Option<String> {
    let mentions = extract_file_mentions(input);
    if mentions.is_empty() {
        return None;
    }

    let mut blocks = Vec::new();
    let mut seen = std::collections::HashSet::new();
    let ws = Workspace::new(workspace.to_path_buf());

    for mention in mentions.into_iter().take(MAX_FILE_MENTIONS_PER_MESSAGE) {
        // `Workspace::resolve` already returns absolute paths when the root
        // is absolute (TUI always runs from an absolute workspace), so we
        // skip `canonicalize()` here — it's per-mention I/O on the
        // message-send hot path. Accept the rare symlink-aliasing dedup
        // miss as the cost of avoiding a syscall (Gemini code-review).
        let (path, display_path, exists) = match ws.resolve(&mention) {
            Ok(p) => {
                let d = p.display().to_string();
                (p, d, true)
            }
            Err(p) => {
                let d = p.display().to_string();
                (p, d, false)
            }
        };

        // Gate every block — including <missing-file> — through the dedup
        // set so a user typing the same non-existent file twice doesn't
        // waste tokens on duplicate missing-file blocks (Devin code-review).
        if !seen.insert(display_path.clone()) {
            continue;
        }

        if exists {
            blocks.push(render_file_mention_context(&mention, &path, &display_path));
        } else {
            blocks.push(format!(
                "<missing-file mention=\"@{mention}\" path=\"{display_path}\" />"
            ));
        }
    }

    if blocks.is_empty() {
        None
    } else {
        Some(blocks.join("\n\n"))
    }
}

fn extract_file_mentions(input: &str) -> Vec<String> {
    let chars: Vec<char> = input.chars().collect();
    let mut mentions = Vec::new();
    let mut idx = 0;

    while idx < chars.len() {
        if chars[idx] != '@' || !is_file_mention_start(&chars, idx) {
            idx += 1;
            continue;
        }

        let Some(next) = chars.get(idx + 1).copied() else {
            break;
        };
        if next.is_whitespace() {
            idx += 1;
            continue;
        }

        if matches!(next, '"' | '\'') {
            let quote = next;
            let mut end = idx + 2;
            let mut raw = String::new();
            while end < chars.len() && chars[end] != quote {
                raw.push(chars[end]);
                end += 1;
            }
            if !raw.trim().is_empty() {
                mentions.push(raw.trim().to_string());
            }
            idx = end.saturating_add(1);
            continue;
        }

        let mut end = idx + 1;
        let mut raw = String::new();
        while end < chars.len() && !chars[end].is_whitespace() {
            raw.push(chars[end]);
            end += 1;
        }
        let trimmed = trim_unquoted_mention(&raw);
        if !trimmed.is_empty() {
            mentions.push(trimmed.to_string());
        }
        idx = end;
    }

    mentions
}

fn is_file_mention_start(chars: &[char], idx: usize) -> bool {
    if idx == 0 {
        return true;
    }
    chars
        .get(idx.saturating_sub(1))
        .is_some_and(|ch| ch.is_whitespace() || matches!(ch, '(' | '[' | '{' | '<' | '"' | '\''))
}

fn trim_unquoted_mention(raw: &str) -> &str {
    let mut trimmed = raw.trim();
    while trimmed.chars().count() > 1
        && trimmed
            .chars()
            .last()
            .is_some_and(|ch| matches!(ch, ',' | ';' | ':' | '!' | '?' | ')' | ']' | '}'))
    {
        trimmed = &trimmed[..trimmed.len() - trimmed.chars().last().unwrap().len_utf8()];
    }
    trimmed
}

fn render_file_mention_context(raw: &str, path: &Path, display_path: &str) -> String {
    if !path.exists() {
        return format!("<missing-file mention=\"@{raw}\" path=\"{display_path}\" />");
    }
    if path.is_dir() {
        return render_directory_mention_context(raw, path, display_path);
    }
    if !path.is_file() {
        return format!("<unsupported-path mention=\"@{raw}\" path=\"{display_path}\" />");
    }
    if is_media_path(path) {
        return format!(
            "<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>"
        );
    }

    match read_text_prefix(path) {
        Ok((text, truncated)) => {
            let truncated_attr = if truncated { " truncated=\"true\"" } else { "" };
            format!(
                "<file mention=\"@{raw}\" path=\"{display_path}\"{truncated_attr}>\n{text}\n</file>"
            )
        }
        Err(err) => {
            format!(
                "<unreadable-file mention=\"@{raw}\" path=\"{display_path}\">\n{err}\n</unreadable-file>"
            )
        }
    }
}

fn render_directory_mention_context(raw: &str, path: &Path, display_path: &str) -> String {
    let entries = match std::fs::read_dir(path) {
        Ok(entries) => entries,
        Err(err) => {
            return format!(
                "<unreadable-directory mention=\"@{raw}\" path=\"{display_path}\">\n{err}\n</unreadable-directory>"
            );
        }
    };

    let mut names = entries
        .filter_map(|entry| entry.ok())
        .map(|entry| {
            let marker = entry
                .file_type()
                .ok()
                .filter(|ty| ty.is_dir())
                .map_or("", |_| "/");
            format!("{}{}", entry.file_name().to_string_lossy(), marker)
        })
        .collect::<Vec<_>>();
    names.sort();
    let total = names.len();
    names.truncate(MAX_DIRECTORY_MENTION_ENTRIES);
    let mut body = names.join("\n");
    if total > MAX_DIRECTORY_MENTION_ENTRIES {
        let omitted = total - MAX_DIRECTORY_MENTION_ENTRIES;
        let _ = write!(body, "\n... {omitted} more entries");
    }
    format!("<directory mention=\"@{raw}\" path=\"{display_path}\">\n{body}\n</directory>")
}

fn read_text_prefix(path: &Path) -> std::io::Result<(String, bool)> {
    let mut file = std::fs::File::open(path)?;
    let mut buffer = Vec::new();
    file.by_ref()
        .take(MAX_MENTION_FILE_BYTES + 1)
        .read_to_end(&mut buffer)?;
    let truncated = buffer.len() as u64 > MAX_MENTION_FILE_BYTES;
    if truncated {
        buffer.truncate(MAX_MENTION_FILE_BYTES as usize);
    }
    if buffer.contains(&0) {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            "file appears to be binary",
        ));
    }
    let text = if truncated {
        String::from_utf8_lossy(&buffer).to_string()
    } else {
        std::str::from_utf8(&buffer)
            .map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidData, "file is not UTF-8"))?
            .to_string()
    };
    Ok((text, truncated))
}

fn is_media_path(path: &Path) -> bool {
    let Some(ext) = path.extension().and_then(|ext| ext.to_str()) else {
        return false;
    };
    matches!(
        ext.to_ascii_lowercase().as_str(),
        "png"
            | "jpg"
            | "jpeg"
            | "gif"
            | "webp"
            | "bmp"
            | "tif"
            | "tiff"
            | "ppm"
            | "mp4"
            | "mov"
            | "m4v"
            | "webm"
            | "avi"
            | "mkv"
    )
}