agentmux_srv/server/editor_handlers/
scratch.rs1use std::io;
9use std::path::{Path, PathBuf};
10
11use super::{editor_may_change, in_a_distro_home, scratch_session_token};
12use crate::backend::base::expand_home_dir_safe;
13use crate::backend::rpc_types::{CreateScratchFileReq, CreateScratchFileResult, MoveScratchFileReq, MoveScratchFileResult};
14
15const THIRTY_DAYS_MS: u64 = 30 * 24 * 60 * 60 * 1000;
16
17pub(super) struct Candidate {
19 created_at: u64,
20 pub(super) scratch_id: String,
21 display_name: String,
22}
23
24fn scratch_dir_of(home: &Path) -> PathBuf {
25 home.join(".agentmux").join("cache").join("scratch")
26}
27
28pub(super) fn create_scratch_file(home: &Path, cmd: CreateScratchFileReq) -> Result<CreateScratchFileResult, String> {
30 let scratch_dir = scratch_dir_of(home);
31 std::fs::create_dir_all(&scratch_dir).map_err(|e| format!("createscratchfile: create dir: {e}"))?;
32 let now_ms = agentmux_common::time::now_ms_u64();
33 let session_token = scratch_session_token();
34
35 let candidates = scan_candidates(&scratch_dir, cmd.exclude_scratch_ids.as_deref(), now_ms);
36 if let Some((scratch_id, display_name)) = claim_most_recent(&scratch_dir, candidates, session_token) {
37 let file_path = scratch_dir.join(format!("{}.md", scratch_id));
38 return Ok(CreateScratchFileResult { scratch_id, file_path: file_path.to_string_lossy().into_owned(), display_name });
39 }
40 mint_scratch(&scratch_dir, cmd.display_name, now_ms, session_token)
41}
42
43pub(super) fn scan_candidates(scratch_dir: &Path, exclude: Option<&[String]>, now_ms: u64) -> Vec<Candidate> {
46 let mut candidates = Vec::new();
47 let Ok(entries) = std::fs::read_dir(scratch_dir) else { return candidates };
48 for entry in entries.flatten() {
49 let meta_path = entry.path();
50 let fname = meta_path.file_name().and_then(|f| f.to_str()).unwrap_or("").to_string();
51 if !fname.ends_with(".md.meta") {
52 continue;
53 }
54 let Ok(content) = std::fs::read_to_string(&meta_path) else { continue };
55 let Ok(meta_json) = serde_json::from_str::<serde_json::Value>(&content) else { continue };
56 if meta_json.get("saved_to").map_or(false, |v| !v.is_null()) {
57 continue;
58 }
59 let created_at = meta_json.get("created_at").and_then(|v| v.as_u64()).unwrap_or(0);
60 let sid = meta_json.get("scratch_id").and_then(|v| v.as_str()).unwrap_or("").to_string();
61 if created_at == 0 || sid.is_empty() {
62 continue;
63 }
64 if exclude.map_or(false, |ex| ex.iter().any(|e| e == &sid)) {
65 continue;
66 }
67 if now_ms.saturating_sub(created_at) > THIRTY_DAYS_MS {
68 let _ = std::fs::remove_file(scratch_dir.join(format!("{}.md", sid)));
70 let _ = std::fs::remove_file(&meta_path);
71 let _ = std::fs::remove_file(scratch_dir.join(format!("{}.md.claim", sid)));
72 continue;
73 }
74 let display_name = meta_json.get("display_name").and_then(|v| v.as_str()).unwrap_or("Untitled").to_string();
75 candidates.push(Candidate { created_at, scratch_id: sid, display_name });
76 }
77 candidates
78}
79
80pub(super) fn claim_most_recent(scratch_dir: &Path, mut candidates: Vec<Candidate>, session_token: &str) -> Option<(String, String)> {
84 candidates.sort_by(|a, b| b.created_at.cmp(&a.created_at));
85 for Candidate { scratch_id: sid, display_name: dname, .. } in &candidates {
86 let claim_path = scratch_dir.join(format!("{}.md.claim", sid));
87 if claim_path.exists() {
89 if let Ok(tok) = std::fs::read_to_string(&claim_path) {
90 if tok.trim() == session_token {
91 continue;
93 }
94 }
95 let _ = std::fs::remove_file(&claim_path);
97 }
98 match std::fs::OpenOptions::new().write(true).create_new(true).open(&claim_path) {
101 Ok(mut f) => {
102 use std::io::Write as _;
103 let _ = f.write_all(session_token.as_bytes());
104 if scratch_dir.join(format!("{}.md", sid)).exists() {
105 return Some((sid.clone(), dname.clone()));
106 }
107 let _ = std::fs::remove_file(&claim_path);
109 }
110 Err(_) => continue, }
112 }
113 None
114}
115
116fn mint_scratch(
118 scratch_dir: &Path,
119 display_name: Option<String>,
120 now_ms: u64,
121 session_token: &str,
122) -> Result<CreateScratchFileResult, String> {
123 let scratch_id = uuid::Uuid::new_v4().to_string();
124 let display_name = display_name.unwrap_or_else(|| "Untitled".to_string());
125 let file_path = scratch_dir.join(format!("{}.md", scratch_id));
126 std::fs::write(&file_path, "").map_err(|e| format!("createscratchfile: {e}"))?;
127 let meta = serde_json::json!({
128 "display_name": display_name,
129 "scratch_id": scratch_id,
130 "created_at": now_ms,
131 });
132 let meta_path = scratch_dir.join(format!("{}.md.meta", scratch_id));
133 std::fs::write(&meta_path, meta.to_string()).map_err(|e| format!("createscratchfile: meta: {e}"))?;
134 let claim_path = scratch_dir.join(format!("{}.md.claim", scratch_id));
135 let _ = std::fs::write(&claim_path, session_token);
136 Ok(CreateScratchFileResult { scratch_id, file_path: file_path.to_string_lossy().into_owned(), display_name })
137}
138
139const OUTSIDE_HOME: &str = "The Editor saves only inside your home folder.";
141
142pub(super) fn save_error(err: &io::Error, name: &str) -> String {
144 match err.kind() {
145 io::ErrorKind::AlreadyExists => crate::backend::fs_ops::exists_message(name),
146 io::ErrorKind::PermissionDenied => "You don't have permission to save there.".to_string(),
147 io::ErrorKind::StorageFull | io::ErrorKind::QuotaExceeded => "There isn't enough space to save it there.".to_string(),
148 _ => format!("Couldn't save it there: {err}"),
149 }
150}
151
152pub(super) fn copy_to_new_file(from: &mut dyn io::Read, dest: &Path) -> io::Result<()> {
155 let mut out = std::fs::OpenOptions::new().write(true).create_new(true).open(dest)?;
156 let written = io::copy(from, &mut out).and_then(|_| out.sync_all());
157 drop(out);
158 if written.is_err() {
159 let _ = std::fs::remove_file(dest);
160 }
161 written
162}
163
164pub(super) fn move_scratch_file(home: &Path, cmd: &MoveScratchFileReq) -> Result<MoveScratchFileResult, String> {
167 let canonical_home = home.canonicalize().map_err(|e| format!("movescratchfile: home: {e}"))?;
168 if cmd.scratch_id.contains('/') || cmd.scratch_id.contains('\\') || cmd.scratch_id.contains("..") {
170 return Err("movescratchfile: invalid scratch_id".to_string());
171 }
172 let scratch_dir = scratch_dir_of(home);
173 let scratch_path = scratch_dir.join(format!("{}.md", cmd.scratch_id));
174 if !scratch_path.exists() {
175 return Err("movescratchfile: scratch file not found".to_string());
176 }
177 let expanded_dest = expand_home_dir_safe(&cmd.destination_path);
178 let dest_path = expanded_dest.as_path();
179
180 if !dest_path.starts_with(home) && !in_a_distro_home(dest_path) {
183 return Err(OUTSIDE_HOME.to_string());
184 }
185 if dest_path.components().any(|c| c == std::path::Component::ParentDir) {
189 return Err("A path can't contain “..”.".to_string());
190 }
191 let name = dest_path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
194 crate::backend::fs_ops::validate_new_name(&name)?;
195 if std::fs::symlink_metadata(dest_path).is_ok() {
198 return Err(crate::backend::fs_ops::exists_message(&name));
199 }
200 if let Some(parent) = dest_path.parent() {
201 std::fs::create_dir_all(parent).map_err(|e| save_error(&e, &name))?;
202 }
203 let canonical_dest = dest_path
205 .parent()
206 .and_then(|p| p.canonicalize().ok())
207 .map(|p| p.join(dest_path.file_name().unwrap_or_default()))
208 .ok_or_else(|| "movescratchfile: invalid destination path".to_string())?;
209 if !editor_may_change(&canonical_dest, &canonical_home) {
211 return Err(OUTSIDE_HOME.to_string());
212 }
213 let mut scratch = std::fs::File::open(&scratch_path).map_err(|e| save_error(&e, &name))?;
216 copy_to_new_file(&mut scratch, &canonical_dest).map_err(|e| save_error(&e, &name))?;
217 drop(scratch);
218 std::fs::remove_file(&scratch_path).map_err(|e| format!("movescratchfile: remove scratch: {e}"))?;
219 let _ = std::fs::remove_file(scratch_dir.join(format!("{}.md.meta", cmd.scratch_id)));
221 let _ = std::fs::remove_file(scratch_dir.join(format!("{}.md.claim", cmd.scratch_id)));
222 Ok(MoveScratchFileResult { file_path: canonical_dest.to_string_lossy().into_owned() })
223}