返回 CodeWhale
workspace_context.rs
根目录 / crates / tui / src / tui / workspace_context.rs
1 //! Per-workspace git context shown in the composer header.
2 //!
3 //! The TUI shows a "branch | clean/N modified/…" badge. It is derived from
4 //! the one cached git probe ([`codewhale_engine::git_status`]) rather than a git
5 //! query of its own, so the badge, the Git view and the chrome never run two
6 //! `git status` processes for the same tick (#6565). The badge is re-read
7 //! every `REFRESH_SECS` seconds; the read takes the probe's cached snapshot
8 //! and only probes when that snapshot is stale.
9
10 #[cfg(test)]
11 use codewhale_dependencies::{ExternalTool, Git};
12 use std::path::Path;
13 use std::time::{Duration, Instant};
14
15 use crate::tui::app::App;
16
17 /// How often (seconds) the workspace context badge is allowed to
18 /// re-query git. Exposed for tests that exercise the TTL.
19 pub(crate) const REFRESH_SECS: u64 = 15;
20
21 /// One completed background refresh, including an unavailable Git result.
22 #[derive(Debug)]
23 pub(crate) struct WorkspaceContextSnapshot {
24 pub workspace: std::path::PathBuf,
25 pub context: Option<String>,
26 pub is_linked_worktree: bool,
27 /// The workspace notes (`/note`), read off the render path with the git
28 /// context on the same TTL, for the dock's NOTES view.
29 pub notes: Vec<String>,
30 pub memory_size_hint: Option<String>,
31 }
32
33 /// Read the badge from the shared git probe: its cached snapshot while that
34 /// is fresh, or a new probe. `force` re-probes regardless, for an explicit
35 /// refresh after something that may have changed the tree.
36 fn collect_snapshot(workspace: &Path, force: bool) -> WorkspaceContextSnapshot {
37 let snap = if force {
38 codewhale_engine::git_status::force_refresh(workspace)
39 } else {
40 codewhale_engine::git_status::refresh_if_stale(workspace)
41 };
42 let current = snap.probed_workspace.as_deref() == Some(workspace);
43 WorkspaceContextSnapshot {
44 workspace: workspace.to_path_buf(),
45 context: current
46 .then(|| codewhale_engine::git_status::context_line(&snap))
47 .flatten(),
48 is_linked_worktree: current && snap.is_linked_worktree,
49 notes: crate::commands::read_notes(workspace, &crate::commands::notes_path(workspace))
50 .unwrap_or_default(),
51 memory_size_hint: None,
52 }
53 }
54
55 fn collect_snapshot_with_memory(
56 workspace: &Path,
57 force: bool,
58 memory_path: Option<std::path::PathBuf>,
59 ) -> WorkspaceContextSnapshot {
60 let mut snapshot = collect_snapshot(workspace, force);
61 snapshot.memory_size_hint = memory_path.as_deref().map(memory_size_hint);
62 snapshot
63 }
64
65 fn apply_snapshot(app: &mut App, snapshot: WorkspaceContextSnapshot) {
66 if snapshot.workspace != app.workspace {
67 return;
68 }
69 if app.workspace_context != snapshot.context
70 || app.workspace_is_linked_worktree != snapshot.is_linked_worktree
71 || app.workspace_notes != snapshot.notes
72 || app.memory_size_hint != snapshot.memory_size_hint
73 {
74 app.needs_redraw = true;
75 }
76 app.workspace_context = snapshot.context;
77 app.workspace_is_linked_worktree = snapshot.is_linked_worktree;
78 app.workspace_notes = snapshot.notes;
79 app.memory_size_hint = snapshot.memory_size_hint;
80 }
81
82 /// Pull a fresh workspace context from disk if the cached value is
83 /// older than [`REFRESH_SECS`] and `allow_refresh` is true. Always
84 /// drains any pending async result into `app.workspace_context` first
85 /// so the render pass sees the latest value (#399 S1).
86 pub(super) fn refresh_if_needed(app: &mut App, now: Instant, allow_refresh: bool) {
87 refresh_inner(app, now, allow_refresh, false);
88 }
89
90 fn refresh_inner(app: &mut App, now: Instant, allow_refresh: bool, force: bool) {
91 // Completion is distinct from a missing result: losing a repository must
92 // clear a stale branch, and an old workspace's refresh must not replace it.
93 let completed = app
94 .workspace_context_cell
95 .lock()
96 .ok()
97 .and_then(|mut cell| cell.take());
98 if let Some(snapshot) = completed {
99 apply_snapshot(app, snapshot);
100 }
101
102 if app
103 .workspace_context_refreshed_at
104 .is_some_and(|refreshed_at| {
105 now.duration_since(refreshed_at) < Duration::from_secs(REFRESH_SECS)
106 })
107 {
108 return;
109 }
110
111 if !allow_refresh {
112 return;
113 }
114
115 // Offload git query to a background thread when a Tokio runtime is
116 // available. Fall back to synchronous execution for tests and other
117 // non-async contexts (#399 S1).
118 if let Ok(handle) = tokio::runtime::Handle::try_current() {
119 let ctx = app.workspace_context_cell.clone();
120 let workspace = app.workspace.clone();
121 let memory_path = app.use_memory.then(|| app.memory_path.clone());
122 handle.spawn_blocking(move || {
123 let result = collect_snapshot_with_memory(&workspace, force, memory_path);
124 if let Ok(mut guard) = ctx.lock() {
125 *guard = Some(result);
126 }
127 });
128 } else {
129 // No runtime — run synchronously so tests and one-shot callers
130 // still get a result immediately.
131 let memory_path = app.use_memory.then(|| app.memory_path.clone());
132 let snapshot = collect_snapshot_with_memory(&app.workspace, force, memory_path);
133 apply_snapshot(app, snapshot);
134 }
135 app.workspace_context_refreshed_at = Some(now);
136 }
137
138 /// The memory file's size as the sidebar shows it; a missing or unreadable
139 /// file renders as an em dash.
140 fn memory_size_hint(memory_path: &Path) -> String {
141 std::fs::metadata(memory_path)
142 .map(|meta| format_size(meta.len()))
143 .unwrap_or_else(|_| "\u{2014}".to_string())
144 }
145
146 /// Human-readable byte size, in the exact shape the sidebar rendered inline.
147 fn format_size(bytes: u64) -> String {
148 if bytes >= 1024 * 1024 {
149 format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0))
150 } else if bytes >= 1024 {
151 format!("{:.1} KB", bytes as f64 / 1024.0)
152 } else {
153 format!("{bytes} B")
154 }
155 }
156
157 /// Force a workspace-context re-query on the next render tick, bypassing the
158 /// normal TTL. Keeps the current value visible while the background git query
159 /// is running.
160 pub(super) fn refresh_now(app: &mut App, now: Instant) {
161 if let Ok(mut cell) = app.workspace_context_cell.lock() {
162 *cell = None;
163 }
164 app.workspace_context_refreshed_at = None;
165 refresh_inner(app, now, true, true);
166 }
167
168 pub(crate) fn branch_from_context(context: &str) -> Option<&str> {
169 let (branch, _) = context.rsplit_once(" | ")?;
170 (!branch.is_empty()).then_some(branch)
171 }
172
173 /// Concise, factual workspace identity for the footer status chip (#3188).
174 ///
175 /// The identity is sourced from workspace/git detection only — never from
176 /// model narration or config text. `name` is the workspace basename, `branch`
177 /// is `Some` only when the workspace is a git repository (carrying the cached
178 /// `"detached:<hash>"` form for detached HEAD), and `is_git` distinguishes a
179 /// real repo from a plain directory so the footer can show an explicit
180 /// non-repo state instead of an empty `Repo:` label.
181 #[derive(Debug, Clone, PartialEq, Eq)]
182 pub(crate) struct WorkspaceIdentity {
183 pub name: String,
184 pub branch: Option<String>,
185 pub is_git: bool,
186 }
187
188 /// Basename used as the workspace identity. Falls back to a stable sentinel
189 /// when the path has no final component (filesystem root). Derived purely
190 /// from the workspace path, so it never spawns git on the render path.
191 pub(crate) fn workspace_basename(workspace: &Path) -> String {
192 workspace
193 .file_name()
194 .and_then(|s| s.to_str())
195 .filter(|s| !s.is_empty())
196 .unwrap_or("(root)")
197 .to_string()
198 }
199
200 /// Resolve the footer identity from the workspace path plus the cached
201 /// "branch | status" context string. `context` is `None` when the workspace
202 /// is not a git repository (or git is unavailable), which we surface as an
203 /// explicit non-repo state rather than hiding the chip.
204 pub(crate) fn identity_from_context(workspace: &Path, context: Option<&str>) -> WorkspaceIdentity {
205 let branch = context.and_then(branch_from_context).map(str::to_string);
206 WorkspaceIdentity {
207 name: workspace_basename(workspace),
208 is_git: branch.is_some(),
209 branch,
210 }
211 }
212
213 /// Hard display-column cap for the opt-in `workspace` / `git_branch`
214 /// metrics-line chips (#6112): the only status items whose value is
215 /// arbitrary-length text, so they are the ones that could reflow the row.
216 /// The full path stays in `/status` and the empty-state caption.
217 pub(crate) const STATUS_CHIP_MAX_WIDTH: usize = 24;
218
219 /// Left-truncate `text` to `max_width` display columns, keeping the tail —
220 /// the discriminating part of a directory name or branch — and marking the
221 /// cut with a leading `…`. Unicode-safe: widths come from `unicode_width`
222 /// and the cut never splits a `char`.
223 pub(crate) fn truncate_left(text: &str, max_width: usize) -> String {
224 use unicode_segmentation::UnicodeSegmentation;
225 use unicode_width::UnicodeWidthStr;
226 if max_width == 0 {
227 return String::new();
228 }
229 let text: String = text.chars().filter(|ch| !ch.is_control()).collect();
230 if text.width() <= max_width {
231 return text;
232 }
233 let mut width = 1; // ellipsis
234 let mut start = text.len();
235 for (index, grapheme) in text.grapheme_indices(true).rev() {
236 let next = width + grapheme.width();
237 if next > max_width {
238 break;
239 }
240 width = next;
241 start = index;
242 }
243 format!("…{}", &text[start..])
244 }
245
246 /// Linked worktrees often repeat a repository leaf name. Include their parent
247 /// directory as a disambiguator, without reading the filesystem during draw.
248 pub(crate) fn status_workspace_name(workspace: &Path, is_linked_worktree: bool) -> String {
249 let leaf = workspace_basename(workspace);
250 if is_linked_worktree && let Some(parent) = workspace.parent().and_then(Path::file_name) {
251 return format!("{}/{leaf}", parent.to_string_lossy());
252 }
253 leaf
254 }
255
256 #[cfg(test)]
257 fn run_git(workspace: &Path, args: &[&str]) -> std::io::Result<String> {
258 let output = Git::output(args, workspace)?;
259 if !output.status.success() {
260 return Err(std::io::Error::other("git command failed"));
261 }
262 Ok(String::from_utf8_lossy(&output.stdout).to_string())
263 }
264
265 #[cfg(test)]
266 mod tests {
267 use super::*;
268
269 #[test]
270 fn memory_size_hint_is_cached_off_the_render_path() {
271 // #3908: the Session sidebar rendered this by stat-ing the memory file
272 // inside the draw closure, once per frame. The stat now happens here,
273 // on the workspace-context TTL, so the sidebar reads a plain String.
274 let dir = tempfile::tempdir().expect("temp dir");
275 let memory = dir.path().join("MEMORY.md");
276 std::fs::write(&memory, vec![b'x'; 2048]).unwrap();
277
278 assert_eq!(memory_size_hint(&memory), "2.0 KB");
279
280 std::fs::remove_file(&memory).unwrap();
281 assert_eq!(memory_size_hint(&memory), "\u{2014}");
282 }
283
284 #[test]
285 fn memory_size_formats_match_the_sidebar_original() {
286 assert_eq!(format_size(512), "512 B");
287 assert_eq!(format_size(1024), "1.0 KB");
288 assert_eq!(format_size(1024 * 1024), "1.0 MB");
289 }
290
291 #[test]
292 fn workspace_basename_handles_root_path() {
293 assert_eq!(workspace_basename(Path::new("/")), "(root)");
294 assert_eq!(workspace_basename(Path::new("/a/b/project")), "project");
295 }
296
297 #[test]
298 fn truncate_left_keeps_the_tail_within_budget() {
299 // Short values pass through untouched.
300 assert_eq!(truncate_left("codewhale", 24), "codewhale");
301 // Exactly at the cap is not a truncation.
302 assert_eq!(truncate_left("abcdefghij", 10), "abcdefghij");
303 // Long values keep the tail behind a one-column ellipsis.
304 let cut = truncate_left("very-long-workspace-name", 10);
305 assert_eq!(cut, "\u{2026}pace-name");
306 assert_eq!(
307 unicode_width::UnicodeWidthStr::width(cut.as_str()),
308 10,
309 "{cut}"
310 );
311 // Wide chars count by display columns and are never split.
312 let cut = truncate_left("workspace-作業ディレクトリ", 10);
313 assert!(cut.starts_with('\u{2026}'), "{cut}");
314 assert!(
315 unicode_width::UnicodeWidthStr::width(cut.as_str()) <= 10,
316 "{cut}"
317 );
318 }
319 #[test]
320 fn workspace_chip_respects_zero_width_graphemes_and_terminal_controls() {
321 use unicode_width::UnicodeWidthStr;
322 for text in ["e\u{301}-family-👨‍👩‍👧‍👦", "作業-directory", "\x1b[31mname\n"]
323 {
324 for budget in 0..25 {
325 let result = truncate_left(text, budget);
326 assert!(result.width() <= budget, "{result:?} exceeds {budget}");
327 assert!(!result.chars().any(char::is_control));
328 }
329 }
330 assert_eq!(truncate_left("prefix-👨‍👩‍👧‍👦", 3), "…👨‍👩‍👧‍👦");
331 assert_eq!(
332 status_workspace_name(Path::new("/trees/feature/codewhale"), true),
333 "feature/codewhale"
334 );
335 assert_eq!(
336 status_workspace_name(Path::new("/trees/feature/codewhale"), false),
337 "codewhale"
338 );
339 }
340
341 #[test]
342 fn workspace_snapshot_detects_linked_worktrees_and_detached_heads() {
343 let root = tempfile::tempdir().unwrap();
344 let main = root.path().join("main");
345 let linked = root.path().join("feature");
346 std::fs::create_dir(&main).unwrap();
347 run_git(&main, &["init", "--initial-branch=main"]).unwrap();
348 run_git(
349 &main,
350 &[
351 "-c",
352 "user.name=Fixture",
353 "-c",
354 "user.email=fixture@example.invalid",
355 "-c",
356 "commit.gpgsign=false",
357 "commit",
358 "--allow-empty",
359 "-m",
360 "fixture",
361 ],
362 )
363 .unwrap();
364 run_git(
365 &main,
366 &["worktree", "add", "-b", "feature", linked.to_str().unwrap()],
367 )
368 .unwrap();
369 let ordinary = collect_snapshot(&main, false);
370 assert!(!ordinary.is_linked_worktree);
371 let linked_snapshot = collect_snapshot(&linked, false);
372 assert!(linked_snapshot.is_linked_worktree);
373 assert_eq!(
374 linked_snapshot
375 .context
376 .as_deref()
377 .and_then(branch_from_context),
378 Some("feature")
379 );
380 run_git(&linked, &["checkout", "--detach"]).unwrap();
381 // The badge reads the shared probe's cache; a checkout forces it.
382 codewhale_engine::git_status::force_refresh(&linked);
383 let detached = collect_snapshot(&linked, false);
384 assert!(detached.is_linked_worktree);
385 assert!(
386 detached
387 .context
388 .as_deref()
389 .and_then(branch_from_context)
390 .unwrap()
391 .starts_with("detached:")
392 );
393 let outside = root.path().join("outside");
394 std::fs::create_dir(&outside).unwrap();
395 let missing = collect_snapshot(&outside, false);
396 assert!(missing.context.is_none());
397 assert!(!missing.is_linked_worktree);
398 }
399 }
400
400 lines RUST