chore: baseline md-preview 1.4.2 + agent workspace

This commit is contained in:
2026-10-21 16:06:27 +08:00
commit f63aff47a8
30 changed files with 15085 additions and 0 deletions

207
src/instance.rs Normal file
View File

@@ -0,0 +1,207 @@
//! Local launch forwarding. The OS file lock owns the endpoint lifetime; a crashed
//! process releases it automatically, so stale endpoint data cannot block restart.
use serde::{Deserialize, Serialize};
use std::fs::{File, OpenOptions};
use std::hash::{BuildHasher, Hasher};
use std::io::{self, Read, Write};
use std::net::{Ipv4Addr, SocketAddr, TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::time::Duration;
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct Launch {
pub paths: Vec<PathBuf>,
pub edit: bool,
}
#[derive(Serialize, Deserialize)]
struct Endpoint {
port: u16,
token: String,
}
#[derive(Serialize, Deserialize)]
struct Request {
token: String,
launch: Launch,
}
pub struct Primary {
_lock: File,
listener: TcpListener,
endpoint: Endpoint,
}
pub fn acquire(directory: &Path, launch: &Launch) -> io::Result<Option<Primary>> {
std::fs::create_dir_all(directory)?;
let mut options = OpenOptions::new();
options.read(true).write(true).create(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let lock = options.open(directory.join("instance.lock"))?;
let endpoint_path = directory.join("instance.json");
match lock.try_lock() {
Ok(()) => {
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))?;
let token = (0..2)
.map(|_| {
format!(
"{:016x}",
std::collections::hash_map::RandomState::new()
.build_hasher()
.finish()
)
})
.collect::<String>();
let endpoint = Endpoint {
port: listener.local_addr()?.port(),
token,
};
// Windows file locks can exclude reads, so publish outside the locked file.
let mut endpoint_file = options.truncate(true).open(&endpoint_path)?;
serde_json::to_writer(&mut endpoint_file, &endpoint)?;
endpoint_file.flush()?;
Ok(Some(Primary {
_lock: lock,
listener,
endpoint,
}))
}
Err(std::fs::TryLockError::WouldBlock) => {
// The winner may still be publishing its endpoint after taking the lock.
let mut last_error = io::Error::other("Running instance is not ready");
for _ in 0..30 {
let endpoint = File::open(&endpoint_path).and_then(|file| {
serde_json::from_reader::<_, Endpoint>(file).map_err(io::Error::from)
});
match endpoint.and_then(|endpoint| forward(&endpoint, launch)) {
Ok(()) => return Ok(None),
Err(error) => last_error = error,
}
std::thread::sleep(Duration::from_millis(100));
}
Err(last_error)
}
Err(std::fs::TryLockError::Error(error)) => Err(error),
}
}
fn forward(endpoint: &Endpoint, launch: &Launch) -> io::Result<()> {
let address = SocketAddr::from((Ipv4Addr::LOCALHOST, endpoint.port));
let mut stream = TcpStream::connect_timeout(&address, Duration::from_secs(1))?;
stream.set_read_timeout(Some(Duration::from_secs(3)))?;
stream.set_write_timeout(Some(Duration::from_secs(3)))?;
serde_json::to_writer(
&mut stream,
&serde_json::json!({"token": endpoint.token, "launch": launch}),
)?;
stream.shutdown(std::net::Shutdown::Write)?;
let mut ack = [0];
stream.read_exact(&mut ack)?;
if ack != [1] {
return Err(io::Error::other("Launch was not accepted"));
}
Ok(())
}
impl Primary {
pub fn listen(self, handler: impl Fn(Launch) -> bool + Send + 'static) {
std::thread::spawn(move || {
// Keep the lock alive alongside the listener.
let _lock = self._lock;
for stream in self.listener.incoming() {
let Ok(mut stream) = stream else { break };
let _ = stream.set_read_timeout(Some(Duration::from_secs(1)));
let _ = stream.set_write_timeout(Some(Duration::from_secs(1)));
let request =
serde_json::from_reader::<_, Request>((&mut stream).take(1024 * 1024));
if let Ok(request) = request {
if request.token == self.endpoint.token && handler(request.launch) {
let _ = stream.write_all(&[1]);
}
}
}
});
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn secondary_launch_forwards_paths_and_edit_flag() {
let directory = std::env::temp_dir().join(format!("mdp-instance-{}", std::process::id()));
let launch = Launch {
paths: vec![directory.join("含 空格.md")],
edit: true,
};
let primary = acquire(&directory, &launch).unwrap().unwrap();
let (tx, rx) = std::sync::mpsc::channel();
primary.listen(move |launch| tx.send(launch).is_ok());
assert!(acquire(&directory, &launch).unwrap().is_none());
assert_eq!(rx.recv_timeout(Duration::from_secs(2)).unwrap(), launch);
let empty = Launch {
paths: vec![],
edit: false,
};
assert!(acquire(&directory, &empty).unwrap().is_none());
assert_eq!(rx.recv_timeout(Duration::from_secs(2)).unwrap(), empty);
}
#[test]
fn rejects_foreign_tokens_and_accepts_concurrent_launches() {
let directory =
std::env::temp_dir().join(format!("mdp-instance-concurrent-{}", std::process::id()));
let initial = Launch {
paths: vec![],
edit: false,
};
let primary = acquire(&directory, &initial).unwrap().unwrap();
let foreign = Endpoint {
port: primary.endpoint.port,
token: "wrong-token".to_string(),
};
let (tx, rx) = std::sync::mpsc::channel();
primary.listen(move |launch| tx.send(launch).is_ok());
assert!(forward(&foreign, &initial).is_err());
assert!(rx.try_recv().is_err());
let threads = (0..8)
.map(|index| {
let directory = directory.clone();
std::thread::spawn(move || {
let launch = Launch {
paths: vec![directory.join(format!("{index}.md"))],
edit: false,
};
assert!(acquire(&directory, &launch).unwrap().is_none());
})
})
.collect::<Vec<_>>();
for thread in threads {
thread.join().unwrap();
}
let mut paths = (0..8)
.map(|_| rx.recv_timeout(Duration::from_secs(2)).unwrap().paths[0].clone())
.collect::<Vec<_>>();
paths.sort();
paths.dedup();
assert_eq!(paths.len(), 8);
}
#[test]
fn released_lock_allows_restart_with_stale_endpoint() {
let directory =
std::env::temp_dir().join(format!("mdp-instance-restart-{}", std::process::id()));
let launch = Launch {
paths: vec![],
edit: false,
};
let first = acquire(&directory, &launch).unwrap().unwrap();
drop(first);
assert!(acquire(&directory, &launch).unwrap().is_some());
}
}

4229
src/main.rs Normal file

File diff suppressed because it is too large Load Diff

247
src/session.rs Normal file
View File

@@ -0,0 +1,247 @@
use serde::{Deserialize, Serialize};
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DocumentTab {
pub id: u64,
pub path: PathBuf,
pub dirty: bool,
pub missing: bool,
pub edit_on_open: bool,
}
#[derive(Debug, Default)]
pub struct DocumentSession {
pub tabs: Vec<DocumentTab>,
pub active_id: Option<u64>,
next_id: u64,
}
#[derive(Debug, Deserialize, Serialize)]
struct PersistedSession {
version: u8,
active: Option<usize>,
tabs: Vec<PathBuf>,
}
impl DocumentSession {
pub fn load(path: &Path) -> Self {
let Ok(raw) = fs::read(path) else {
return Self::default();
};
let Ok(saved) = serde_json::from_slice::<PersistedSession>(&raw) else {
return Self::default();
};
if saved.version != 1 {
return Self::default();
}
let mut session = Self::default();
for path in saved.tabs {
session.open(path, false);
}
session.active_id = saved
.active
.and_then(|index| session.tabs.get(index))
.map(|tab| tab.id)
.or_else(|| session.tabs.last().map(|tab| tab.id));
session
}
pub fn open(&mut self, path: PathBuf, edit_on_open: bool) -> u64 {
let path = normalize_path(path);
if let Some(tab) = self.tabs.iter_mut().find(|tab| tab.path == path) {
tab.missing = !tab.path.exists();
tab.edit_on_open |= edit_on_open;
self.active_id = Some(tab.id);
return tab.id;
}
self.next_id += 1;
let id = self.next_id;
self.tabs.push(DocumentTab {
id,
missing: !path.exists(),
path,
dirty: false,
edit_on_open,
});
self.active_id = Some(id);
id
}
pub fn activate(&mut self, id: u64) -> bool {
let Some(tab) = self.tabs.iter_mut().find(|tab| tab.id == id) else {
return false;
};
tab.missing = !tab.path.exists();
self.active_id = Some(id);
true
}
pub fn close(&mut self, id: u64) -> bool {
let Some(index) = self.tabs.iter().position(|tab| tab.id == id) else {
return false;
};
let was_active = self.active_id == Some(id);
self.tabs.remove(index);
if was_active {
self.active_id = self
.tabs
.get(index)
.or_else(|| index.checked_sub(1).and_then(|i| self.tabs.get(i)))
.map(|tab| tab.id);
}
true
}
pub fn save(&self, path: &Path) -> io::Result<()> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
let active = self
.active_id
.and_then(|id| self.tabs.iter().position(|tab| tab.id == id));
let saved = PersistedSession {
version: 1,
active,
tabs: self.tabs.iter().map(|tab| tab.path.clone()).collect(),
};
let body = serde_json::to_vec_pretty(&saved).map_err(io::Error::other)?;
let temporary = path.with_extension("json.tmp");
fs::write(&temporary, body)?;
#[cfg(target_os = "windows")]
if path.exists() {
fs::remove_file(path)?;
}
fs::rename(temporary, path)
}
pub fn active(&self) -> Option<&DocumentTab> {
let id = self.active_id?;
self.tabs.iter().find(|tab| tab.id == id)
}
pub fn active_mut(&mut self) -> Option<&mut DocumentTab> {
let id = self.active_id?;
self.tabs.iter_mut().find(|tab| tab.id == id)
}
pub fn get_mut(&mut self, id: u64) -> Option<&mut DocumentTab> {
self.tabs.iter_mut().find(|tab| tab.id == id)
}
pub fn relocate(&mut self, id: u64, path: PathBuf) -> bool {
let path = normalize_path(path);
if self.tabs.iter().any(|tab| tab.id != id && tab.path == path) {
return false;
}
let Some(tab) = self.get_mut(id) else {
return false;
};
tab.path = path;
tab.missing = !tab.path.exists();
true
}
}
fn normalize_path(path: PathBuf) -> PathBuf {
let absolute = if path.is_absolute() {
path
} else {
std::env::current_dir().unwrap_or_default().join(path)
};
fs::canonicalize(&absolute).unwrap_or_else(|_| {
absolute
.parent()
.and_then(|parent| fs::canonicalize(parent).ok())
.and_then(|parent| absolute.file_name().map(|name| parent.join(name)))
.unwrap_or(absolute)
})
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use std::time::{SystemTime, UNIX_EPOCH};
fn temp_dir(name: &str) -> PathBuf {
let unique = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos();
let dir = std::env::temp_dir().join(format!(
"md-preview-session-{name}-{}-{unique}",
std::process::id()
));
fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn opening_the_same_path_activates_without_duplicate() {
let dir = temp_dir("dedupe");
let file = dir.join("note.md");
fs::write(&file, "# Note").unwrap();
let mut session = DocumentSession::default();
let first = session.open(file.clone(), false);
let second = session.open(file.clone(), true);
assert_eq!(first, second);
assert_eq!(session.tabs.len(), 1);
assert_eq!(session.active_id, Some(first));
assert!(session.tabs[0].edit_on_open);
let _ = fs::remove_dir_all(dir);
}
#[test]
fn closing_active_tab_selects_the_next_neighbor() {
let dir = temp_dir("close");
let mut session = DocumentSession::default();
let first = session.open(dir.join("one.md"), false);
let second = session.open(dir.join("two.md"), false);
let third = session.open(dir.join("three.md"), false);
assert!(session.activate(second));
assert!(session.close(second));
assert_eq!(session.active_id, Some(third));
assert_eq!(
session.tabs.iter().map(|tab| tab.id).collect::<Vec<_>>(),
vec![first, third]
);
let _ = fs::remove_dir_all(dir);
}
#[test]
fn persisted_session_keeps_missing_tabs_and_active_order() {
let dir = temp_dir("roundtrip");
let state_path = dir.join("session.json");
let existing = dir.join("existing.md");
let missing = dir.join("missing.md");
fs::write(&existing, "# Existing").unwrap();
let mut session = DocumentSession::default();
session.open(existing.clone(), false);
session.open(missing.clone(), false);
session.save(&state_path).unwrap();
let restored = DocumentSession::load(&state_path);
assert_eq!(restored.tabs.len(), 2);
assert_eq!(restored.tabs[0].path, fs::canonicalize(existing).unwrap());
assert_eq!(
restored.tabs[1].path,
fs::canonicalize(&dir)
.unwrap()
.join(missing.file_name().unwrap())
);
assert!(!restored.tabs[0].missing);
assert!(restored.tabs[1].missing);
assert_eq!(restored.active_id, restored.tabs.get(1).map(|tab| tab.id));
let _ = fs::remove_dir_all(dir);
}
}