History Options: no duplicate snapshot when saving an unchanged document (#2966)

Automatically Create New Snapshot When Saving adds no row when the document
is unchanged since the snapshot the previous save added (and that snapshot
is still there), so Ctrl+S on a clean document doesn't stack duplicates.
The new snapshot's tiles are trimmed against the history budget at once,
and its memory cost is documented: snapshots count against History & Cache
by dropping the oldest states, but are never dropped themselves.

Tests: the engine dedupe, and the desktop save path (a save adds one, Save a
Copy none, a background save finishing on another document snapshots the
document it saved). The purge test from main deletes the first snapshot so
it measures only the snapshot it takes.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
David MannandClaude Opus 5.5 committed 2026-10-15 14:00:07 +02:00
1 parent cb8f2808d2
commit 42e831fa30
6 files changed
+103 -5

No files matched your search

+3
View File
@@ -503,6 +503,9 @@ mod tests {
#[test]
fn purging_histories_frees_only_what_no_snapshot_keeps() {
let mut s = session();
// Only the snapshot taken here: the first snapshot (the document as opened) would keep
// tiles of the oldest states too.
s.execute("history.deleteSnapshot", json!({"snapshot": 0})).unwrap();
s.execute("history.newSnapshot", json!({})).unwrap();
s.execute("edit.fill", json!({"color": "#0000ff"})).unwrap();
let st = s.active().unwrap();
+43 -2
View File
@@ -62,19 +62,36 @@ pub fn show_new_snapshot_dialog(s: &Session) -> bool {
/// History Options › Automatically Create New Snapshot When Saving: after the active document
/// was saved to its own file (not a copy or an export), add a snapshot of it named with the local
/// time of the save, as Photoshop does. Not a history state. Returns the new snapshot's id, or
/// `None` when the option is off or no document is active. Shells call it where they record a
/// document save.
/// `None` when the option is off, no document is active, or the document is unchanged since the
/// snapshot the previous save added (and that snapshot is still there), so saving a clean
/// document again doesn't add a duplicate row. Shells call it where they record a document save.
///
/// Memory: like every History panel snapshot, each one pins a copy of the document for the
/// session (only the tiles that differ from the document and the other snapshots cost memory).
/// [`crate::DocState::trim_history`] counts those tiles against the History & Cache budget by
/// dropping the oldest history states, but never drops a snapshot itself: many saves of a
/// changing document can hold more than the budget until snapshots are deleted or the document
/// is closed.
pub fn snapshot_on_save(s: &mut Session) -> Option<u64> {
if !s.prefs().history_options.automatically_create_new_snapshot_when_saving {
return None;
}
let st = s.active_mut()?;
// Saved again without a change: the previous save's snapshot already shows this document.
if let Some(prev) = st.save_snapshot
&& st.snapshots.iter().any(|snap| snap.id == prev && std::sync::Arc::ptr_eq(&snap.doc, &st.doc))
{
return None;
}
let name = save_snapshot_name().unwrap_or_else(|| crate::history_cmds::next_snapshot_name(st));
let id = st.next_snapshot;
st.next_snapshot = id.saturating_add(1);
let (doc, layers) = (st.doc.clone(), st.layer_target());
// Like the camera button: the document and its saved state are unchanged.
st.snapshots.push(Snapshot { id, name, doc, layers });
st.save_snapshot = Some(id);
// The snapshot's tiles count against the history budget.
st.trim_history();
Some(id)
}
@@ -400,6 +417,30 @@ mod tests {
assert_eq!(snapshot_on_save(&mut empty), None);
}
/// Saving an unchanged document again (⌘S on a clean document) adds no duplicate row; a
/// change, or deleting the previous save's snapshot, makes the next save add one again.
#[test]
fn saving_an_unchanged_document_adds_no_duplicate_snapshot() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
s.execute(CMD, json!({"automaticallyCreateNewSnapshotWhenSaving": true})).unwrap();
let first = snapshot_on_save(&mut s).unwrap();
assert_eq!(snapshot_on_save(&mut s), None, "unchanged since the last save snapshot");
assert_eq!(snapshot_names(&s).len(), 2, "the first snapshot and one save snapshot");
// A view-only change (no document change) doesn't count either.
s.active_mut().unwrap().revision += 1;
assert_eq!(snapshot_on_save(&mut s), None);
// An edit does.
s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();
let second = snapshot_on_save(&mut s).unwrap();
assert!(second > first);
assert_eq!(snapshot_on_save(&mut s), None);
// The previous save's snapshot deleted: the next save shows the document again.
s.execute("history.deleteSnapshot", json!({"snapshot": second})).unwrap();
assert!(snapshot_on_save(&mut s).is_some());
assert_eq!(snapshot_names(&s).len(), 3);
}
#[test]
fn show_new_snapshot_dialog_reads_the_option() {
let mut s = Session::new();
+4
View File
@@ -235,6 +235,9 @@ pub struct DocState {
pub snapshots: Vec<history_cmds::Snapshot>,
/// The id the next snapshot gets; ids are never reused, so deleting one keeps the others.
next_snapshot: u64,
/// The snapshot the latest save added (History Options › Automatically Create New Snapshot
/// When Saving), so saving an unchanged document again doesn't add a duplicate row.
save_snapshot: Option<u64>,
}
impl DocState {
@@ -283,6 +286,7 @@ impl DocState {
color_samplers: Vec::new(),
snapshots: vec![first],
next_snapshot: 1,
save_snapshot: None,
}
}
/// The selected layers in bottom-to-top document order, always including the active layer.
+50
View File
@@ -254,3 +254,53 @@ fn save_settings_start_at_the_opened_files_encoding() {
app.open_bytes("art.webp", &lossless).unwrap();
assert!(app.save_settings().webp_lossless);
}
/// The names of the active document's History panel snapshots.
fn snapshots(app: &PhotocraftApp) -> Vec<String> {
app.session.active().unwrap().snapshots.iter().map(|s| s.name.clone()).collect()
}
/// History Options › Automatically Create New Snapshot When Saving (#2966) through the desktop
/// save path: a save adds one snapshot, saving again unchanged adds none, Save a Copy adds none.
#[test]
fn a_save_adds_one_snapshot_and_a_copy_none() {
let mut app = app();
app.run("history.options", json!({"automaticallyCreateNewSnapshotWhenSaving": true})).unwrap();
let before = snapshots(&app).len();
app.save_as(Some("saved.psd".into())).unwrap();
assert_eq!(snapshots(&app).len(), before + 1, "the save adds a snapshot");
let st = app.session.active().unwrap();
assert!(std::sync::Arc::ptr_eq(&st.snapshots.last().unwrap().doc, &st.doc), "of the document as saved");
app.save_as(Some("saved.psd".into())).unwrap();
assert_eq!(snapshots(&app).len(), before + 1, "saving an unchanged document adds no duplicate");
app.run("layer.new.layer", json!({})).unwrap();
app.write_document("copy.psd".into(), &ExportSettings::default(), true).unwrap();
assert_eq!(snapshots(&app).len(), before + 1, "Save a Copy adds none");
app.save_as(Some("saved.psd".into())).unwrap();
assert_eq!(snapshots(&app).len(), before + 2);
}
/// A background save that finishes while another document is active snapshots the document it
/// saved, not the active one.
#[test]
fn a_background_save_snapshots_its_own_document() {
let mut app = app();
app.run("history.options", json!({"automaticallyCreateNewSnapshotWhenSaving": true})).unwrap();
let (saved_doc, revision) = {
let st = app.session.active().unwrap();
(st.doc.id, st.revision)
};
let saved_snaps = snapshots(&app).len();
app.run("file.new", json!({"width": 4, "height": 4, "name": "Untitled-2"})).unwrap();
let active = app.active_doc_id().unwrap();
assert_ne!(active, saved_doc);
let active_snaps = snapshots(&app).len();
// What jobs_ui does when the save job of `saved_doc` ends.
app.saved(saved_doc, revision, "background.psd", &[], false);
assert_eq!(app.active_doc_id(), Ok(active), "the active document stays active");
assert_eq!(snapshots(&app).len(), active_snaps, "the active document gets no snapshot");
let st = app.session.documents().iter().find(|st| st.doc.id == saved_doc).unwrap();
assert_eq!(st.snapshots.len(), saved_snaps + 1, "the saved document gets one");
assert_eq!(st.path.as_deref(), Some("background.psd"));
}
+1 -1
View File
@@ -112,7 +112,7 @@ store expose and persist the same setting; scripts keep using canonical command
| `layer.newAdjustmentLayer.hueSaturation` | `{"hue":30,"saturation":10}` |
| `paint.stroke` | `{"points":[[x,y,pressure],…],"size":20,"color":"#ff0000"}` |
| `select.rect` | `{"x":0,"y":0,"width":100,"height":50,"mode":"add","ellipse":false}` |
| `document.inspect` | `{}`: layer tree, history, snapshots (`[{id, name}]`, for `history.selectSnapshot`; id 0 is the document as opened, unless `history.options` `automaticallyCreateFirstSnapshot` is off), selection bounds |
| `document.inspect` | `{}`: layer tree, history, snapshots (`[{id, name}]`, for `history.selectSnapshot`; id 0 is the document as opened, unless `history.options` `automaticallyCreateFirstSnapshot` is off; with `automaticallyCreateNewSnapshotWhenSaving` on, each save of a changed document adds one named `HH:MM:SS`, or `Snapshot N` in the browser; every snapshot keeps its copy of the document for the session: its tiles count against the History & Cache budget by dropping the oldest history states, but snapshots are never dropped themselves), selection bounds |
| `layer.list` | `{"document":index?,"flat":bool?}`: just the layers, top-down: `id`, `name`, `kind`, `visible`, `bounds` (`[x,y,w,h]` or null), `selected`, `active`; groups list their `children`, or with `flat` every layer is one row with its `depth` and `parent` group id |
| `document.pixel` | `{"x":10,"y":10}`: composite RGBA |
| `document.presets.list` | `{}` → `{presets:[{name,settings}]}`: saved New Document configurations |
+2 -2
View File
@@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js
| [Performance](#performance) | 3 | 22 | 22 | 56 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 17 not run, 5 not measurable yet (baseline 2026-10-05) |
| [File compatibility](#file-compatibility) | 7 | 14 | 6 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 188/256, round trip ≥ 258/256 |
| [Tools](#tools) | 33 | 11 | 0 | |
| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 26 of 166 (target 0) |
| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 26 of 171 (target 0) |
| [Type](#type) | 4 | 3 | 2 | |
| [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) |
| [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 29 of 29 crates; panic_hunt present |
@@ -177,7 +177,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t
## Workspace and UI
**Settings that do nothing: 26 of 166** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't.
**Settings that do nothing: 26 of 171** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't.
Unread: `general.color_picker`, `general.animated_zoom`, `general.zoom_resizes_windows`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `file_handling.save_in_background`, `performance.cache_levels`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.text_engine`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `enhanced_controls.touch_gestures`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.resolution`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`.