Skip to main content

agentmux_srv/server/editor_handlers/
scratch.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The scratch file service (`createscratchfile`, `movescratchfile`), moved out of `register_editor_handlers`
5//! unchanged as named functions. Spec: docs/specs/SPEC_EDITOR_WIDGET_DEFAULT_UX_2026_06_14.md. Each takes the
6//! user's home folder as a parameter, so a test can point it at a temp dir.
7
8use 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
17/// A saved-nowhere scratch buffer that could be handed out again.
18pub(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
28/// Creates a scratch buffer file in `~/.agentmux/cache/scratch/`, or hands out the most recent unclaimed one.
29pub(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
43/// Phase 1: scan the `.md.meta` files, collecting candidates (not saved, not expired, not in
44/// `exclude_scratch_ids`) and pruning expired pairs.
45pub(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            // Prune the expired pair (all three files: .md, .md.meta, .md.claim).
69            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
80/// Phase 2: try to atomically claim the most recent candidate. Claim files stop two concurrent calls returning
81/// the same backing file to different panes. Each claim file stores the per-process session token; a claim from
82/// a previous process (crash/restart) has a different token and is cleared so recovery works.
83pub(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        // Evict stale claims from a previous process session.
88        if claim_path.exists() {
89            if let Ok(tok) = std::fs::read_to_string(&claim_path) {
90                if tok.trim() == session_token {
91                    // A valid live claim: another concurrent call already owns this.
92                    continue;
93                }
94            }
95            // A stale claim (different session): remove it so this can be reclaimed.
96            let _ = std::fs::remove_file(&claim_path);
97        }
98        // Try to exclusively create the claim file. If another concurrent call wins the race it will have
99        // already created it, so this one is skipped.
100        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                // The backing file is gone (deleted externally): release the claim.
108                let _ = std::fs::remove_file(&claim_path);
109            }
110            Err(_) => continue, // A concurrent call claimed this one first.
111        }
112    }
113    None
114}
115
116/// No reusable candidate: a fresh UUID pair, claimed so subsequent calls don't immediately reuse it.
117fn 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
139/// The refusal for a destination the Editor may not write: the same limit as its saves.
140const OUTSIDE_HOME: &str = "The Editor saves only inside your home folder.";
141
142/// A failed save as a sentence for the person.
143pub(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
152/// Writes all of `from` to a new file at `dest`. The file is created exclusively, so one that appeared since
153/// any earlier check is never replaced; a write that fails part-way leaves nothing behind.
154pub(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
164/// Promotes a scratch buffer to a real user-chosen path (Save As, or a name typed into its tab). The errors
165/// are sentences, shown to the person as they are.
166pub(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    // The scratch_id has no path components.
169    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    // A coarse home-boundary check before any filesystem mutation, on the unexpanded path because the
181    // destination may not exist yet (canonicalize fails on non-existent paths).
182    if !dest_path.starts_with(home) && !in_a_distro_home(dest_path) {
183        return Err(OUTSIDE_HOME.to_string());
184    }
185    // Reject ".." components before create_dir_all: the coarse starts_with check is purely lexical and passes
186    // paths like ~/foo/../../../tmp/evil because the prefix matches, but create_dir_all would then materialize
187    // directories outside the home boundary before the canonical check fires.
188    if dest_path.components().any(|c| c == std::path::Component::ParentDir) {
189        return Err("A path can't contain “..”.".to_string());
190    }
191    // The file's own name follows the rules a rename does (Windows' reserved names and characters, a
192    // trailing dot or space), so the file saved is the file named.
193    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    // An existing destination is refused before any folder is made. `symlink_metadata`, so a dangling link
196    // counts as taken; the exclusive create below is what holds if something appears in between.
197    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    // Canonicalize the parent (now guaranteed to exist) and append the filename.
204    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    // The fine-grained home-boundary check, with canonical paths.
210    if !editor_may_change(&canonical_dest, &canonical_home) {
211        return Err(OUTSIDE_HOME.to_string());
212    }
213    // Copy, then remove the scratch source (a cross-device-safe move): the buffer's file goes only once the
214    // real one is whole.
215    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    // Clean up the .meta sidecar and the claim file.
220    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}