fix(notes): keep Discard usable after a failed load

Discard waited for a stored revision, so after a load failed (stored
notes not valid UTF-8, a read error, a lost reply) the editor stayed
read-only with no way to reload. The page now tracks the outstanding
load itself: Discard is refused only while a load or save is in flight,
a load error or a ten-second timeout ends the load, and Discard retries.

A save acknowledgement arriving after its timeout and after Discard had
started a reload replaced the saved state while the editor still showed
older text, so the next save would silently revert it. Acknowledgements
are ignored while a load is outstanding, and a reload forgets the last
save.

The component removes a lock whose token could not be written and
cleans up renamed stale locks with the abandoned staging files.
check_notes.py adds a failed load followed by a repaired file and
Discard; the previous package stays read-only there and fails.
This commit is contained in:
Marco Allegretti 2026-10-09 09:05:25 +00:00
parent 87436d0e08
commit c1ea57fbef
No known key found for this signature in database
5 changed files with 64 additions and 15 deletions

View file

@ -1 +1 @@
555f2d3d0183d28f99f66efef3f2dc8bb8aa3e6a4d038dc78b1414ccf54d23dd52a1668314d377d10603580908d7d9de7109a6ddcf0d7aa175bbf4bbd835c80c a533f421c6e9b5d5df82d082b68af0b8408a7f02fd060bd71d1b33bc1579046a3791d73a929b90c8a62c7c42949f412bd88952c7e10f1575cc85cccb1602a40d

View file

@ -79,13 +79,20 @@ impl SaveLock {
.open(LOCK_PATH) .open(LOCK_PATH)
{ {
Ok(mut file) => { Ok(mut file) => {
let _ = file.write_all(token.as_bytes()); if let Err(e) = file.write_all(token.as_bytes()) {
let _ = std::fs::remove_file(LOCK_PATH);
return Err(format!("cannot lock notes: {e}"));
}
return Ok(SaveLock { token }); return Ok(SaveLock { token });
} }
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
// A lock older than STALE_LOCK (or of unknown age) was left // A lock older than STALE_LOCK was left by an ended session
// by an ended session. Renaming it away is atomic, so only // (wasmtime-wasi reports modification times, so an unknown
// one save can take it over. // age does not occur in practice). Renaming it away is
// atomic, so only one save can take it over. Two saves that
// both see it stale within the same instant could still
// both proceed; that needs an abandoned lock and two
// windows saving at once.
let stale = std::fs::metadata(LOCK_PATH) let stale = std::fs::metadata(LOCK_PATH)
.and_then(|m| m.modified()) .and_then(|m| m.modified())
.map(|t| t.elapsed().is_ok_and(|age| age > STALE_LOCK)) .map(|t| t.elapsed().is_ok_and(|age| age > STALE_LOCK))
@ -112,7 +119,8 @@ impl Drop for SaveLock {
} }
} }
/// Removes staging files left by saves that ended before their rename. Only /// Removes staging files left by saves that ended before their rename, and
/// stale locks whose removal failed. Only
/// called with the lock held, when no other save is in progress. /// called with the lock held, when no other save is in progress.
fn remove_abandoned_staging() { fn remove_abandoned_staging() {
let Ok(entries) = std::fs::read_dir("/data") else { let Ok(entries) = std::fs::read_dir("/data") else {
@ -121,7 +129,9 @@ fn remove_abandoned_staging() {
for entry in entries.flatten() { for entry in entries.flatten() {
let name = entry.file_name(); let name = entry.file_name();
let name = name.to_string_lossy(); let name = name.to_string_lossy();
if name.starts_with(".notes.txt.") && name.ends_with(".saving") { let abandoned = (name.starts_with(".notes.txt.") && name.ends_with(".saving"))
|| (name.starts_with(".notes.lock.") && name.ends_with(".stale"));
if abandoned {
let _ = std::fs::remove_file(entry.path()); let _ = std::fs::remove_file(entry.path());
} }
} }

View file

@ -119,6 +119,7 @@
var seq = 0; var seq = 0;
var pending = null; var pending = null;
var lastSent = null; var lastSent = null;
var loading = null; // timer of the outstanding load, if any
var encoder = new TextEncoder(); var encoder = new TextEncoder();
function setStatus(msg) { statusEl.textContent = msg; } function setStatus(msg) { statusEl.textContent = msg; }
@ -169,15 +170,32 @@
setStatus('saving…'); setStatus('saving…');
}); });
// Loads the stored notes into a read-only editor. Only one load is
// outstanding at a time; a failed or unanswered load can be retried with
// Discard.
function load(status) {
rev = null;
lastSent = null;
setLoaded(false);
loading = setTimeout(function () {
loading = null;
setStatus('the notes did not load; use Discard to retry');
}, REPLY_TIMEOUT);
send({ op: 'load' });
setStatus(status);
}
function finishLoad() {
clearTimeout(loading);
loading = null;
}
// Discard reloads the stored notes, replacing unsaved edits. // Discard reloads the stored notes, replacing unsaved edits.
document.getElementById('discard').addEventListener('click', function () { document.getElementById('discard').addEventListener('click', function () {
if (!window.weftIpc || pending || rev === null) return; if (!window.weftIpc || pending || loading) return;
editor.value = saved; editor.value = saved;
countChars(); countChars();
rev = null; load('reloading…');
setLoaded(false);
send({ op: 'load' });
setStatus('reloading…');
}); });
document.addEventListener('keydown', function (e) { document.addEventListener('keydown', function (e) {
@ -193,14 +211,15 @@
if (msg.op === 'loaded') { if (msg.op === 'loaded') {
// Only the reply to the outstanding load applies; the editor is // Only the reply to the outstanding load applies; the editor is
// read-only until it arrives, so it never replaces newer text. // read-only until it arrives, so it never replaces newer text.
if (rev !== null) return; if (!loading) return;
finishLoad();
editor.value = msg.text; editor.value = msg.text;
countChars(); countChars();
saved = msg.text; saved = msg.text;
rev = msg.rev; rev = msg.rev;
setLoaded(true); setLoaded(true);
setStatus(''); setStatus('');
} else if (msg.op === 'saved' && lastSent && msg.seq === lastSent.seq) { } else if (msg.op === 'saved' && !loading && lastSent && msg.seq === lastSent.seq) {
// Also accepts an acknowledgement that arrives after the timeout. // Also accepts an acknowledgement that arrives after the timeout.
saved = lastSent.text; saved = lastSent.text;
rev = msg.rev; rev = msg.rev;
@ -208,6 +227,7 @@
setStatus(editor.value === saved ? 'saved' : 'saved; newer changes are not saved yet'); setStatus(editor.value === saved ? 'saved' : 'saved; newer changes are not saved yet');
} else if (msg.op === 'error') { } else if (msg.op === 'error') {
if (pending && msg.seq === pending.seq) finishSave(); if (pending && msg.seq === pending.seq) finishSave();
if (loading && msg.seq === undefined) finishLoad();
setStatus(msg.conflict setStatus(msg.conflict
? 'not saved: changed in another window. Copy your text, then Discard to reload.' ? 'not saved: changed in another window. Copy your text, then Discard to reload.'
: 'error: ' + msg.message); : 'error: ' + msg.message);
@ -217,7 +237,7 @@
function setupIpc() { function setupIpc() {
if (!window.weftIpc) { setTimeout(setupIpc, 50); return; } if (!window.weftIpc) { setTimeout(setupIpc, 50); return; }
window.weftIpc.onmessage = onMessage; window.weftIpc.onmessage = onMessage;
send({ op: 'load' }); load('');
} }
setLoaded(false); setLoaded(false);

View file

@ -16,6 +16,9 @@ sequence, quotes, a tab and non-ASCII characters, launches
4. Discard reloads the stored text. Keys typed while that reload is in 4. Discard reloads the stored text. Keys typed while that reload is in
flight (runtime paused again) must be ignored, so a following save stores flight (runtime paused again) must be ignored, so a following save stores
the reloaded text plus only what was typed afterwards. the reloaded text plus only what was typed afterwards.
5. A load that fails (the stored notes are not valid UTF-8) leaves Discard
usable: after the file is repaired, Discard loads it and it can be edited
and saved again.
Requires Xvfb, xwd, ImageMagick's convert and xdotool. Requires Xvfb, xwd, ImageMagick's convert and xdotool.
""" """
@ -136,6 +139,22 @@ def run(args, desktop, home, xdotool):
act("type", "--delay", "40", "!") act("type", "--delay", "40", "!")
act("key", "ctrl+s") act("key", "ctrl+s")
wait_for_file(notes, other + "!") wait_for_file(notes, other + "!")
notes.write_bytes(b"\xff not text")
act("mousemove", "--sync", *DISCARD)
act("click", "1")
time.sleep(2)
if notes.read_bytes() != b"\xff not text":
raise AssertionError("a failed load changed the stored notes")
notes.write_text("repaired", encoding="utf-8")
act("click", "1")
time.sleep(2)
act("mousemove", "--sync", "100", "300")
act("click", "1")
act("key", "ctrl+End")
act("type", "--delay", "40", "?")
act("key", "ctrl+s")
wait_for_file(notes, "repaired?")
leftovers = [p.name for p in notes.parent.iterdir() if p.name != "notes.txt"] leftovers = [p.name for p in notes.parent.iterdir() if p.name != "notes.txt"]
if leftovers: if leftovers:
raise AssertionError(f"files left beside the notes: {leftovers}") raise AssertionError(f"files left beside the notes: {leftovers}")