Skip to main content

rpi_cli/
session_cwd.rs

1//! Stored-session working-directory recovery.
2//!
3//! Port of the upstream `packages/coding-agent/src/core/session-cwd.ts`. A
4//! session file records the cwd it was created in; when that directory has
5//! since been deleted, restoring the session must either fall back to the
6//! current cwd or fail with a clear, actionable message instead of silently
7//! operating in a non-existent directory.
8
9use std::fmt;
10use std::path::{Path, PathBuf};
11
12/// A session whose recorded working directory no longer exists on disk.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct SessionCwdIssue {
15    /// The session file that recorded the missing cwd, when known.
16    pub session_file: Option<PathBuf>,
17    /// The cwd stored in the session file (does not exist).
18    pub session_cwd: PathBuf,
19    /// The cwd the process is currently running in (the fallback).
20    pub fallback_cwd: PathBuf,
21}
22
23/// Detect a missing session cwd. Returns `None` when there is no session file,
24/// the stored cwd is empty, or the stored cwd is still a directory. A **file**
25/// at the recorded path does not pass: every tool resolves relative paths
26/// against the cwd, so adopting a non-directory would break them all.
27pub 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
46/// The working directory a restored session should adopt.
47///
48/// `Some` when the session recorded a directory that still exists — restoring a
49/// conversation must return the agent to where that conversation happened,
50/// because every tool resolves relative paths against the run's cwd. `None` when
51/// the record is empty or the path is gone (or is a file, not a directory); the
52/// caller then falls back to the launch cwd and tells the user via
53/// [`missing_session_cwd_note`].
54pub 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
61/// The one-line transcript note for a session whose recorded directory is gone.
62pub 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
70/// Whether two paths name the same directory.
71///
72/// Deciding whether a restore "moved" the run cannot be a textual `==`: the
73/// launch cwd comes from `current_dir` while the recorded one was written by an
74/// earlier run, and the two disagree in spelling for the same directory
75/// (symlinked homes, `..` segments, trailing separators, Windows case). Compare
76/// canonical forms instead, falling back to the addressed paths when either
77/// side cannot be canonicalized (a path that is not there has no identity to
78/// resolve).
79pub(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
97/// Returns `None` when the recorded directory IS the launch directory: `-c` in
98/// the project the session was created in adopts nothing, and printing the
99/// adoption note would be a false alarm on every ordinary resume. The formatter
100/// itself stays a plain `String` so the public API does not change.
101pub(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
108/// The one-line transcript note for a session adopted from another directory.
109///
110/// Restoring a conversation moves the whole run — tools, system prompt, context
111/// files, extensions — to the recorded directory, so the user has to hear about
112/// it: a `rpi -c` launched in one project must not silently start editing files
113/// in another. Mirrors pi's `Session found in different project: <cwd>` notice.
114pub 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
122/// The one-line transcript note for a session restored into an untrusted
123/// directory. Trust is re-resolved against the adopted directory, so project
124/// settings, skills, and context files from it stay off until the user allows.
125pub 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
134/// One-line error message (native `formatMissingSessionCwdError`).
135pub 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
149/// Short prompt shown by the startup selector (native
150/// `formatMissingSessionCwdPrompt`).
151pub 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/// Error raised when a session's cwd cannot be resolved and no override was
160/// supplied.
161#[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
174/// Fail unless the session cwd exists (native `assertSessionCwdExists`).
175pub 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        // A FILE at the recorded path must not be adopted: every tool resolves
246        // relative paths against the cwd, and a file is not a directory.
247        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    /// Adopting another project's directory is a behaviour change the user must
269    /// see: the tools, context files, and extensions all switch projects. A
270    /// silent adoption would look like `rpi -c` started editing files in the
271    /// launch directory while it is actually working somewhere else.
272    #[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    /// `-c` in the directory the session was created in adopts that same
282    /// directory. There is no behaviour change to report, and announcing one
283    /// would fire on every ordinary resume (rpi-web restores repeatedly, so it
284    /// repeated the line for every restored session).
285    #[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        // The same directory reached by a different spelling is still the
291        // launch directory: the recorded cwd was written by an earlier run, so
292        // a textual comparison is not enough (trailing separator, `.`, `..`).
293        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}