1use std::fmt;
10use std::path::{Path, PathBuf};
11
12#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct SessionCwdIssue {
15 pub session_file: Option<PathBuf>,
17 pub session_cwd: PathBuf,
19 pub fallback_cwd: PathBuf,
21}
22
23pub fn get_missing_session_cwd_issue(
28 session_file: Option<&Path>,
29 session_cwd: &Path,
30 fallback_cwd: &Path,
31) -> Option<SessionCwdIssue> {
32 let session_file = session_file?;
33 if session_cwd.as_os_str().is_empty() {
34 return None;
35 }
36 if session_cwd.is_dir() {
37 return None;
38 }
39 Some(SessionCwdIssue {
40 session_file: Some(session_file.to_path_buf()),
41 session_cwd: session_cwd.to_path_buf(),
42 fallback_cwd: fallback_cwd.to_path_buf(),
43 })
44}
45
46pub fn resolve_session_cwd(session_cwd: &Path) -> Option<PathBuf> {
55 if session_cwd.as_os_str().is_empty() {
56 return None;
57 }
58 session_cwd.is_dir().then(|| session_cwd.to_path_buf())
59}
60
61pub fn missing_session_cwd_note(recorded: &Path, fallback: &Path) -> String {
63 format!(
64 "This session's directory ({}) no longer exists; continuing in {}.",
65 recorded.display(),
66 fallback.display()
67 )
68}
69
70pub(crate) fn is_same_directory(left: &Path, right: &Path) -> bool {
80 let canonical = |path: &Path| std::fs::canonicalize(path).ok();
81 match (canonical(left), canonical(right)) {
82 (Some(left), Some(right)) => paths_equal(&left, &right),
83 _ => paths_equal(left, right),
84 }
85}
86
87fn paths_equal(left: &Path, right: &Path) -> bool {
88 if cfg!(windows) {
89 left.to_string_lossy()
90 .replace('/', "\\")
91 .eq_ignore_ascii_case(&right.to_string_lossy().replace('/', "\\"))
92 } else {
93 left == right
94 }
95}
96
97pub(crate) fn moved_session_cwd_note(launch: &Path, adopted: &Path) -> Option<String> {
102 if is_same_directory(launch, adopted) {
103 return None;
104 }
105 Some(adopted_session_cwd_note(launch, adopted))
106}
107
108pub fn adopted_session_cwd_note(launch: &Path, adopted: &Path) -> String {
115 format!(
116 "Continuing this session in {}, where it was created (launched from {}).",
117 adopted.display(),
118 launch.display()
119 )
120}
121
122pub fn untrusted_session_cwd_note(recorded: &Path) -> String {
126 format!(
127 "This session's directory ({}) is not trusted, so its project settings, \
128 skills, and context files are not loaded. Run /trust yes (or restart \
129 with --approve) to allow them.",
130 recorded.display()
131 )
132}
133
134pub fn format_missing_session_cwd_error(issue: &SessionCwdIssue) -> String {
136 let session_file = issue
137 .session_file
138 .as_ref()
139 .map(|p| format!("\nSession file: {}", p.display()))
140 .unwrap_or_default();
141 format!(
142 "Stored session working directory does not exist: {}{}\nCurrent working directory: {}",
143 issue.session_cwd.display(),
144 session_file,
145 issue.fallback_cwd.display()
146 )
147}
148
149pub fn format_missing_session_cwd_prompt(issue: &SessionCwdIssue) -> String {
152 format!(
153 "cwd from session file does not exist\n{}\n\ncontinue in current cwd\n{}",
154 issue.session_cwd.display(),
155 issue.fallback_cwd.display()
156 )
157}
158
159#[derive(Debug, Clone, PartialEq, Eq)]
162pub struct MissingSessionCwdError {
163 pub issue: SessionCwdIssue,
164}
165
166impl fmt::Display for MissingSessionCwdError {
167 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168 f.write_str(&format_missing_session_cwd_error(&self.issue))
169 }
170}
171
172impl std::error::Error for MissingSessionCwdError {}
173
174pub fn assert_session_cwd_exists(
176 session_file: Option<&Path>,
177 session_cwd: &Path,
178 fallback_cwd: &Path,
179) -> Result<(), MissingSessionCwdError> {
180 match get_missing_session_cwd_issue(session_file, session_cwd, fallback_cwd) {
181 Some(issue) => Err(MissingSessionCwdError { issue }),
182 None => Ok(()),
183 }
184}
185
186#[cfg(test)]
187mod tests {
188 use super::*;
189 use std::path::PathBuf;
190
191 #[test]
192 fn no_session_file_is_ok() {
193 assert!(
194 get_missing_session_cwd_issue(None, Path::new("/whatever"), Path::new("/cwd"))
195 .is_none()
196 );
197 }
198
199 #[test]
200 fn existing_dir_is_ok() {
201 let dir = std::env::temp_dir();
202 assert!(get_missing_session_cwd_issue(Some(Path::new("/s.jsonl")), &dir, &dir).is_none());
203 }
204
205 #[test]
206 fn empty_stored_cwd_is_ok() {
207 assert!(get_missing_session_cwd_issue(
208 Some(Path::new("/s.jsonl")),
209 Path::new(""),
210 Path::new("/cwd")
211 )
212 .is_none());
213 }
214
215 #[test]
216 fn missing_dir_reports_issue() {
217 let missing = PathBuf::from("/definitely/not/here/xyzzy-1234");
218 let issue =
219 get_missing_session_cwd_issue(Some(Path::new("/s.jsonl")), &missing, Path::new("/cwd"))
220 .expect("issue");
221 assert_eq!(issue.session_cwd, missing);
222 assert!(format_missing_session_cwd_error(&issue).contains("does not exist"));
223 assert!(format_missing_session_cwd_prompt(&issue).contains("continue in current cwd"));
224 assert!(assert_session_cwd_exists(
225 Some(Path::new("/s.jsonl")),
226 &missing,
227 Path::new("/cwd")
228 )
229 .is_err());
230 }
231
232 #[test]
233 fn resolve_session_cwd_accepts_only_existing_directories() {
234 let dir = tempfile::tempdir().unwrap();
235 assert_eq!(
236 resolve_session_cwd(dir.path()),
237 Some(dir.path().to_path_buf())
238 );
239 assert_eq!(resolve_session_cwd(Path::new("")), None);
240 assert_eq!(
241 resolve_session_cwd(Path::new("/definitely/not/here/xyzzy-4321")),
242 None
243 );
244
245 let file = dir.path().join("not-a-dir");
248 std::fs::write(&file, b"x").unwrap();
249 assert_eq!(resolve_session_cwd(&file), None);
250 assert!(
251 get_missing_session_cwd_issue(Some(Path::new("/s.jsonl")), &file, dir.path()).is_some(),
252 "a file at the recorded path counts as a missing cwd"
253 );
254 }
255
256 #[test]
257 fn missing_and_untrusted_notes_name_the_directories() {
258 let note = missing_session_cwd_note(Path::new("/gone/project"), Path::new("/here"));
259 assert!(note.contains("/gone/project"), "{note}");
260 assert!(note.contains("/here"), "{note}");
261 assert!(note.contains("no longer exists"), "{note}");
262
263 let note = untrusted_session_cwd_note(Path::new("/gone/project"));
264 assert!(note.contains("/gone/project"), "{note}");
265 assert!(note.contains("/trust yes"), "{note}");
266 }
267
268 #[test]
273 fn adopting_a_directory_is_announced_with_both_paths() {
274 let note =
275 adopted_session_cwd_note(Path::new("/launch/project"), Path::new("/other/project"));
276 assert!(note.contains("/other/project"), "{note}");
277 assert!(note.contains("/launch/project"), "{note}");
278 assert!(note.contains("where it was created"), "{note}");
279 }
280
281 #[test]
286 fn adopting_the_launch_directory_is_silent() {
287 let dir = tempfile::tempdir().unwrap();
288 assert_eq!(moved_session_cwd_note(dir.path(), dir.path()), None);
289
290 let spelled = dir.path().join("sub").join("..");
294 std::fs::create_dir_all(dir.path().join("sub")).unwrap();
295 assert_eq!(
296 moved_session_cwd_note(dir.path(), &spelled),
297 None,
298 "{} vs {}",
299 dir.path().display(),
300 spelled.display()
301 );
302 let mut trailing = dir.path().as_os_str().to_os_string();
303 trailing.push(std::path::MAIN_SEPARATOR_STR);
304 assert_eq!(
305 moved_session_cwd_note(dir.path(), Path::new(&trailing)),
306 None
307 );
308 let elsewhere = tempfile::tempdir().unwrap();
309 let note = moved_session_cwd_note(dir.path(), elsewhere.path())
310 .expect("a genuinely different directory must still be announced");
311 assert!(note.contains("where it was created"), "{note}");
312 }
313}