Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Survive a lost window GPU device: draw nothing, save unsaved work for recovery, close (#3438, #1215)

00xJ04615a8bc26c7
diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs
index b0b00a865..4fdd54960 100644
--- a/apps/photocraft/src/main.rs
+++ b/apps/photocraft/src/main.rs
@@ -785,8 +785,9 @@ fn main() -> eframe::Result {
{
app.set_wgpu(rs);
} else {
- // The window still draws with wgpu: record its errors instead of panicking.
- let _ = photocraft_ui_egui::gpu_canvas::DeviceHealth::watch(&rs.device);
+ // The window still draws with wgpu: record its errors instead of panicking,
+ // and notice when the device is lost (#3438).
+ app.watch_window_device(&rs.device);
}
}
let fallback_reason = std::env::var("PHOTOCRAFT_GPU_STARTUP_FAILURE").ok().or_else(|| {
diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs
index 20de0d6be..c814bc75c 100644
--- a/apps/photocraft/src/services.rs
+++ b/apps/photocraft/src/services.rs
@@ -383,12 +383,13 @@ fn with_store<R>(store: &SharedRecovery, f: impl FnOnce(&mut RecoveryStore) -> R
fn recovery_services(dir: Option<PathBuf>) -> Services {
let recover_dir = dir.clone();
let store: SharedRecovery = Rc::new(RefCell::new(dir.map(RecoveryStore::new)));
- let (s1, s2, s4) = (store.clone(), store.clone(), store.clone());
+ let (s1, s2, s4, s5) = (store.clone(), store.clone(), store.clone(), store.clone());
Services {
autosave: Some(Box::new(move |doc: &Arc<Document>, revision: u64, path: Option<&str>| {
with_store(&s1, |s| s.autosave_checked(doc, revision, path.map(str::to_string)))?
})),
autosave_results: Some(Box::new(move || with_store(&s4, |s| s.take_completed()).unwrap_or_default())),
+ flush_autosaves: Some(Box::new(move || with_store(&s5, RecoveryStore::flush).unwrap_or_default())),
discard_autosave: Some(Box::new(move |id: u64| {
let _ = with_store(&s2, |s| s.discard(id));
})),
diff --git a/crates/format/src/autosave.rs b/crates/format/src/autosave.rs
index 06150e60e..a2fbddb73 100644
--- a/crates/format/src/autosave.rs
+++ b/crates/format/src/autosave.rs
@@ -297,6 +297,17 @@ impl RecoveryStore {
self.savers.iter().flat_map(|(&id, saver)| saver.take_completed().into_iter().map(move |(revision, result)| (id, revision, result))).collect()
}
+ /// Finish every queued autosave and wait for it, then return the outcomes as
+ /// [`take_completed`](Self::take_completed) does. For a session that ends without asking,
+ /// e.g. because the window's graphics device was lost (#3438). The workers stop, so later
+ /// autosaves of the same documents report a stopped worker.
+ pub fn flush(&mut self) -> Vec<(u64, u64, std::result::Result<(), String>)> {
+ for saver in self.savers.values_mut() {
+ saver.shutdown();
+ }
+ self.take_completed()
+ }
+
/// Document `doc_id` was saved or closed: remove its recovery data, both its own autosaves
/// and the entry it adopted.
pub fn discard(&mut self, doc_id: u64) -> Result<()> {
diff --git a/crates/format/tests/autosave.rs b/crates/format/tests/autosave.rs
index 29905d7ac..fa078dab6 100644
--- a/crates/format/tests/autosave.rs
+++ b/crates/format/tests/autosave.rs
@@ -188,6 +188,27 @@ fn recovered_entries_survive_a_second_crash_until_saved_or_closed() {
std::fs::remove_dir_all(dir).unwrap();
}
+/// #3438: a session about to end without asking (its window's graphics device was lost) writes
+/// everything queued before it returns, so the next launch recovers it.
+#[test]
+fn flush_writes_every_queued_autosave_before_returning() {
+ let dir = temp_dir("flush");
+ let (a, b) = (version(1, 3, ColorMode::Rgb), version(2, 5, ColorMode::Grayscale));
+ let mut store = RecoveryStore::new(&dir);
+ store.autosave_checked(&Arc::new(a.clone()), 4, None).unwrap();
+ store.autosave_checked(&Arc::new(b.clone()), 6, Some("/work/b.pcraft".into())).unwrap();
+ let mut done = store.flush();
+ done.sort_by_key(|(id, ..)| *id);
+ assert_eq!(done, vec![(1, 4, Ok(())), (2, 6, Ok(()))]);
+ // On disk while the store is still alive, not only once it is dropped.
+ let docs = recovered(&RecoveryStore::new(&dir));
+ assert_eq!(docs.len(), 2);
+ assert!(docs.values().any(|d| *d == same(a.clone())) && docs.values().any(|d| *d == same(b.clone())));
+ assert!(store.autosave_checked(&Arc::new(a), 5, None).is_err(), "the workers stopped");
+ drop(store);
+ std::fs::remove_dir_all(dir).unwrap();
+}
+
#[test]
fn new_documents_never_overwrite_surviving_entries() {
let dir = temp_dir("collision");
diff --git a/crates/gpu/src/health.rs b/crates/gpu/src/health.rs
index cb1a116c4..61aacf8b5 100644
--- a/crates/gpu/src/health.rs
+++ b/crates/gpu/src/health.rs
@@ -53,6 +53,8 @@ struct Inner {
faulted: AtomicBool,
fault: Mutex<Option<Fault>>,
errors: AtomicU64,
+ /// wgpu itself reported the device lost (see [`DeviceHealth::device_lost`]).
+ device_lost: AtomicBool,
}
/// Shared health flag of one wgpu device. Cheap to clone; every clone sees the same state.
@@ -84,6 +86,7 @@ impl DeviceHealth {
(_, false) => message,
};
log::error!("wgpu device lost ({reason:?}): {detail}");
+ lost.0.device_lost.store(true, Ordering::Release);
lost.mark(Fault::Lost(detail));
});
let errors = health.clone();
@@ -134,6 +137,32 @@ impl DeviceHealth {
self.0.errors.load(Ordering::Relaxed)
}
+ /// Whether wgpu itself reported the device lost: its device-lost callback ran, or polling it
+ /// panicked. Unlike a fault recorded with [`mark`](Self::mark) (a simulated loss, or an
+ /// uncaptured error that names one), nothing drawn with the device reaches the screen any
+ /// more, the window's own frames included (#3438).
+ pub fn device_lost(&self) -> bool {
+ self.0.device_lost.load(Ordering::Acquire)
+ }
+
+ /// Non-blocking poll that runs even after a fault was recorded, so a device that is lost
+ /// later (a driver reset while the app sat idle or the PC slept) is noticed before the next
+ /// frame is drawn with it. Skipped once [`device_lost`](Self::device_lost).
+ pub fn probe(&self, device: &wgpu::Device) {
+ if self.device_lost() {
+ return;
+ }
+ if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| device.poll(wgpu::PollType::Poll))).is_err() {
+ self.lost_by_poll();
+ }
+ }
+
+ /// `Device::poll` panicked: wgpu found the device lost.
+ fn lost_by_poll(&self) {
+ self.0.device_lost.store(true, Ordering::Release);
+ self.mark(Fault::Lost("the device stopped responding".into()));
+ }
+
/// Block until `index` (or all submitted work) finished, unless the device is unusable.
/// Returns whether the device is still healthy afterwards. `Device::poll` panics on a lost
/// device, so a panic is caught and recorded as a loss (native only; the web has no blocking
@@ -147,7 +176,7 @@ impl DeviceHealth {
match poll {
Ok(Ok(_)) => {}
Ok(Err(e)) => log::warn!("wgpu poll: {e}"),
- Err(_) => self.mark(Fault::Lost("the device stopped responding".into())),
+ Err(_) => self.lost_by_poll(),
}
self.is_ok()
}
@@ -158,7 +187,7 @@ impl DeviceHealth {
return;
}
if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| device.poll(wgpu::PollType::Poll))).is_err() {
- self.mark(Fault::Lost("the device stopped responding".into()));
+ self.lost_by_poll();
}
}
}
@@ -190,6 +219,8 @@ mod tests {
assert_eq!(h.fault(), Some(Fault::Lost("reset".into())));
c.mark(Fault::Lost("later".into()));
assert_eq!(h.fault().map(|f| f.to_string()).as_deref(), Some("GPU device lost: reset"));
+ // A recorded loss is not wgpu reporting the device lost (#3438).
+ assert!(!h.device_lost());
}
#[test]
diff --git a/crates/gpu/tests/device_loss.rs b/crates/gpu/tests/device_loss.rs
index 689a78728..294961ee8 100644
--- a/crates/gpu/tests/device_loss.rs
+++ b/crates/gpu/tests/device_loss.rs
@@ -82,6 +82,28 @@ fn health_wait_on_a_destroyed_device_is_safe() {
assert!(!health.wait(&device, None));
}
+/// #3438: only wgpu reporting the device lost counts as a real loss. A fault recorded by hand (a
+/// simulated loss, or an uncaptured error that names one) leaves the device usable, and
+/// [`DeviceHealth::probe`] keeps polling it so a later real loss is still noticed.
+#[test]
+fn only_wgpu_reports_a_real_device_loss() {
+ let _lock = GPU_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
+ let Some((_adapter, device, _queue)) = device() else { return };
+ let health = DeviceHealth::watch(&device);
+ health.probe(&device);
+ assert!(health.is_ok() && !health.device_lost());
+ health.mark(Fault::Lost("simulated".into()));
+ health.probe(&device);
+ assert!(!health.is_ok());
+ assert!(!health.device_lost(), "a recorded fault is not a real loss");
+ device.destroy();
+ health.probe(&device);
+ assert!(health.device_lost(), "a destroyed device is lost: {:?}", health.fault());
+ // Once lost, probing is a no-op rather than another caught panic.
+ health.probe(&device);
+ assert!(health.device_lost());
+}
+
fn assert_unwatched_destroyed_device(encode_only: bool) {
let _lock = GPU_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let Some((adapter, device, queue)) = device() else { return };
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index 8cddc60b2..2a1a7c3bf 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -20,9 +20,11 @@
//! - The synthetic input methods reject unknown fields, wrong types, unknown enum values and
//! out-of-range numbers before acting, naming the parameter (#2449)
//! - `ui.resize {width, height}`: resize the main window
-//! - `ui.gpu.simulateLoss {error?}`: act as if the wgpu device was lost (or, with `error: true`,
-//! reported an error): the app switches to the CPU renderer for the rest of the session, as on a
-//! real loss. For testing the fallback; returns whether a GPU canvas was active
+//! - `ui.gpu.simulateLoss {error?, destroy?}`: act as if the wgpu device was lost (or, with
+//! `error: true`, reported an error): the app switches to the CPU renderer for the rest of the
+//! session, as on a real loss. For testing the fallback; returns whether a GPU canvas was active.
+//! `destroy: true` destroys the window's real device instead, as a driver reset does: the app
+//! saves its unsaved documents for recovery and closes (#3438); returns `destroyed`
//! - `ui.screenshot {path?, focus?}`: capture the main window (PNG). Raises the window first (default)
//! because occluded macOS windows stop rendering
//! - `ui.focus`: bring the main window to the front
@@ -1190,6 +1192,11 @@ fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest)
ok(Value::Null)
}
"ui.gpu.simulateLoss" => {
+ if p.get("destroy").and_then(Value::as_bool).unwrap_or(false) {
+ let destroyed = app.destroy_window_device();
+ ctx.request_repaint();
+ return ok(json!({"destroyed": destroyed}));
+ }
let error = p.get("error").and_then(Value::as_bool).unwrap_or(false);
let fault = if error {
photocraft_gpu::Fault::Error("simulated error (ui.gpu.simulateLoss)".into())
diff --git a/crates/ui-egui/src/gpu_status.rs b/crates/ui-egui/src/gpu_status.rs
index 337283bdf..008e52a6f 100644
--- a/crates/ui-egui/src/gpu_status.rs
+++ b/crates/ui-egui/src/gpu_status.rs
@@ -38,6 +38,52 @@ pub fn check(app: &mut PhotocraftApp, ctx: &egui::Context) {
}
}
+/// End-of-frame check of the device the window itself draws with (#3438). Once wgpu reports it
+/// lost (a driver reset, for example after the PC slept), egui-wgpu can't draw another frame: one
+/// with shapes panics creating its staging buffers (#1215), and one without leaves a frozen window
+/// whose close button opens an unsaved-changes prompt nobody can see. So this frame and every later
+/// one draw nothing; the first writes every unsaved document to crash recovery, waits for the
+/// writes, and closes the app without asking. The next launch reopens the documents.
+pub fn check_window(app: &mut PhotocraftApp, ctx: &egui::Context) {
+ let Some((device, health)) = app.window_device.as_ref() else { return };
+ // A loss while the app sat idle or the PC slept is noticed here, before the next frame.
+ health.probe(device);
+ if !health.device_lost() {
+ return;
+ }
+ ctx.graphics_mut(|g| *g = Default::default());
+ if app.window_lost {
+ return;
+ }
+ app.window_lost = true;
+ let reason = health.fault().map_or_else(|| "GPU device lost".to_string(), |f| f.to_string());
+ log::error!("{reason}: the window can't be drawn any more; saving unsaved documents for recovery and closing");
+ save_for_recovery(app);
+ app.allow_close = true;
+ ctx.send_viewport_cmd(egui::ViewportCommand::Close);
+}
+
+/// Queue a crash-recovery autosave of every document with unsaved changes, whatever the autosave
+/// timer and preference, and wait until the writes finished (see `Services::flush_autosaves`).
+fn save_for_recovery(app: &mut PhotocraftApp) {
+ let jobs: Vec<_> = app.session.documents().iter().filter(|d| d.is_dirty()).map(|d| (d.doc.clone(), d.revision, d.path.clone())).collect();
+ if let Some(save) = app.services.autosave.as_mut() {
+ for (doc, revision, path) in &jobs {
+ if let Err(e) = save(doc, *revision, path.as_deref()) {
+ log::error!("couldn't save {} for recovery: {e}", doc.name);
+ }
+ }
+ }
+ if let Some(flush) = app.services.flush_autosaves.as_mut() {
+ for (id, revision, outcome) in flush() {
+ match outcome {
+ Ok(()) => log::info!("document {id} (revision {revision}) saved for recovery"),
+ Err(e) => log::error!("couldn't save document {id} for recovery: {e}"),
+ }
+ }
+ }
+}
+
/// Drop the GPU canvas after `fault`: free its resources, send every view through the CPU
/// path, record why, and tell the user. Documents are untouched.
pub fn fall_back(app: &mut PhotocraftApp, fault: &photocraft_gpu::Fault) {
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 2c23a29e3..7736de117 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -523,6 +523,10 @@ pub struct Services {
pub autosave: Option<AutosaveFn>,
/// None for services that report synchronous success through `autosave`.
pub autosave_results: Option<AutosaveResultsFn>,
+ /// Finish every queued crash-recovery autosave and wait for it, with outcomes like
+ /// `autosave_results`. For a session that ends without asking: the window's graphics device
+ /// was lost (see `gpu_status::check_window`).
+ pub flush_autosaves: Option<AutosaveResultsFn>,
pub discard_autosave: Option<DiscardAutosaveFn>,
pub recover: Option<RecoverFn>,
pub adopt_autosave: Option<AdoptAutosaveFn>,
@@ -813,6 +817,11 @@ pub struct PhotocraftApp {
/// GPU canvas renderer, when running on the wgpu backend (see [`Self::set_wgpu`]). Dropped
/// for the rest of the session when the device is lost (see `gpu_status`).
gpu: Option<gpu_canvas::GpuCanvas>,
+ /// The device the window itself draws with, and its health flag: the GPU canvas's, or one
+ /// watched for the CPU canvas (see `gpu_status::check_window`).
+ window_device: Option<(eframe::wgpu::Device, photocraft_gpu::DeviceHealth)>,
+ /// That device was lost: frames draw nothing and the app is closing (#3438).
+ window_lost: bool,
/// Run once the first frames have rendered (see [`Self::on_started`]).
started: Option<gpu_status::StartedHook>,
/// Frame and canvas-upload timings (exposed via `ui.inspect`).
@@ -976,6 +985,8 @@ impl PhotocraftApp {
doc_hist: None,
hist_job: None,
gpu: None,
+ window_device: None,
+ window_lost: false,
started: None,
perf: Default::default(),
stroke_trace: stroke_trace::StrokeTrace::from_env(),
@@ -1024,10 +1035,12 @@ impl PhotocraftApp {
self.perf.gpu_info.canvas = "cpu".into();
self.perf.gpu_info.fallback = Some(detail.clone());
gpu_status::queue_fallback_notice(self, detail);
+ self.watch_window_device(&rs.device);
return;
}
};
self.perf.gpu_info.canvas = "gpu".into();
+ self.window_device = Some((rs.device.clone(), gpu.health().clone()));
self.gpu = Some(gpu);
self.prefs_rt.gpu_style = None;
}
@@ -1043,6 +1056,24 @@ impl PhotocraftApp {
self.gpu.as_ref().map(|g| g.health().clone())
}
+ /// Watch the device the window draws with when the GPU canvas doesn't (the CPU canvas), so
+ /// its loss is handled like the GPU canvas's (see `gpu_status::check_window`).
+ pub fn watch_window_device(&mut self, device: &eframe::wgpu::Device) {
+ self.window_device = Some((device.clone(), photocraft_gpu::DeviceHealth::watch(device)));
+ }
+
+ /// Whether the window's graphics device was lost, so the app saved its documents for
+ /// recovery and is closing (#3438).
+ pub fn window_lost(&self) -> bool {
+ self.window_lost
+ }
+
+ /// Destroy the window's graphics device, as a driver reset does (`ui.gpu.simulateLoss`
+ /// with `destroy`, tests). Returns whether there was one.
+ pub fn destroy_window_device(&mut self) -> bool {
+ self.window_device.as_ref().map(|(device, _)| device.destroy()).is_some()
+ }
+
/// Run `hook` once the app has rendered its first frames (and a document opened at launch
/// has drawn): the desktop app clears its crash-safe GPU startup marker there.
pub fn on_started(&mut self, hook: impl FnOnce(&mut PhotocraftApp) + 'static) {
@@ -2154,6 +2185,8 @@ impl eframe::App for PhotocraftApp {
jobs_ui::keep_polling(self, &ctx);
// Menus and buttons in this frame may have asked for a file dialog.
self.poll_file_dialog(&ctx, Some(frame));
+ // Last, after everything drawn this frame: a lost window device can't draw it (#3438).
+ gpu_status::check_window(self, &ctx);
}
}
diff --git a/crates/ui-egui/tests/gpu_device_loss.rs b/crates/ui-egui/tests/gpu_device_loss.rs
index ed9626ee2..3a84b96cb 100644
--- a/crates/ui-egui/tests/gpu_device_loss.rs
+++ b/crates/ui-egui/tests/gpu_device_loss.rs
@@ -219,3 +219,77 @@ fn canvas_over_the_texture_budget_builds_no_textures() {
assert!(g.texture_info(key).is_none());
g.release();
}
+
+/// #3438, #1215: when the window's own device is really lost (a driver reset, for example after
+/// the PC slept), egui-wgpu can't draw another frame. One with shapes panicked inside it ("Failed
+/// to create staging buffer for index data"), and a frozen window's close button opened an
+/// unsaved-changes prompt nobody could see. Now the app draws nothing, writes the unsaved document
+/// for recovery and closes. Runs the real frame loop on the harness's own device.
+#[test]
+fn a_lost_window_device_saves_unsaved_work_for_recovery_and_closes() {
+ let _gpu = gpu_lock();
+ let log = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
+ let (autosaves, flushes) = (log.clone(), log.clone());
+ let render_state = std::sync::Arc::new(std::sync::Mutex::new(None::<RenderState>));
+ let window = render_state.clone();
+ let built = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || {
+ egui_kittest::Harness::builder().with_size(egui::vec2(1000.0, 700.0)).with_max_steps(16).wgpu().build_eframe(move |cc| {
+ PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
+ let services = photocraft_ui_egui::Services {
+ autosave: Some(Box::new(move |doc: &std::sync::Arc<Document>, revision: u64, _: Option<&str>| {
+ autosaves.lock().unwrap().push(format!("autosave {} {revision}", doc.id.0));
+ Ok(())
+ })),
+ flush_autosaves: Some(Box::new(move || {
+ flushes.lock().unwrap().push("flush".into());
+ Vec::new()
+ })),
+ ..Default::default()
+ };
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services);
+ if let Some(rs) = cc.wgpu_render_state.as_ref() {
+ *window.lock().unwrap() = Some(rs.clone());
+ app.set_wgpu(rs.clone());
+ }
+ app.run("file.new", json!({"width": 320, "height": 240})).unwrap();
+ app.run("layer.new.layer", json!({})).unwrap();
+ app
+ })
+ }));
+ // Upload and submit the last frame's shapes the way the window's renderer does each frame: on
+ // a lost device, egui-wgpu panics here when there is anything to draw (#1215).
+ let upload = |h: &egui_kittest::Harness<'_, PhotocraftApp>| {
+ let rs = render_state.lock().unwrap().clone().expect("the harness renders with wgpu");
+ let output = h.output();
+ let jobs = h.ctx.tessellate(output.shapes.clone(), output.pixels_per_point);
+ let screen = eframe::egui_wgpu::ScreenDescriptor { size_in_pixels: [1000, 700], pixels_per_point: output.pixels_per_point };
+ let mut encoder = rs.device.create_command_encoder(&Default::default());
+ let uploaded = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ let commands = rs.renderer.write().update_buffers(&rs.device, &rs.queue, &mut encoder, &jobs, &screen);
+ rs.queue.submit(commands.into_iter().chain([encoder.finish()]));
+ }));
+ (jobs.len(), uploaded.is_ok())
+ };
+ let Ok(mut h) = built else {
+ eprintln!("skipping: no GPU adapter");
+ return;
+ };
+ h.run_steps(4);
+ let (jobs, uploaded) = upload(&h);
+ assert!(jobs > 0 && uploaded, "draws before the loss");
+ let (doc, revision, dirty) = h.state().session.active().map(|d| (d.doc.id.0, d.revision, d.is_dirty())).unwrap();
+ assert!(dirty, "the new layer is unsaved");
+ assert!(log.lock().unwrap().is_empty(), "no autosave before the loss");
+ assert!(h.state_mut().destroy_window_device());
+ // wgpu reports a destroyed device lost once the work submitted before finished (slow on a
+ // software adapter); a driver reset reports it at once.
+ if let Some(rs) = render_state.lock().unwrap().as_ref() {
+ let _ = rs.device.poll(eframe::wgpu::PollType::Wait { submission_index: None, timeout: Some(std::time::Duration::from_secs(30)) });
+ }
+ h.run_steps(2);
+ assert!(h.state().window_lost(), "the loss was noticed");
+ assert_eq!(*log.lock().unwrap(), vec![format!("autosave {doc} {revision}"), "flush".to_string()], "saved for recovery once");
+ // The frame on the lost device has nothing to draw, so egui-wgpu has nothing to upload.
+ assert_eq!(upload(&h), (0, true), "a frame with shapes panics inside egui-wgpu on a lost device");
+ assert_eq!(h.state().session.documents().len(), 1, "the document stays until the app closes");
+}
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 15334ac3a..a1c319396 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -82,7 +82,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i
- Engine commands (`engine.execute`, `photocraft-cli run`, MCP `command_run`) reject a param key their `params` doc does not name for the commands listed in `STRICT` (`crates/engine/src/param_check.rs`, today `layer.hideLayers` and `layer.showLayers`): `{"ids":[4]}` is the error `unknown parameter \`ids\` (expected: layer)`, and nothing runs. Other commands still ignore unknown keys until their `params` doc is complete and they are added to that list (`coalesce` and `target` are always accepted).
- `ui.type {text}`: type text (goes to the focused widget, or to the canvas while the Type tool is editing)
- `ui.resize {width, height}`: resize the main window
-- `ui.gpu.simulateLoss {error?}`: act as if the wgpu device was lost (or reported an error with `error: true`). The app switches to the CPU image compositor for the rest of the session and shows the same recovery warning as on a real loss. `gpuFallbackNotice` in `ui.inspect` contains the reason while the warning is open. Keep Using CPU saves CPU compatibility for the next launch; Retry GPU saves GPU mode and asks the user to save and restart. The window renderer still requires a working graphics or software adapter. Returns `wasActive` and `gpuInfo`. For testing the fallback
+- `ui.gpu.simulateLoss {error?}`: act as if the wgpu device was lost (or reported an error with `error: true`). The app switches to the CPU image compositor for the rest of the session and shows the same recovery warning as on a real loss. `gpuFallbackNotice` in `ui.inspect` contains the reason while the warning is open. Keep Using CPU saves CPU compatibility for the next launch; Retry GPU saves GPU mode and asks the user to save and restart. The window renderer still requires a working graphics or software adapter. Returns `wasActive` and `gpuInfo`. For testing the fallback. With `destroy: true` it destroys the window's real wgpu device instead, as a driver reset does (see `docs/development.md` › device loss): the app saves every unsaved document for recovery and closes. Returns `destroyed`
- `ui.screenshot {path?, focus?}`: capture the main window (PNG). With no path the reply contains
base64 PNG data; a path is relative to the automation write root. Raises the window first
(default) because occluded macOS windows stop rendering
diff --git a/docs/development.md b/docs/development.md
index 6891e88a9..c0fcdc947 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -97,6 +97,8 @@ keep the marker for recovery.
If the device is lost while running (#243), every GPU entry point checks the device's health flag first, the canvas switches to the CPU compositor for the rest of the session and a notice says "GPU device was lost; using the CPU renderer." `ui.gpu.simulateLoss` triggers this path from the control channel.
+The window itself draws with the same device (or, with the CPU canvas, one it watches), and nothing can draw it once wgpu reports that device lost, for example after a driver reset while the PC slept (#3438). A frame with shapes then panicked inside egui-wgpu ("Failed to create staging buffer", #1215). A frame without any froze the window, and the close button opened an unsaved-changes prompt nobody could see. `gpu_status::check_window` polls the device each frame. Once wgpu reports it lost, frames draw nothing, every unsaved document is written to crash recovery (`Services::flush_autosaves` waits for the writes), and the app closes; the next launch reopens them. `ui.gpu.simulateLoss {destroy: true}` destroys the real device to test this path.
+
## Logs
The desktop app writes its `log` records to standard error and to `logs/photocraft.log` in the settings directory (Linux `~/.config/photocraft/logs/`, macOS `~/Library/Application Support/Photocraft/logs/`, Windows `%APPDATA%\Photocraft\logs\`, or under `PHOTOCRAFT_CONFIG_DIR` / the portable data folder). A start launched from a desktop menu or the Dock has no terminal, so this file is what to attach to a bug report: GPU startup fallbacks, a lost device and the crash guard's panic report all land there. Each launch moves the previous log to `photocraft.1.log` (and that one to `photocraft.2.log`), so the log of a run that crashed survives the next start. A launch while another PhotoCraft is still running leaves that instance's log where it is and writes its own `photocraft-<pid>.log` next to it (the newest two of those are kept once their instances have exited; the `PhotoCraft <version>, log file <path>` line at startup names the file in use). The file stops growing at 16 MiB. `--version` and command-line errors write no file.