1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
//! Human comment boxes (#367): sticky notes on lines, shared in a session.
//!
//! A note is overlay state, never buffer content: it hangs under a line of a
//! workspace file, carries its author, replies and a resolved flag, and in a
//! `--solo` session replicates to every participant over the collab relay
//! ([`crate::collab::CollabMsg::Note`]). Alone, the same notes are personal
//! sticky notes.
//!
//! Replication merges copies the same way on every peer: every change bumps
//! the note's `rev`, the higher-ranked copy's fields win, replies from both
//! copies are kept, and a deletion is a tombstone (`deleted`) that no older
//! copy can undo.
//!
//! A note remembers the text of its line. Lines inserted or removed above it
//! move that text, and [`Note::place`] finds it again near where it was, so
//! the box follows the code on every participant without tracking edits.
//!
//! The session owner (or a lone croft) keeps the notes in
//! `<cache>/notes/<workspace hash>.json`, so they outlive a disconnect and a
//! restart without writing into the repository.
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Reply {
pub author: String,
pub body: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Note {
/// Unique across participants: the author's name, their process id and
/// a counter.
pub id: String,
/// Workspace-relative path, forward slashes.
pub file: String,
/// 0-based line when last placed.
pub line: usize,
/// That line's text, to find it again after edits above it.
pub anchor: String,
pub author: String,
pub body: String,
#[serde(default)]
pub replies: Vec<Reply>,
#[serde(default)]
pub resolved: bool,
#[serde(default)]
pub deleted: bool,
pub rev: u64,
}
impl Note {
/// The line the note belongs under in `lines`: the nearest line holding
/// its anchor text anywhere in the buffer (a block pasted far away still
/// carries its note), else its last line clamped to the buffer.
pub fn place(&self, lines: &[String]) -> usize {
let last = lines.len().saturating_sub(1);
let start = self.line.min(last);
if lines
.get(start)
.is_some_and(|l| l.trim() == self.anchor.trim())
{
return start;
}
if self.anchor.trim().is_empty() {
return start;
}
for d in 1..=last {
for cand in [start.checked_sub(d), start.checked_add(d)] {
if let Some(i) = cand.filter(|&i| i <= last)
&& lines[i].trim() == self.anchor.trim()
{
return i;
}
}
}
start
}
/// The box body: the note, then each reply.
pub fn text(&self) -> String {
let mut s = self.body.clone();
for r in &self.replies {
s.push_str(&format!("\n\n{}: {}", r.author, r.body));
}
s
}
/// The box title.
pub fn title(&self) -> String {
if self.resolved {
format!("{} \u{b7} note \u{b7} resolved", self.author)
} else {
format!("{} \u{b7} note", self.author)
}
}
/// A total order on copies of one note: revision first, then the
/// content itself, so two peers holding different copies of the same
/// revision pick the same winner.
fn outranks(&self, other: &Note) -> bool {
let key = |n: &Note| (n.rev, serde_json::to_string(n).unwrap_or_default());
key(self) > key(other)
}
/// Combine two copies of one note the same way on every peer: fields
/// from the higher-ranked copy, replies from both (nothing anyone wrote
/// is lost to a concurrent edit), and a deletion from either sticks.
fn joined(a: &Note, b: &Note) -> Note {
let (win, lose) = if a.outranks(b) { (a, b) } else { (b, a) };
let mut out = win.clone();
for r in &lose.replies {
if !out.replies.contains(r) {
out.replies.push(r.clone());
}
}
out.deleted = a.deleted || b.deleted;
out
}
}
/// Every note in a workspace, merged from local changes and peers.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Notes {
notes: Vec<Note>,
next: u64,
/// Bumped on every change, so a view can tell when to refresh.
pub generation: u64,
}
impl Notes {
/// Take in a copy (local or from a peer). Returns whether it changed
/// anything.
pub fn merge(&mut self, note: Note) -> bool {
match self.notes.iter_mut().find(|n| n.id == note.id) {
Some(existing) => {
let joined = Note::joined(existing, ¬e);
if &joined == existing {
return false;
}
*existing = joined;
self.generation += 1;
true
}
None => {
self.notes.push(note);
self.generation += 1;
true
}
}
}
/// Live (not deleted) notes on `file`.
pub fn on_file<'a>(&'a self, file: &'a str) -> impl Iterator<Item = &'a Note> + 'a {
self.notes
.iter()
.filter(move |n| n.file == file && !n.deleted)
}
/// Every live note.
pub fn live(&self) -> impl Iterator<Item = &Note> {
self.notes.iter().filter(|n| !n.deleted)
}
/// Every note including tombstones, for syncing a joiner.
pub fn all(&self) -> &[Note] {
&self.notes
}
/// The live note with `id`.
pub fn get(&self, id: &str) -> Option<&Note> {
self.notes.iter().find(|n| n.id == id && !n.deleted)
}
/// A new note by `author`, merged and returned for broadcasting.
pub fn add(&mut self, author: &str, file: &str, line: usize, anchor: &str, body: &str) -> Note {
self.next += 1;
let note = Note {
// The clock too: a pid alone recurs across restarts, and a
// reused id would merge a new note into an old tombstone.
id: format!(
"{author}-{}-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_nanos()),
self.next
),
file: file.to_string(),
line,
anchor: anchor.to_string(),
author: author.to_string(),
body: body.to_string(),
replies: Vec::new(),
resolved: false,
deleted: false,
rev: 1,
};
self.merge(note.clone());
note
}
/// Apply `change` to note `id` as a new revision; returns the new copy
/// for broadcasting.
pub fn update(&mut self, id: &str, change: impl FnOnce(&mut Note)) -> Option<Note> {
let n = self.notes.iter_mut().find(|n| n.id == id)?;
change(n);
n.rev += 1;
self.generation += 1;
Some(n.clone())
}
/// Where a workspace's notes are kept.
pub fn store_path(cache: &Path, workspace: &Path) -> PathBuf {
let mut h: u64 = 0xcbf29ce484222325;
for b in workspace.to_string_lossy().bytes() {
h ^= u64::from(b);
h = h.wrapping_mul(0x100000001b3);
}
cache.join("notes").join(format!("{h:016x}.json"))
}
pub fn load(path: &Path) -> Self {
Self {
notes: read_store(path),
next: 0,
generation: 1,
}
}
/// Write every note, tombstones included: a guest that reconnects after
/// a restart still holds its copy of a deleted note, and only the
/// tombstone stops that copy bringing the note back.
///
/// The store on disk is merged in first, under a lock: two windows on
/// one workspace each wrote their own list over the other's, and a note
/// added in one vanished when the other saved. This window picks the
/// other's notes up in the same step.
pub fn save(&mut self, path: &Path) -> std::io::Result<()> {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
let lock = std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(path.with_extension("json.lock"))?;
// Released when `lock` is dropped at the end of the call.
lock.lock()?;
for note in read_store(path) {
self.merge(note);
}
// Written aside and renamed in, so a crash mid-write never leaves a
// truncated file that `load` reads as no notes at all.
let tmp = path.with_extension(format!("json.{}.tmp", std::process::id()));
std::fs::write(&tmp, serde_json::to_string(&self.notes).unwrap_or_default())?;
std::fs::rename(&tmp, path).inspect_err(|_| {
let _ = std::fs::remove_file(&tmp);
})
}
}
/// Merge every store under `old` into the store of the same name under
/// `new` and remove it (#1578 review): how a launch takes over the notes an
/// older croft keeps in the cache. Merged note by note, not one file picked
/// over the other: an older window still open goes on writing its copy to
/// the cache while this version writes to the state directory, and each
/// may hold notes the other lacks. The old store's lock is held throughout,
/// so an older croft saving meanwhile is not lost; it writes a fresh cache
/// store that the next launch merges in. Lock files and anything that is
/// not a store are left for the caller. Best-effort: a store that cannot
/// be merged stays where it is.
pub fn merge_stores(old: &Path, new: &Path) {
let Ok(entries) = std::fs::read_dir(old) else {
return;
};
for entry in entries.flatten() {
let from = entry.path();
if from.extension().is_none_or(|x| x != "json")
|| !entry.file_type().is_ok_and(|t| t.is_file())
{
continue;
}
let Ok(lock) = std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(from.with_extension("json.lock"))
else {
continue;
};
if lock.lock().is_err() {
continue;
}
let mut notes = Notes::load(&from);
if notes.save(&new.join(entry.file_name())).is_ok() {
let _ = std::fs::remove_file(&from);
}
}
}
/// The notes in the store at `path`; none when it does not exist. A store
/// that does not parse is moved aside to `.bak` first, so the next save
/// writes a fresh file instead of replacing the only copy of those notes.
fn read_store(path: &Path) -> Vec<Note> {
let Ok(text) = std::fs::read_to_string(path) else {
return Vec::new();
};
match serde_json::from_str(&text) {
Ok(notes) => notes,
Err(_) => {
let _ = std::fs::rename(path, path.with_extension("json.bak"));
Vec::new()
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// #1578 review: an older window still writing its notes to the cache
/// and a newer one writing to the state directory each hold notes the
/// other lacks; taking over the cache store merges the two note by
/// note, the higher revision winning, instead of keeping one file.
#[test]
fn taking_over_the_cache_store_merges_it_with_the_state_store() {
let cache = tempfile::tempdir().unwrap();
let state = tempfile::tempdir().unwrap();
let old = cache.path().join("notes");
let new = state.path().join("notes");
let mut legacy = Notes::load(&old.join("n.json"));
let shared = legacy.add("ann", "f.rs", 1, "x", "v1");
let only_old = legacy.add("ann", "f.rs", 2, "y", "old only");
let mut current = Notes::load(&new.join("n.json"));
current.merge(shared.clone());
current.update(&shared.id, |n| n.body = "v2".into());
let only_new = current.add("bob", "g.rs", 3, "z", "new only");
current.save(&new.join("n.json")).unwrap();
legacy.save(&old.join("n.json")).unwrap();
merge_stores(&old, &new);
let merged = Notes::load(&new.join("n.json"));
assert_eq!(merged.get(&shared.id).unwrap().body, "v2");
assert!(merged.get(&only_old.id).is_some());
assert!(merged.get(&only_new.id).is_some());
assert!(!old.join("n.json").exists(), "the cache store is gone");
// Negative: nothing under the cache merges nothing and creates
// nothing.
let nowhere = state.path().join("never");
merge_stores(&cache.path().join("missing"), &nowhere);
assert!(!nowhere.exists());
}
#[test]
fn two_windows_saving_keep_each_others_notes_and_a_bad_store_is_kept() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("n.json");
let mut a = Notes::load(&path);
let mut b = Notes::load(&path);
let x = a.add("ann", "f.rs", 1, "x", "from a");
a.save(&path).unwrap();
let y = b.add("bob", "f.rs", 2, "y", "from b");
b.save(&path).unwrap();
let disk = Notes::load(&path);
assert!(disk.get(&x.id).is_some() && disk.get(&y.id).is_some());
assert!(b.get(&x.id).is_some(), "b picked up a's note");
std::fs::write(&path, "{ not json").unwrap();
let mut c = Notes::load(&path);
assert_eq!(
std::fs::read_to_string(path.with_extension("json.bak")).unwrap(),
"{ not json"
);
c.add("cy", "f.rs", 3, "z", "new");
c.save(&path).unwrap();
assert!(path.with_extension("json.bak").exists());
}
fn lines(s: &[&str]) -> Vec<String> {
s.iter().map(|l| l.to_string()).collect()
}
#[test]
fn a_note_follows_its_line_when_lines_are_added_above() {
let mut notes = Notes::default();
let n = notes.add("ada", "a.rs", 1, "fn b() {}", "why?");
assert_eq!(n.place(&lines(&["fn a() {}", "fn b() {}"])), 1);
assert_eq!(
n.place(&lines(&["// new", "// more", "fn a() {}", "fn b() {}"])),
3
);
assert_eq!(n.place(&lines(&["fn b() {}"])), 0, "and when lines go");
assert_eq!(
n.place(&lines(&["changed", "also changed"])),
1,
"an edited line keeps the old number"
);
}
#[test]
fn a_note_finds_its_anchor_anywhere_in_the_buffer() {
let mut notes = Notes::default();
let n = notes.add("ada", "a.rs", 0, "fn moved() {}", "why?");
let mut buf = vec![String::from("// filler"); 1000];
buf.push(String::from("fn moved() {}"));
assert_eq!(n.place(&buf), 1000);
let again = notes.add("ada", "a.rs", 0, "x", "y");
assert_ne!(n.id, again.id);
}
#[test]
fn the_newest_revision_wins_and_a_deletion_sticks() {
let mut a = Notes::default();
let n = a.add("ada", "a.rs", 0, "x", "note");
let mut b = Notes::default();
assert!(b.merge(n.clone()));
let resolved = a.update(&n.id, |n| n.resolved = true).unwrap();
let replied = b
.update(&n.id, |n| {
n.replies.push(Reply {
author: "bob".into(),
body: "ok".into(),
})
})
.unwrap();
// Same revision from two sides: both converge, and neither the
// reply nor anything else is lost.
a.merge(replied.clone());
b.merge(resolved.clone());
assert_eq!(a.get(&n.id), b.get(&n.id));
assert_eq!(a.get(&n.id).unwrap().replies.len(), 1);
let gone = a.update(&n.id, |n| n.deleted = true).unwrap();
b.merge(gone);
assert!(!b.merge(n.clone()), "an old copy can't resurrect it");
assert!(b.get(&n.id).is_none());
}
#[test]
fn a_deleted_note_stays_deleted_across_a_restart() {
let tmp = tempfile::tempdir().unwrap();
let path = Notes::store_path(tmp.path(), Path::new("/w"));
let mut n = Notes::default();
let keep = n.add("ada", "a.rs", 0, "x", "keep");
let drop = n.add("ada", "a.rs", 1, "y", "drop");
n.update(&drop.id, |d| d.deleted = true);
n.save(&path).unwrap();
let mut back = Notes::load(&path);
assert_eq!(back.live().count(), 1);
assert_eq!(back.get(&keep.id).map(|k| k.body.as_str()), Some("keep"));
// A guest's stale copy from before the delete, arriving after the
// restart, must not bring it back.
back.merge(drop.clone());
assert!(back.get(&drop.id).is_none());
}
#[test]
fn the_box_reads_title_body_and_replies() {
let mut notes = Notes::default();
let n = notes.add("ada", "a.rs", 0, "x", "why?");
let n = notes
.update(&n.id, |n| {
n.replies.push(Reply {
author: "bob".into(),
body: "because".into(),
});
n.resolved = true;
})
.unwrap();
assert_eq!(n.title(), "ada \u{b7} note \u{b7} resolved");
assert_eq!(n.text(), "why?\n\nbob: because");
}
}