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
//! File paths in the transcript drawn as links to the files.
//!
//! A path links only once it is known to be a file in the session's
//! workspace. Rendering never touches the file system: it reads
//! [`PathIndex`] through a [`PathLinker`], links the paths known to be files,
//! and reports every other mention. The history cache queues those for a
//! [`PathCheck`], which runs off the UI thread; its result re-renders the
//! entries that mention a newly found file. A linked path keeps its text as
//! written, with its folders and position dimmer than its file name, and
//! carries a `file://` URL that the terminal backend writes as an OSC 8
//! hyperlink. With icons on, a Nerd Font file-type icon comes before it,
//! outside the link.
mod icons;
mod target;
pub(super) use icons::is_icon_run;
use std::{
collections::{HashMap, HashSet},
path::{Path, PathBuf},
sync::Arc,
};
use ratatui::style::{Modifier, Style};
use super::{text_links::LinkedRun, theme::Theme};
#[cfg(test)]
#[path = "path_links_tests.rs"]
mod tests;
/// What is known about one workspace-relative path.
#[derive(Clone, Debug, PartialEq, Eq)]
enum Known {
/// Queued for, or inside, a check.
Checking,
/// A file; its `file://` URL.
File(Arc<str>),
/// Not a file, or the check failed. Checked again when a turn ends.
Missing,
}
/// The paths the transcript mentions and which of them are files in the
/// workspace, as far as checks have found.
#[derive(Debug)]
pub(super) struct PathIndex {
workspace: PathBuf,
known: HashMap<String, Known>,
/// Paths waiting for the next check, in the order rendering met them.
queued: Vec<String>,
}
impl PathIndex {
pub(super) fn new(workspace: PathBuf) -> Self {
Self {
workspace,
known: HashMap::new(),
queued: Vec::new(),
}
}
pub(super) fn workspace(&self) -> &Path {
&self.workspace
}
/// The URL of `path` when it is known to be a file.
fn file_url(&self, path: &str) -> Option<&Arc<str>> {
match self.known.get(path) {
Some(Known::File(url)) => Some(url),
Some(Known::Checking | Known::Missing) | None => None,
}
}
/// Queues the paths in `mentioned` that were never looked up.
pub(super) fn want<'a>(&mut self, mentioned: impl IntoIterator<Item = &'a str>) {
for path in mentioned {
if !self.known.contains_key(path) {
self.known.insert(path.to_owned(), Known::Checking);
self.queued.push(path.to_owned());
}
}
}
/// Queues every path a check found missing, or that a running check may
/// have looked up too early: the turn that just ended may have written it.
pub(super) fn recheck_missing(&mut self) {
let queued: HashSet<&str> = self.queued.iter().map(String::as_str).collect();
let mut recheck = Vec::new();
for (path, known) in &mut self.known {
let in_flight = *known == Known::Checking && !queued.contains(path.as_str());
if *known == Known::Missing || in_flight {
*known = Known::Checking;
recheck.push(path.clone());
}
}
self.queued.extend(recheck);
}
/// Takes every queued path as one check, if any are queued.
pub(super) fn take_check(&mut self) -> Option<PathCheck> {
(!self.queued.is_empty()).then(|| PathCheck {
workspace: self.workspace.clone(),
paths: std::mem::take(&mut self.queued),
})
}
/// Records `checked` and returns the paths it found to be files. A check
/// of another workspace, from before the session moved, changes nothing.
pub(super) fn apply(&mut self, checked: CheckedPaths) -> Vec<String> {
if checked.workspace != self.workspace {
return Vec::new();
}
let mut found = Vec::new();
for (path, url) in checked.paths {
let known = match url {
Some(url) => {
found.push(path.clone());
Known::File(url)
}
None => Known::Missing,
};
self.known.insert(path, known);
}
found
}
}
/// Paths to look up in a workspace. [`Self::run`] blocks on the file system.
#[derive(Debug)]
pub(super) struct PathCheck {
workspace: PathBuf,
paths: Vec<String>,
}
/// What a [`PathCheck`] found: each path's URL when it is a file.
#[derive(Debug)]
pub(super) struct CheckedPaths {
workspace: PathBuf,
paths: Vec<(String, Option<Arc<str>>)>,
}
impl PathCheck {
/// Looks up every path. Blocks; run it off the UI thread. A path links
/// when it resolves, symlinks and `..` followed, to a file inside the
/// workspace; the URL names that file.
pub(super) fn run(self) -> CheckedPaths {
let host = file_url_host();
let root = self.workspace.canonicalize().ok();
let paths = self
.paths
.into_iter()
.map(|path| {
let url = root.as_deref().and_then(|root| {
let file = self.workspace.join(&path).canonicalize().ok()?;
(file.starts_with(root) && file.is_file())
.then(|| file_url(&file, host.as_deref()))
.flatten()
});
(path, url)
})
.collect();
CheckedPaths {
workspace: self.workspace,
paths,
}
}
}
/// The host a `file://` URL names, so a terminal can tell a file on this
/// machine from one on a machine reached over SSH. Windows keeps the host
/// empty: a host there would name a network share.
fn file_url_host() -> Option<String> {
if cfg!(windows) {
return None;
}
gethostname::gethostname().into_string().ok()
}
/// `path`'s `file://` URL, percent-encoded, naming `host` when it is a valid one.
fn file_url(path: &Path, host: Option<&str>) -> Option<Arc<str>> {
let mut url = url::Url::from_file_path(path).ok()?;
if let Some(host) = host {
// A host name URLs cannot carry leaves the URL host-less.
let _ = url.set_host(Some(host));
}
Some(url.as_str().into())
}
/// How a linked path is styled where it is drawn.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct PathLinkStyle {
/// The file name.
pub(super) name: Style,
/// Its folders and `:line`.
pub(super) quiet: Style,
}
impl PathLinkStyle {
/// A transcript path: the name in the accent color, its folders and
/// `:line` dimmer.
pub(super) fn transcript() -> Self {
let name = Theme::accent().remove_modifier(Modifier::UNDERLINED);
Self {
name,
quiet: name.add_modifier(Modifier::DIM),
}
}
/// A path on the user message bar, where the accent loses contrast: the
/// bar's own colors, underlined, with the name bold.
pub(super) fn user_message() -> Self {
let quiet = Theme::user_message().add_modifier(Modifier::UNDERLINED);
Self {
name: quiet.add_modifier(Modifier::BOLD),
quiet,
}
}
}
/// One render's view of a [`PathIndex`]: links the paths known to be files
/// and collects the other mentions, which the caller hands back to the index
/// with [`PathIndex::want`].
pub(super) struct PathLinker<'a> {
index: Option<&'a PathIndex>,
unlinked: Vec<String>,
/// Draw a file-type icon before each linked path.
icons: bool,
}
impl<'a> PathLinker<'a> {
pub(super) fn new(index: &'a PathIndex) -> Self {
Self {
index: Some(index),
unlinked: Vec::new(),
icons: false,
}
}
/// This linker, drawing a Nerd Font file-type icon before each path it
/// links.
pub(super) fn with_icons(self) -> Self {
Self {
icons: true,
..self
}
}
/// A linker that links nothing and reports nothing, for text that is
/// still streaming or is not transcript content.
pub(super) fn off() -> Self {
Self {
index: None,
unlinked: Vec::new(),
icons: false,
}
}
/// The mentions this render met that are not linked.
pub(super) fn into_unlinked(self) -> Vec<String> {
self.unlinked
}
/// Prose `text` in `base`, each linked path in its own runs.
pub(super) fn prose(
&mut self,
text: &str,
base: Style,
style: PathLinkStyle,
) -> Vec<LinkedRun> {
let Some(index) = self.index else {
return vec![LinkedRun::plain(text, base)];
};
let mut runs = Vec::new();
let mut shown = 0;
for mention in target::prose_mentions(text, index.workspace()) {
let Some(url) = self.link(index, mention.path) else {
continue;
};
if shown < mention.range.start {
runs.push(LinkedRun::plain(&text[shown..mention.range.start], base));
}
let written = &text[mention.range.clone()];
runs.extend(self.link_runs(written, mention.path_len, url, style));
shown = mention.range.end;
}
if shown < text.len() || runs.is_empty() {
runs.push(LinkedRun::plain(&text[shown..], base));
}
runs
}
/// `text` as a link when all of it is one linked path, as an inline code
/// span or a tool call's argument may be.
pub(super) fn whole(&mut self, text: &str, style: PathLinkStyle) -> Option<Vec<LinkedRun>> {
let index = self.index?;
let mention = target::whole_mention(text, index.workspace())?;
let url = self.link(index, mention.path)?;
Some(self.link_runs(text, mention.path_len, url, style))
}
/// `path`'s URL if it is a known file; otherwise records it as unlinked.
fn link(&mut self, index: &PathIndex, path: String) -> Option<Arc<str>> {
let url = index.file_url(&path).cloned();
if url.is_none() {
self.unlinked.push(path);
}
url
}
/// `written`, a path then its position from `path_len` on, as runs: its
/// icon when icons are on, unlinked, then its folders, file name, and
/// position, linked.
fn link_runs(
&self,
written: &str,
path_len: usize,
url: Arc<str>,
style: PathLinkStyle,
) -> Vec<LinkedRun> {
let (path, position) = written.split_at(path_len);
let name_start = path
.rfind(std::path::is_separator)
.map_or(0, |slash| slash + 1);
let (folders, name) = path.split_at(name_start);
let icon = self
.icons
.then(|| LinkedRun::plain(icons::icon_run_text(name), style.name));
let linked = [
(folders, style.quiet),
(name, style.name),
(position, style.quiet),
]
.into_iter()
.filter(|(text, _)| !text.is_empty())
.map(|(text, style)| LinkedRun::linked(text, style, Arc::clone(&url)));
icon.into_iter().chain(linked).collect()
}
}