Skip to main content

agentmux_srv/server/service/
session_restore.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Restore-on-relaunch (Feature 1 of
5//! `docs/specs/SPEC_SESSION_RESTORE_AND_SAVED_LAYOUTS_2026_08_13.md`).
6//!
7//! A graceful window close today deliberately cascades a full delete of the
8//! workspace/tabs/blocks (`e3a6f85c2`, wired to the last-window "main" case
9//! by `4cbf856b7` — see `docs/retro/retro-pane-layout-restore-was-a-leak-not-a-feature-2026-08-13.md`),
10//! so the next cold launch always finds `Client.windowids` empty and reseeds
11//! the hardcoded default 3-pane layout (`window_create::default_three_pane_tree`).
12//!
13//! This module adds an independent, durable "what was open last" record —
14//! written just before that destroy cascade runs (`window_close::handle_close_window`)
15//! and consulted by the cold-launch path (`window_create::handle_create_window`)
16//! before it falls back to the hardcoded seed. It deliberately does NOT touch
17//! the destroy cascade itself (that fix is correct and must stay — orphaned
18//! shell processes were the original bug) and does NOT reuse Pillar 1's
19//! crash-reproject machinery (that's scoped to crash-only recovery from rows
20//! a graceful close is specifically supposed to remove — see
21//! `docs/specs/SPEC_PILLAR1_HOST_REPROJECT_DESIGN_2026_06_30.md` §3).
22//!
23//! Stored as a JSON blob under `Client.meta["session:last_topology"]` —
24//! `Client` is already a durable singleton row with a generic `meta` sidecar
25//! (the same "per-entity loosely-typed sidecar" pattern Pillar 1 Step 2 used
26//! for floating-pane placement on `Block.meta`), so this needs no new
27//! `StoreObj` type, table, or migration.
28
29use std::collections::HashMap;
30
31use agentmux_common::ipc::{Command, Event};
32use agentmux_common::LayoutNode;
33use serde_json::{json, Value};
34
35use crate::backend::obj::{Block, Client, LayoutState, Tab, Workspace};
36use crate::backend::service::{WebCallType, WebReturnType};
37use crate::backend::storage::store::Store;
38use crate::server::AppState;
39
40use super::reducer_helpers::{dispatch_to_reducer, seed_layout_via_reducer};
41
42pub(crate) use crate::backend::session_snapshot::{load_last_session_snapshot, save_last_session_snapshot, SNAPSHOT_META_KEY};
43pub(crate) use crate::backend::layout_file::{placeholder, placeholder_idx};
44
45/// Read the given workspace's tabs/blocks/layout directly from the store and
46/// build a durable, block-id-independent snapshot (real block ids are
47/// replaced with positional placeholders — `CreateBlock` always assigns a
48/// fresh id, so the snapshot can never reference one that will exist again).
49/// Returns `None` for an empty/unknown workspace (nothing worth persisting).
50pub(crate) fn snapshot_workspace(store: &Store, workspace_id: &str) -> Option<Value> {
51    let workspace = store.get::<Workspace>(workspace_id).ok().flatten()?;
52    let mut tabs = Vec::new();
53    // Position of `workspace.activetabid` WITHIN the successfully-captured
54    // `tabs` array (reagentx P2 on PR #2560: previously never captured at
55    // all, so a restore always focused whichever tab `CreateTab`'s
56    // first-tab-wins default left active — see `wcore/tab.rs`'s
57    // `ws.activetabid.is_empty()` check). Same "index by position in the
58    // list that actually survived" reasoning as blocks below: if the
59    // originally-active tab is one that fails to load, this simply stays
60    // `None` and restore falls back to whatever `CreateTab` leaves active.
61    let mut active_tab_index: Option<usize> = None;
62    // `pinnedtabids` is a legacy field (pinning was removed from AgentMux —
63    // see `tab_lifecycle.rs`); a workspace the reducer hasn't touched yet
64    // (e.g. straight out of `ensure_initial_data`) can still have its one
65    // tab sitting there instead of in `tabids` until the next
66    // `TabsReorderedBulk` event drains it. Read both so a snapshot taken
67    // before that drain doesn't silently see zero tabs.
68    for tab_id in workspace.pinnedtabids.iter().chain(workspace.tabids.iter()) {
69        let Some(tab) = store.get::<Tab>(tab_id).ok().flatten() else {
70            continue;
71        };
72        // Index by position WITHIN `blocks` (the successfully-loaded list),
73        // not position within `tab.blockids` (the full original list) —
74        // reviewer-caught bug (reagentx P2 on PR #2560): a single unreadable
75        // block previously desynced every subsequent placeholder index
76        // against restore's `new_block_ids` (built from the same
77        // successfully-recreated count), silently misattributing later
78        // blocks' layout positions. `blocks.len()` at insert time is always
79        // this block's actual final position, skipped entries included or
80        // not.
81        let mut idx_by_block_id: HashMap<String, usize> = HashMap::new();
82        let mut blocks = Vec::new();
83        for block_id in &tab.blockids {
84            let Some(block) = store.get::<Block>(block_id).ok().flatten() else {
85                continue;
86            };
87            idx_by_block_id.insert(block_id.clone(), blocks.len());
88            blocks.push(json!({ "meta": block.meta }));
89        }
90        if blocks.is_empty() {
91            continue;
92        }
93        let (rootnode, focusednodeid, magnifiednodeid) = if tab.layoutstate.is_empty() {
94            (None, String::new(), String::new())
95        } else {
96            match store.get::<LayoutState>(&tab.layoutstate) {
97                Ok(Some(layout)) => {
98                    let rootnode = layout.rootnode.map(|mut tree| {
99                        placeholderize(&mut tree, &idx_by_block_id);
100                        tree
101                    });
102                    (rootnode, layout.focusednodeid, layout.magnifiednodeid)
103                }
104                _ => (None, String::new(), String::new()),
105            }
106        };
107        if tab_id == &workspace.activetabid {
108            active_tab_index = Some(tabs.len());
109        }
110        tabs.push(json!({
111            "name": tab.name,
112            "blocks": blocks,
113            "rootnode": rootnode,
114            "focusednodeid": focusednodeid,
115            "magnifiednodeid": magnifiednodeid,
116        }));
117    }
118    if tabs.is_empty() {
119        return None;
120    }
121    let mut snapshot = json!({ "tabs": tabs, "active_tab_index": active_tab_index });
122    // The workspace's name comes back with it (an older record has none).
123    if !workspace.name.trim().is_empty() {
124        snapshot["name"] = json!(workspace.name);
125    }
126    Some(snapshot)
127}
128
129/// Replace every leaf's real block id (in `data.block_id`, `block_stack`,
130/// `active_block_id`) with a positional placeholder, in place.
131fn placeholderize(node: &mut LayoutNode, idx_by_block_id: &HashMap<String, usize>) {
132    if let Some(data) = node.data.as_mut() {
133        if let Some(&idx) = idx_by_block_id.get(&data.block_id) {
134            data.block_id = placeholder(idx);
135        }
136        for id in data.block_stack.iter_mut() {
137            if let Some(&idx) = idx_by_block_id.get(id.as_str()) {
138                *id = placeholder(idx);
139            }
140        }
141        if let Some(&idx) = idx_by_block_id.get(&data.active_block_id) {
142            data.active_block_id = placeholder(idx);
143        }
144    }
145    for child in node.children.iter_mut() {
146        placeholderize(child, idx_by_block_id);
147    }
148}
149
150/// Replace every leaf's positional placeholder with the corresponding freshly
151/// created block id, in place. A placeholder with no matching entry (should
152/// not happen — `new_ids` is built 1:1 from the same snapshot's `blocks`
153/// array — but tolerated defensively) is left as-is; such a leaf simply won't
154/// resolve to a real block and the frontend already handles unknown block ids
155/// in a layout leaf as an empty pane, matching how a manually-crafted or
156/// corrupted layout degrades today.
157fn resolve_placeholders(node: &mut LayoutNode, new_ids: &[String]) {
158    if let Some(data) = node.data.as_mut() {
159        if let Some(idx) = placeholder_idx(&data.block_id) {
160            if let Some(real) = new_ids.get(idx) {
161                data.block_id = real.clone();
162            }
163        }
164        for id in data.block_stack.iter_mut() {
165            if let Some(idx) = placeholder_idx(id) {
166                if let Some(real) = new_ids.get(idx) {
167                    *id = real.clone();
168                }
169            }
170        }
171        if let Some(idx) = placeholder_idx(&data.active_block_id) {
172            if let Some(real) = new_ids.get(idx) {
173                data.active_block_id = real.clone();
174            }
175        }
176    }
177    for child in node.children.iter_mut() {
178        resolve_placeholders(child, new_ids);
179    }
180}
181
182
183
184/// Consume the durable "last session" record after a fully successful
185/// restore (called only once `window_create::handle_create_window`'s final
186/// window read-back succeeds — see that call site's comment for why not any
187/// earlier). Best-effort, same as `save_last_session_snapshot`: a failure to
188/// clear just means a future stray/misused restore call could replay this
189/// snapshot again, which `client_windowids_empty`'s server-side check
190/// (`handle_create_window`) already independently guards against — this is
191/// defense in depth, not the only thing preventing duplicates.
192pub(crate) fn clear_last_session_snapshot(store: &Store) {
193    // Same `with_tx`-atomicity reasoning as `save_last_session_snapshot`
194    // above (reagentx P1 on PR #2560) — this read-then-write was
195    // previously two separate store calls.
196    let result = store.with_tx(|tx| {
197        let clients = tx.get_all::<Client>()?;
198        let Some(mut client) = clients.into_iter().next() else {
199            return Ok(());
200        };
201        if client.meta.remove(SNAPSHOT_META_KEY).is_none() {
202            return Ok(()); // nothing to clear
203        }
204        tx.update(&mut client)?;
205        Ok(())
206    });
207    if let Err(e) = result {
208        tracing::warn!(
209            error = %e,
210            "session_restore: failed to clear last-session snapshot after restore"
211        );
212    }
213}
214
215fn find_error(events: &[Event]) -> Option<String> {
216    events.iter().find_map(|e| match e {
217        Event::Error { message, .. } => Some(message.clone()),
218        _ => None,
219    })
220}
221
222async fn apply_and_publish(
223    state: &AppState,
224    events: &[Event],
225) -> Result<(), String> {
226    for ev in events {
227        if let Err(e) = crate::persist_subscriber::apply_event_to_mstore(ev, &state.mstore) {
228            return Err(format!("SQLite write failed: {}", e));
229        }
230    }
231    Ok(())
232}
233
234/// Snapshot the current session WITHOUT tearing anything down.
235///
236/// This is the OS-shutdown flush point (`SPEC_CONTINUOUS_SESSION_PERSISTENCE_2026_09_08.md`
237/// Phase 0). It exists because the only existing writer of the session
238/// snapshot is `window_close.rs`, gated on the close that empties
239/// `Client.windowids` — so a Windows restart, which terminates the process
240/// without ever calling `CloseWindow`, has always left no snapshot at all and
241/// lost the workspace. Verified against a real incident: the killed
242/// instance's DB had `session:last_topology` absent, `windowids` still
243/// populated, and 22 orphaned blocks.
244///
245/// Deliberately does NOT run `delete_workspace`. The OS is about to reclaim
246/// every process anyway, and that saga's 5s-per-shell `KILL_GRACE_SECS` does
247/// not fit inside the OS's shutdown budget (historically ~5s total, and
248/// Windows kills apps that overstay it). Save, then let the process die.
249///
250/// Takes no window ids: during shutdown the caller is a native wndproc with no
251/// convenient window-id/label mapping in hand, and srv already knows its own
252/// current topology. Captures every live window (`session_windows`), so a
253/// restore after an OS shutdown reconstructs exactly what a restore after a
254/// quit would have.
255///
256/// The host's quit calls it too, with `for_quit` (arg 0) set, before it closes
257/// any window: the record is then marked as a quit's, and the close that
258/// empties `Client.windowids` keeps it (`session_windows::save_on_last_close`).
259///
260/// Idempotent and safe to call repeatedly: it overwrites the same
261/// `Client.meta` key, and a single attempt here never retries or blocks on
262/// failure, so a shutdown flush can never wedge the shutdown it is trying to
263/// protect. That is a statement about *this call itself* staying fast and
264/// single-shot, not about what it reports: unlike the clean-close path,
265/// `save_last_session_snapshot`'s result here IS propagated into the
266/// response (`success: false` on either an unbuildable snapshot or a failed
267/// store write), because the caller — the cef-side shutdown hook — relies on
268/// that to decide whether to re-arm for a genuine retry on the OS's own
269/// second trigger.
270pub(crate) async fn handle_save_session_snapshot(
271    state: &AppState,
272    call: &WebCallType,
273) -> WebReturnType {
274    let store = &state.mstore;
275    let for_quit = crate::backend::service::get_optional_arg::<bool>(&call.args, 0)
276        .ok()
277        .flatten()
278        .unwrap_or(false);
279    // Arg 1 (default true): whether a quit's save also records the agents' background work. A Store
280    // update's save is marked as a quit's (its closes keep the record) but is no quit until the app closes.
281    let run_at_quit = crate::backend::service::get_optional_arg::<bool>(&call.args, 1).ok().flatten().unwrap_or(true);
282    let result = flush_snapshot(store, for_quit);
283    // A quit closes every pane, and with them what agents left running:
284    // record it for their note, and let another AgentMux among it save its
285    // own session first (`background_work`). After this session's own save.
286    if for_quit && run_at_quit {
287        crate::backend::background_work::at_quit().await;
288    }
289    result
290}
291
292/// Save the session now, for a quit or an OS shutdown.
293fn flush_snapshot(store: &Store, for_quit: bool) -> WebReturnType {
294    let why = if for_quit { "quit" } else { "OS shutdown" };
295    if !super::session_windows::has_live_window(store) {
296        // No client, no window, or no workspace — nothing to capture. Not an
297        // error: a shutdown arriving before the first window exists is
298        // ordinary, and reporting failure would only add noise to a path
299        // that runs while the machine is going down.
300        tracing::debug!("session_restore: {why} flush found no workspace to snapshot");
301        return WebReturnType::success_empty();
302    }
303
304    // reagentx P1 on #3106: the cef-side client (helpers.rs) parses this
305    // response's `success` field to decide whether to re-arm its
306    // once-per-attempt flush latch for a genuine retry on
307    // WM_ENDSESSION(TRUE). That only works if this handler actually reports
308    // failure for an application-level failure — `snapshot_workspace`
309    // returning `None`, or the store write inside
310    // `save_last_session_snapshot` failing — not just for the transport-level
311    // failures (connection refused/timeout) the client can already detect on
312    // its own. Both paths below now propagate `success: false` instead of
313    // this handler always claiming success once it started running.
314    match super::session_windows::snapshot_session(store, for_quit) {
315        Some(snapshot) => {
316            let windows = snapshot["windows"].as_array().map_or(1, Vec::len);
317            // The open workspace keeps the same record (`user_workspace`). Its
318            // own result isn't reported: the session record below is what the
319            // shutdown hook's retry is about.
320            super::user_workspace::write_record_now(store, snapshot.clone());
321            if save_last_session_snapshot(store, snapshot) {
322                tracing::info!(windows, "session_restore: snapshot flushed for {why}");
323                WebReturnType::success_empty()
324            } else {
325                // save_last_session_snapshot already logged the specific
326                // store error (or the no-client case) at warn level; no need
327                // to duplicate the detail here.
328                WebReturnType::error("shutdown flush: snapshot built but the store write failed")
329            }
330        }
331        None => {
332            tracing::warn!("session_restore: {why} flush could not build a snapshot of any window");
333            WebReturnType::error("shutdown flush: could not build a snapshot of any window")
334        }
335    }
336}
337
338/// The workspace backing the first of this client's live windows, if any:
339/// the tests' bootstrapped session. The flush itself captures every live
340/// window (`session_windows::snapshot_session`), skipping stale ids the same
341/// way.
342///
343/// Walks `windowids` rather than only checking the first: the repo's own
344/// restart/reprojection paths already tolerate a polluted `windowids` list
345/// (a stale id whose `Window` row no longer exists, or whose `Window` row
346/// exists but references a `Workspace` that's gone), so that state can and
347/// does occur in real persisted data. Bailing out on the first entry alone
348/// — whether it's missing outright or just points at a dead workspace —
349/// would skip the flush entirely whenever that specific entry is stale, even
350/// with a perfectly good workspace sitting at a later id (Codex P2 on
351/// #3106's first fix, then again on the fix itself: the first pass only
352/// checked that the `Window` row existed, not that its `workspaceid` still
353/// resolved to a live `Workspace`).
354#[cfg(test)]
355fn current_workspace_id(store: &Store) -> Option<String> {
356    let client = store.get_all::<Client>().ok()?.into_iter().next()?;
357    client.windowids.iter().find_map(|window_id| {
358        let window = store
359            .get::<crate::backend::obj::Window>(window_id)
360            .ok()
361            .flatten()?;
362        // A live Window row pointing at a dead Workspace is exactly the
363        // shape `shutdown_flush_survives_a_missing_workspace` exercises for
364        // a single window — here it must not stop the search, only rule out
365        // this one candidate.
366        store
367            .get::<Workspace>(&window.workspaceid)
368            .ok()
369            .flatten()?;
370        Some(window.workspaceid)
371    })
372}
373
374/// One tab to rebuild: its blocks' meta, and a split tree whose leaves name
375/// those blocks by position (`placeholder(i)` ↔ `blocks[i]`).
376pub(crate) struct ReplayTab {
377    pub name: String,
378    pub blocks: Vec<Value>,
379    pub rootnode: Option<LayoutNode>,
380    pub focused: String,
381    pub magnified: String,
382}
383
384/// A tab that `replay_tabs` actually rebuilt, with its blocks' new ids in
385/// the order they were created.
386pub(crate) struct ReplayedTab {
387    pub tab_id: String,
388    pub block_ids: Vec<String>,
389}
390
391/// Rebuild `tabs` inside an existing workspace: per tab `CreateTab`, each
392/// block `CreateBlock` (its saved meta), then `LayoutSetTree` with the tree's
393/// placeholders resolved to the new block ids. Shared by restore-on-relaunch
394/// (into a fresh workspace) and `layout.open` (into the current
395/// window's) — `SPEC_LAYOUT_FILES_2026_09_25.md` §1.1.
396///
397/// Per-tab and per-block failures are logged and skipped, never fatal: a
398/// partially-stale input still rebuilds everything else. The returned vector
399/// is parallel to `tabs` (`None` = that tab didn't come back). Events are
400/// applied to the store but **not published** — the caller does that.
401pub(crate) async fn replay_tabs(
402    state: &AppState,
403    ws_id: &str,
404    tabs: &[ReplayTab],
405    log_ctx: &str,
406) -> (Vec<Event>, Vec<Option<ReplayedTab>>) {
407    let mut all_events = Vec::new();
408    let mut replayed = Vec::with_capacity(tabs.len());
409    // Incognito tabs in the replay get fresh jars, within the cap; tabs that
410    // shared one still do.
411    let mut fresh_jars = std::collections::HashMap::new();
412    let jars_available = crate::server::browser_identity::jars_available(state);
413    let profiles = crate::server::browser_identity::profile_ids();
414    for tab in tabs {
415        let tab_events = dispatch_to_reducer(
416            state,
417            Command::CreateTab { workspace_id: ws_id.to_string(), name: tab.name.clone() },
418        )
419        .await;
420        if let Some(err) = find_error(&tab_events) {
421            tracing::warn!(error = %err, "{log_ctx}: CreateTab failed — skipping this tab");
422            replayed.push(None);
423            continue;
424        }
425        if apply_and_publish(state, &tab_events).await.is_err() {
426            tracing::warn!("{log_ctx}: CreateTab SQLite write failed — skipping this tab");
427            replayed.push(None);
428            continue;
429        }
430        let Some(tab_id) = tab_events.iter().find_map(|e| match e {
431            Event::TabCreated { tab_id, .. } => Some(tab_id.clone()),
432            _ => None,
433        }) else {
434            replayed.push(None);
435            continue;
436        };
437        all_events.extend(tab_events);
438
439        let mut new_block_ids: Vec<String> = Vec::new();
440        for meta in &tab.blocks {
441            // A replayed pane is a new pane: not an agent's, not a popup of
442            // a pane that no longer has this id, no banner from before. A
443            // worker stays its leader's (SPEC_AGENT_WORKERS_2026_10_15.md
444            // §3.5): the mark names the leader's definition, which a restore
445            // keeps, and dropping it would let the worker fork and free its
446            // leader's place.
447            let mut meta = meta.clone();
448            if let Some(obj) = meta.as_object_mut() {
449                for key in crate::server::browser_owner::srv_only_keys() {
450                    if key != crate::server::app_api::agent_spawn::COACHED_BY_META_KEY {
451                        obj.remove(key);
452                    }
453                }
454            }
455            if !crate::server::browser_identity::refresh_for_replay(&mut meta, &mut fresh_jars, jars_available, profiles.as_ref()) {
456                continue;
457            }
458            let blk_events = dispatch_to_reducer(
459                state,
460                Command::CreateBlock { tab_id: tab_id.clone(), meta },
461            )
462            .await;
463            if let Some(err) = find_error(&blk_events) {
464                tracing::warn!(error = %err, "{log_ctx}: CreateBlock failed — skipping this block");
465                continue;
466            }
467            if apply_and_publish(state, &blk_events).await.is_err() {
468                tracing::warn!("{log_ctx}: CreateBlock SQLite write failed — skipping this block");
469                continue;
470            }
471            if let Some(block_id) = blk_events.iter().find_map(|e| match e {
472                Event::BlockCreated { block_id, .. } => Some(block_id.clone()),
473                _ => None,
474            }) {
475                new_block_ids.push(block_id);
476            }
477            all_events.extend(blk_events);
478        }
479
480        if new_block_ids.is_empty() {
481            replayed.push(None);
482            continue;
483        }
484
485        if let Some(mut tree) = tab.rootnode.clone() {
486            resolve_placeholders(&mut tree, &new_block_ids);
487            if let Err(e) =
488                seed_layout_via_reducer(state, &tab_id, tree, tab.focused.clone(), tab.magnified.clone())
489                    .await
490            {
491                tracing::warn!(tab_id = %tab_id, error = %e, "{log_ctx}: layout write failed — tab restored blank");
492            }
493        }
494        replayed.push(Some(ReplayedTab { tab_id, block_ids: new_block_ids }));
495    }
496    (all_events, replayed)
497}
498
499/// Restore the last session: every window it holds (`session_windows::restore_all`).
500/// The one returned is for the window being created. A cold start goes
501/// through `user_workspace::restore_at_launch`, which tries this record among
502/// the open workspace's.
503#[cfg(test)]
504pub(crate) async fn restore_last_session(
505    state: &AppState,
506) -> Result<Option<(String, Vec<Event>)>, String> {
507    let Some(snapshot) = load_last_session_snapshot(&state.mstore) else {
508        return Ok(None);
509    };
510    super::session_windows::restore_all(state, &snapshot).await
511}
512
513/// Attempt to replay the durable "last session" snapshot (if any) into a
514/// fresh workspace: `CreateWorkspace` → per-tab `CreateTab` + per-block
515/// `CreateBlock` (reusing each block's saved `meta`, so a restored agent pane
516/// relaunches the same way opening a fresh one does) → `LayoutSetTree` with
517/// the saved split tree (block ids remapped from placeholders to the newly
518/// created ones).
519///
520/// Returns `Ok(None)` when there's nothing to restore (no snapshot, or every
521/// tab in it failed to recreate) — the caller falls back to the hardcoded
522/// default seed exactly as it did before this feature existed. Returns
523/// `Err` only for a failure in the very first step (creating the workspace
524/// itself); per-tab/per-block failures during replay are logged and skipped
525/// rather than aborting the whole restore, so a partially-stale snapshot
526/// (e.g. one tab's block meta no longer makes sense) still restores
527/// everything else instead of failing shut.
528pub(crate) async fn restore_workspace(
529    state: &AppState,
530    snapshot: &Value,
531) -> Result<Option<(String, Vec<Event>)>, String> {
532    let tabs_json = snapshot
533        .get("tabs")
534        .and_then(|v| v.as_array())
535        .cloned()
536        .unwrap_or_default();
537    if tabs_json.is_empty() {
538        return Ok(None);
539    }
540
541    let name = snapshot.get("name").and_then(|v| v.as_str()).unwrap_or_default().to_string();
542    let ws_events = dispatch_to_reducer(state, Command::CreateWorkspace { name }).await;
543    if let Some(err) = find_error(&ws_events) {
544        return Err(format!("restore_last_session: CreateWorkspace failed: {}", err));
545    }
546    apply_and_publish(state, &ws_events).await?;
547    let Some(ws_id) = ws_events.iter().find_map(|e| match e {
548        Event::WorkspaceCreated { workspace_id, .. } => Some(workspace_id.clone()),
549        _ => None,
550    }) else {
551        return Err("restore_last_session: CreateWorkspace produced no WorkspaceCreated event".into());
552    };
553
554    let replay = replay_tabs_of(snapshot);
555    let (tab_events, replayed) = replay_tabs(state, &ws_id, &replay, "restore_last_session").await;
556    let mut all_events = ws_events;
557    all_events.extend(tab_events);
558    let restored_any_tab = replayed.iter().any(Option::is_some);
559    // Maps this tab's position in the ORIGINAL snapshot (`tabs_json`) to its
560    // freshly-created id, for tabs that actually made it through restore —
561    // resolves `active_tab_index` below by position among what survived,
562    // not raw snapshot index (a tab that fails to restore must not desync
563    // this lookup for every tab after it).
564    let new_tab_ids_by_snapshot_index: HashMap<usize, String> = replayed
565        .iter()
566        .enumerate()
567        .filter_map(|(i, r)| r.as_ref().map(|r| (i, r.tab_id.clone())))
568        .collect();
569
570    if !restored_any_tab {
571        // Nothing actually came back (every tab's CreateTab/CreateBlock
572        // failed) — compensate the now-empty workspace so we don't leave a
573        // stray row behind, and let the caller fall back to the default seed.
574        let comp = dispatch_to_reducer(
575            state,
576            Command::DeleteWorkspace { workspace_id: ws_id.clone(), force: false },
577        )
578        .await;
579        let _ = apply_and_publish(state, &comp).await;
580        super::reducer_helpers::publish_events(state, &comp);
581        return Ok(None);
582    }
583
584    all_events.extend(restore_active_tab(state, &ws_id, snapshot, &new_tab_ids_by_snapshot_index).await);
585    // A window rebuilt from its record (a new version's first start) has new contents: its slot follows.
586    if let Some(old) = snapshot.get("workspaceid").and_then(|v| v.as_str()) {
587        super::session_slots::renamed(&state.mstore, old, &ws_id);
588    }
589    Ok(Some((ws_id, all_events)))
590}
591
592/// The tabs of one saved window (`snapshot_workspace`'s shape), ready for
593/// [`replay_tabs`].
594pub(crate) fn replay_tabs_of(snapshot: &Value) -> Vec<ReplayTab> {
595    let tabs_json = snapshot.get("tabs").and_then(|v| v.as_array()).cloned().unwrap_or_default();
596    tabs_json
597        .iter()
598        .map(|tab_json| ReplayTab {
599            name: tab_json.get("name").and_then(|v| v.as_str()).unwrap_or_default().to_string(),
600            blocks: tab_json
601                .get("blocks")
602                .and_then(|v| v.as_array())
603                .map(|blocks| blocks.iter().map(|b| b.get("meta").cloned().unwrap_or(Value::Null)).collect())
604                .unwrap_or_default(),
605            rootnode: tab_json
606                .get("rootnode")
607                .filter(|v| !v.is_null())
608                .and_then(|v| serde_json::from_value::<LayoutNode>(v.clone()).ok()),
609            focused: tab_json.get("focusednodeid").and_then(|v| v.as_str()).unwrap_or_default().to_string(),
610            // `magnifiednodeid` refers to a LayoutNode.id, not a block id —
611            // like `focusednodeid`, it survives the snapshot round-trip
612            // verbatim (only block ids are placeholder-remapped). Previously
613            // never captured/passed at all (reagentx P2 on PR #2560), so a tab
614            // closed with a pane magnified relaunched showing the full tree.
615            magnified: tab_json.get("magnifiednodeid").and_then(|v| v.as_str()).unwrap_or_default().to_string(),
616        })
617        .collect()
618}
619
620/// Make the snapshot's active tab (`active_tab_index`, a position in its
621/// `tabs`) the workspace's active tab, given the new ids of the tabs that came
622/// back by that position. Returns the applied events, unpublished.
623///
624/// Restore which tab was active (reagentx P2 on PR #2560: previously
625/// never captured/restored at all — every relaunch focused whichever tab
626/// `CreateTab`'s own first-tab-wins default (`wcore/tab.rs`) happened to
627/// leave active, i.e. always the first). `None` (no index in the
628/// snapshot, or that index's tab didn't survive restore) leaves that
629/// default in place rather than erroring — an unset/stale active tab is
630/// a cosmetic miss, not a reason to fail the whole restore.
631pub(crate) async fn restore_active_tab(
632    state: &AppState,
633    ws_id: &str,
634    snapshot: &Value,
635    new_tab_ids_by_snapshot_index: &HashMap<usize, String>,
636) -> Vec<Event> {
637    let Some(active_snapshot_idx) = snapshot.get("active_tab_index").and_then(|v| v.as_u64()) else {
638        return Vec::new();
639    };
640    let Some(new_active_tab_id) = new_tab_ids_by_snapshot_index.get(&(active_snapshot_idx as usize)) else {
641        return Vec::new();
642    };
643    let active_events = dispatch_to_reducer(
644        state,
645        Command::SetActiveTab { workspace_id: ws_id.to_string(), tab_id: new_active_tab_id.clone() },
646    )
647    .await;
648    if let Some(err) = find_error(&active_events) {
649        tracing::warn!(error = %err, "restore_last_session: SetActiveTab failed — leaving default active tab");
650        return Vec::new();
651    }
652    if apply_and_publish(state, &active_events).await.is_err() {
653        tracing::warn!("restore_last_session: SetActiveTab SQLite write failed — leaving default active tab");
654        return Vec::new();
655    }
656    active_events
657}
658
659#[cfg(test)]
660mod tests {
661    use super::*;
662    use crate::server::tests::{dispatch_apply, test_state};
663
664    #[tokio::test]
665    async fn no_snapshot_means_nothing_to_load() {
666        let state = test_state();
667        assert!(load_last_session_snapshot(&state.mstore).is_none());
668    }
669
670    #[tokio::test]
671    async fn save_then_load_round_trips() {
672        let state = test_state();
673        let snap = json!({ "tabs": [{"name": "t", "blocks": [{"meta": {"view": "agent"}}]}] });
674        save_last_session_snapshot(&state.mstore, snap.clone());
675        assert_eq!(load_last_session_snapshot(&state.mstore), Some(snap));
676    }
677
678    #[tokio::test]
679    async fn save_overwrites_prior_snapshot() {
680        let state = test_state();
681        save_last_session_snapshot(&state.mstore, json!({"tabs": [{"name": "old"}]}));
682        save_last_session_snapshot(&state.mstore, json!({"tabs": [{"name": "new"}]}));
683        let loaded = load_last_session_snapshot(&state.mstore).unwrap();
684        assert_eq!(loaded["tabs"][0]["name"], "new");
685    }
686
687    #[tokio::test]
688    async fn snapshot_workspace_captures_tab_and_block_meta() {
689        let state = test_state();
690        let ws_evs = dispatch_apply(&state, Command::CreateWorkspace { name: "w".into() }).await;
691        let ws_id = ws_evs
692            .iter()
693            .find_map(|e| match e {
694                Event::WorkspaceCreated { workspace_id, .. } => Some(workspace_id.clone()),
695                _ => None,
696            })
697            .unwrap();
698        let tab_evs = dispatch_apply(
699            &state,
700            Command::CreateTab { workspace_id: ws_id.clone(), name: "mytab".into() },
701        )
702        .await;
703        let tab_id = tab_evs
704            .iter()
705            .find_map(|e| match e {
706                Event::TabCreated { tab_id, .. } => Some(tab_id.clone()),
707                _ => None,
708            })
709            .unwrap();
710        dispatch_apply(
711            &state,
712            Command::CreateBlock {
713                tab_id: tab_id.clone(),
714                meta: json!({ "view": "agent", "agent:name": "test-agent" }),
715            },
716        )
717        .await;
718
719        let snap = snapshot_workspace(&state.mstore, &ws_id).expect("snapshot should be produced");
720        let tabs = snap["tabs"].as_array().unwrap();
721        assert_eq!(tabs.len(), 1);
722        assert_eq!(tabs[0]["name"], "mytab");
723        let blocks = tabs[0]["blocks"].as_array().unwrap();
724        assert_eq!(blocks.len(), 1);
725        assert_eq!(blocks[0]["meta"]["agent:name"], "test-agent");
726    }
727
728    #[tokio::test]
729    async fn snapshot_of_unknown_workspace_is_none() {
730        let state = test_state();
731        assert!(snapshot_workspace(&state.mstore, "no-such-workspace").is_none());
732    }
733
734    #[tokio::test]
735    async fn restore_with_no_snapshot_returns_none() {
736        let state = test_state();
737        let result = restore_last_session(&state).await.unwrap();
738        assert!(result.is_none());
739    }
740
741    #[tokio::test]
742    async fn round_trip_snapshot_then_restore_recreates_tabs_and_blocks() {
743        let state = test_state();
744        let ws_evs = dispatch_apply(&state, Command::CreateWorkspace { name: "w".into() }).await;
745        let ws_id = ws_evs
746            .iter()
747            .find_map(|e| match e {
748                Event::WorkspaceCreated { workspace_id, .. } => Some(workspace_id.clone()),
749                _ => None,
750            })
751            .unwrap();
752        let tab_evs = dispatch_apply(
753            &state,
754            Command::CreateTab { workspace_id: ws_id.clone(), name: "mytab".into() },
755        )
756        .await;
757        let tab_id = tab_evs
758            .iter()
759            .find_map(|e| match e {
760                Event::TabCreated { tab_id, .. } => Some(tab_id.clone()),
761                _ => None,
762            })
763            .unwrap();
764        let blk1 = dispatch_apply(
765            &state,
766            Command::CreateBlock { tab_id: tab_id.clone(), meta: json!({"view": "agent"}) },
767        )
768        .await
769        .iter()
770        .find_map(|e| match e {
771            Event::BlockCreated { block_id, .. } => Some(block_id.clone()),
772            _ => None,
773        })
774        .unwrap();
775        let blk2 = dispatch_apply(
776            &state,
777            Command::CreateBlock { tab_id: tab_id.clone(), meta: json!({"view": "sysinfo"}) },
778        )
779        .await
780        .iter()
781        .find_map(|e| match e {
782            Event::BlockCreated { block_id, .. } => Some(block_id.clone()),
783            _ => None,
784        })
785        .unwrap();
786        // Give the tab a real split layout referencing both blocks.
787        let tree = agentmux_common::LayoutNode {
788            id: "root".into(),
789            flex_direction: agentmux_common::FlexDirection::Row,
790            size: 10.0,
791            children: vec![
792                agentmux_common::LayoutNode {
793                    id: "left".into(),
794                    size: 5.0,
795                    data: Some(agentmux_common::LayoutNodeData { block_id: blk1.clone(), ..Default::default() }),
796                    ..Default::default()
797                },
798                agentmux_common::LayoutNode {
799                    id: "right".into(),
800                    size: 5.0,
801                    data: Some(agentmux_common::LayoutNodeData { block_id: blk2.clone(), ..Default::default() }),
802                    ..Default::default()
803                },
804            ],
805            data: None,
806            minimized: false,
807            extra: Default::default(),
808        };
809        seed_layout_via_reducer(&state, &tab_id, tree, "left".into(), String::new())
810            .await
811            .unwrap();
812
813        // Snapshot + save exactly like the close hook does.
814        let snap = snapshot_workspace(&state.mstore, &ws_id).expect("snapshot should be produced");
815        save_last_session_snapshot(&state.mstore, snap);
816
817        // Restore into a brand-new workspace.
818        let (new_ws_id, _events) = restore_last_session(&state)
819            .await
820            .unwrap()
821            .expect("restore should recreate the tab");
822        assert_ne!(new_ws_id, ws_id, "restore creates a NEW workspace, not the deleted one");
823
824        let new_workspace = state.mstore.get::<Workspace>(&new_ws_id).unwrap().unwrap();
825        assert_eq!(new_workspace.tabids.len(), 1);
826        let new_tab = state.mstore.get::<Tab>(&new_workspace.tabids[0]).unwrap().unwrap();
827        assert_eq!(new_tab.name, "mytab");
828        assert_eq!(new_tab.blockids.len(), 2);
829
830        let new_blk1 = state.mstore.get::<Block>(&new_tab.blockids[0]).unwrap().unwrap();
831        assert_eq!(new_blk1.meta.get("view").and_then(|v| v.as_str()), Some("agent"));
832        let new_blk2 = state.mstore.get::<Block>(&new_tab.blockids[1]).unwrap().unwrap();
833        assert_eq!(new_blk2.meta.get("view").and_then(|v| v.as_str()), Some("sysinfo"));
834
835        // Layout tree was restored with the NEW block ids, not the old ones
836        // or leftover placeholders.
837        let new_layout = state
838            .mstore
839            .get::<LayoutState>(&new_tab.layoutstate)
840            .unwrap()
841            .unwrap();
842        let rootnode = new_layout.rootnode.expect("layout tree restored");
843        let leaf_block_ids: Vec<String> = rootnode
844            .children
845            .iter()
846            .filter_map(|c| c.data.as_ref().map(|d| d.block_id.clone()))
847            .collect();
848        assert_eq!(leaf_block_ids, vec![new_tab.blockids[0].clone(), new_tab.blockids[1].clone()]);
849        assert!(!leaf_block_ids.iter().any(|id| id.starts_with("__snap_block_")));
850    }
851
852    // reagentx P2 on PR #2560: `LayoutState.magnifiednodeid` was never
853    // captured/restored, so a tab closed with a pane magnified always
854    // relaunched showing the full split tree instead of the magnified pane.
855    #[tokio::test]
856    async fn snapshot_and_restore_preserves_magnifiednodeid() {
857        let state = test_state();
858        let ws_evs = dispatch_apply(&state, Command::CreateWorkspace { name: "w".into() }).await;
859        let ws_id = ws_evs
860            .iter()
861            .find_map(|e| match e {
862                Event::WorkspaceCreated { workspace_id, .. } => Some(workspace_id.clone()),
863                _ => None,
864            })
865            .unwrap();
866        let tab_evs = dispatch_apply(
867            &state,
868            Command::CreateTab { workspace_id: ws_id.clone(), name: "mytab".into() },
869        )
870        .await;
871        let tab_id = tab_evs
872            .iter()
873            .find_map(|e| match e {
874                Event::TabCreated { tab_id, .. } => Some(tab_id.clone()),
875                _ => None,
876            })
877            .unwrap();
878        let blk1 = dispatch_apply(
879            &state,
880            Command::CreateBlock { tab_id: tab_id.clone(), meta: json!({"view": "agent"}) },
881        )
882        .await
883        .iter()
884        .find_map(|e| match e {
885            Event::BlockCreated { block_id, .. } => Some(block_id.clone()),
886            _ => None,
887        })
888        .unwrap();
889        let blk2 = dispatch_apply(
890            &state,
891            Command::CreateBlock { tab_id: tab_id.clone(), meta: json!({"view": "sysinfo"}) },
892        )
893        .await
894        .iter()
895        .find_map(|e| match e {
896            Event::BlockCreated { block_id, .. } => Some(block_id.clone()),
897            _ => None,
898        })
899        .unwrap();
900        let tree = agentmux_common::LayoutNode {
901            id: "root".into(),
902            flex_direction: agentmux_common::FlexDirection::Row,
903            size: 10.0,
904            children: vec![
905                agentmux_common::LayoutNode {
906                    id: "left".into(),
907                    size: 5.0,
908                    data: Some(agentmux_common::LayoutNodeData { block_id: blk1.clone(), ..Default::default() }),
909                    ..Default::default()
910                },
911                agentmux_common::LayoutNode {
912                    id: "right".into(),
913                    size: 5.0,
914                    data: Some(agentmux_common::LayoutNodeData { block_id: blk2.clone(), ..Default::default() }),
915                    ..Default::default()
916                },
917            ],
918            data: None,
919            minimized: false,
920            extra: Default::default(),
921        };
922        // "left" pane is magnified.
923        seed_layout_via_reducer(&state, &tab_id, tree, "left".into(), "left".into())
924            .await
925            .unwrap();
926
927        let snap = snapshot_workspace(&state.mstore, &ws_id).expect("snapshot should be produced");
928        assert_eq!(snap["tabs"][0]["magnifiednodeid"], "left", "magnifiednodeid captured in snapshot");
929        save_last_session_snapshot(&state.mstore, snap);
930
931        let (new_ws_id, _events) = restore_last_session(&state).await.unwrap().unwrap();
932        let new_workspace = state.mstore.get::<Workspace>(&new_ws_id).unwrap().unwrap();
933        let new_tab = state.mstore.get::<Tab>(&new_workspace.tabids[0]).unwrap().unwrap();
934        let new_layout = state.mstore.get::<LayoutState>(&new_tab.layoutstate).unwrap().unwrap();
935        assert_eq!(
936            new_layout.magnifiednodeid, "left",
937            "magnifiednodeid restored — LayoutNode.id values aren't placeholder-remapped, \
938             only block ids are, so this survives verbatim"
939        );
940    }
941
942    // reagentx P2 on PR #2560: `Workspace.activetabid` was never
943    // captured/restored, so a relaunch always focused the first tab
944    // regardless of which was actually active at close.
945    #[tokio::test]
946    async fn snapshot_and_restore_preserves_active_tab_when_not_the_first() {
947        let state = test_state();
948        let ws_evs = dispatch_apply(&state, Command::CreateWorkspace { name: "w".into() }).await;
949        let ws_id = ws_evs
950            .iter()
951            .find_map(|e| match e {
952                Event::WorkspaceCreated { workspace_id, .. } => Some(workspace_id.clone()),
953                _ => None,
954            })
955            .unwrap();
956
957        // tab1 is created first (and would be the default active tab per
958        // wcore/tab.rs's first-tab-wins rule) but tab2 is the one the user
959        // actually left active.
960        let tab1_evs = dispatch_apply(
961            &state,
962            Command::CreateTab { workspace_id: ws_id.clone(), name: "tab-one".into() },
963        )
964        .await;
965        let tab1_id = tab1_evs
966            .iter()
967            .find_map(|e| match e {
968                Event::TabCreated { tab_id, .. } => Some(tab_id.clone()),
969                _ => None,
970            })
971            .unwrap();
972        dispatch_apply(
973            &state,
974            Command::CreateBlock { tab_id: tab1_id.clone(), meta: json!({"view": "agent"}) },
975        )
976        .await;
977
978        let tab2_evs = dispatch_apply(
979            &state,
980            Command::CreateTab { workspace_id: ws_id.clone(), name: "tab-two".into() },
981        )
982        .await;
983        let tab2_id = tab2_evs
984            .iter()
985            .find_map(|e| match e {
986                Event::TabCreated { tab_id, .. } => Some(tab_id.clone()),
987                _ => None,
988            })
989            .unwrap();
990        dispatch_apply(
991            &state,
992            Command::CreateBlock { tab_id: tab2_id.clone(), meta: json!({"view": "sysinfo"}) },
993        )
994        .await;
995
996        dispatch_apply(
997            &state,
998            Command::SetActiveTab { workspace_id: ws_id.clone(), tab_id: tab2_id.clone() },
999        )
1000        .await;
1001        let workspace_before = state.mstore.get::<Workspace>(&ws_id).unwrap().unwrap();
1002        assert_eq!(workspace_before.activetabid, tab2_id, "precondition: tab-two is active");
1003
1004        let snap = snapshot_workspace(&state.mstore, &ws_id).expect("snapshot should be produced");
1005        assert_eq!(snap["active_tab_index"], 1, "active tab is the SECOND captured tab");
1006        save_last_session_snapshot(&state.mstore, snap);
1007
1008        let (new_ws_id, _events) = restore_last_session(&state).await.unwrap().unwrap();
1009        let new_workspace = state.mstore.get::<Workspace>(&new_ws_id).unwrap().unwrap();
1010        assert_eq!(new_workspace.tabids.len(), 2);
1011        let new_tab2 = state.mstore.get::<Tab>(&new_workspace.tabids[1]).unwrap().unwrap();
1012        assert_eq!(new_tab2.name, "tab-two");
1013        assert_eq!(
1014            new_workspace.activetabid, new_tab2.oid,
1015            "the restored workspace's active tab is the NEW tab-two, not whichever \
1016             CreateTab's first-tab-wins default would otherwise leave active"
1017        );
1018    }
1019
1020    /// A restored worker is still its leader's; a restored browser pane is
1021    /// no longer an agent's.
1022    #[tokio::test]
1023    async fn a_restored_worker_keeps_its_leaders_mark() {
1024        use crate::server::app_api::agent_spawn::COACHED_BY_META_KEY;
1025        use crate::server::browser_owner::OWNER_META_KEY;
1026        let state = test_state();
1027        let ws_id = dispatch_apply(&state, Command::CreateWorkspace { name: "w".into() })
1028            .await
1029            .iter()
1030            .find_map(|e| match e {
1031                Event::WorkspaceCreated { workspace_id, .. } => Some(workspace_id.clone()),
1032                _ => None,
1033            })
1034            .unwrap();
1035        let tab_id = dispatch_apply(&state, Command::CreateTab { workspace_id: ws_id.clone(), name: "t".into() })
1036            .await
1037            .iter()
1038            .find_map(|e| match e {
1039                Event::TabCreated { tab_id, .. } => Some(tab_id.clone()),
1040                _ => None,
1041            })
1042            .unwrap();
1043        let mark = json!({ "agent": "Lead", "id": "lead-def", "block_id": "lead-pane" });
1044        let meta = json!({ "view": "agent", COACHED_BY_META_KEY: mark, OWNER_META_KEY: "lead" });
1045        dispatch_apply(&state, Command::CreateBlock { tab_id, meta }).await;
1046        let snap = snapshot_workspace(&state.mstore, &ws_id).unwrap();
1047        save_last_session_snapshot(&state.mstore, snap);
1048
1049        let (new_ws_id, _) = restore_last_session(&state).await.unwrap().unwrap();
1050        let new_ws = state.mstore.get::<Workspace>(&new_ws_id).unwrap().unwrap();
1051        let new_tab = state.mstore.get::<Tab>(&new_ws.tabids[0]).unwrap().unwrap();
1052        let block = state.mstore.get::<Block>(&new_tab.blockids[0]).unwrap().unwrap();
1053        assert_eq!(block.meta.get(COACHED_BY_META_KEY), Some(&mark));
1054        assert!(block.meta.get(OWNER_META_KEY).is_none());
1055    }
1056
1057    #[tokio::test]
1058    async fn restore_is_idempotent_source_snapshot_survives() {
1059        // A second restore attempt (e.g. the app crashed mid-restore and
1060        // relaunched again) must still find and replay the same snapshot —
1061        // restoring does not consume/clear it.
1062        let state = test_state();
1063        let ws_evs = dispatch_apply(&state, Command::CreateWorkspace { name: "w".into() }).await;
1064        let ws_id = ws_evs
1065            .iter()
1066            .find_map(|e| match e {
1067                Event::WorkspaceCreated { workspace_id, .. } => Some(workspace_id.clone()),
1068                _ => None,
1069            })
1070            .unwrap();
1071        let tab_evs = dispatch_apply(
1072            &state,
1073            Command::CreateTab { workspace_id: ws_id.clone(), name: "t".into() },
1074        )
1075        .await;
1076        let tab_id = tab_evs
1077            .iter()
1078            .find_map(|e| match e {
1079                Event::TabCreated { tab_id, .. } => Some(tab_id.clone()),
1080                _ => None,
1081            })
1082            .unwrap();
1083        dispatch_apply(
1084            &state,
1085            Command::CreateBlock { tab_id: tab_id.clone(), meta: json!({"view": "agent"}) },
1086        )
1087        .await;
1088        let snap = snapshot_workspace(&state.mstore, &ws_id).unwrap();
1089        save_last_session_snapshot(&state.mstore, snap);
1090
1091        let (first_ws, _) = restore_last_session(&state).await.unwrap().unwrap();
1092        let (second_ws, _) = restore_last_session(&state).await.unwrap().unwrap();
1093        assert_ne!(first_ws, second_ws, "each restore call creates its own fresh workspace");
1094        assert!(state.mstore.get::<Workspace>(&first_ws).unwrap().is_some());
1095        assert!(state.mstore.get::<Workspace>(&second_ws).unwrap().is_some());
1096    }
1097
1098
1099    // --- Phase 0: OS-shutdown snapshot flush ---------------------------------
1100    // SPEC_CONTINUOUS_SESSION_PERSISTENCE_2026_09_08.md
1101
1102    fn shutdown_call() -> WebCallType {
1103        WebCallType {
1104            service: "window".to_string(),
1105            method: "SaveSessionSnapshot".to_string(),
1106            args: vec![],
1107            uicontext: None,
1108        }
1109    }
1110
1111    /// The workspace the shutdown flush will actually capture: the one behind
1112    /// the client's FIRST window. `test_state()` bootstraps a client, window,
1113    /// workspace and a default tab via `ensure_initial_data`, so this is the
1114    /// bootstrapped session rather than anything the test invents — which is
1115    /// the point, since it mirrors what a real running instance looks like.
1116    fn bootstrapped_workspace(state: &AppState) -> String {
1117        current_workspace_id(&state.mstore).expect("test_state seeds a live session")
1118    }
1119
1120    /// The whole point of Phase 0: an OS shutdown captures the session even
1121    /// though `CloseWindow` never runs. Before this, a restart left
1122    /// `session:last_topology` absent and the workspace was lost — confirmed
1123    /// against a real incident (§1.1 of the spec), where the killed instance's
1124    /// DB had the key missing, `windowids` still populated, and 22 orphaned
1125    /// blocks.
1126    ///
1127    /// Asserts against the bootstrapped session rather than a test-built one:
1128    /// `ensure_initial_data` seeds the store directly, so the reducer has no
1129    /// knowledge of that workspace and reducer-routed `CreateTab` cannot add
1130    /// to it. That divergence is a property of the test harness, not of the
1131    /// shutdown path — and the bootstrapped session is a faithful stand-in for
1132    /// what a real instance has open.
1133    #[tokio::test]
1134    async fn shutdown_flush_writes_a_snapshot_without_a_close() {
1135        let state = test_state();
1136        let ws_id = bootstrapped_workspace(&state);
1137        let ws = state.mstore.get::<Workspace>(&ws_id).unwrap().unwrap();
1138        // Count BOTH lists: a workspace the reducer has not touched yet
1139        // (straight out of `ensure_initial_data`) still has its tab in the
1140        // legacy `pinnedtabids` until a `TabsReorderedBulk` drains it — which
1141        // is exactly why `snapshot_workspace` reads both (see its loop).
1142        let open_tabs = ws.pinnedtabids.len() + ws.tabids.len();
1143        assert!(open_tabs > 0, "precondition: the session has a tab open");
1144        assert!(
1145            load_last_session_snapshot(&state.mstore).is_none(),
1146            "precondition: nothing saved before the flush"
1147        );
1148
1149        handle_save_session_snapshot(&state, &shutdown_call()).await;
1150
1151        let snap = load_last_session_snapshot(&state.mstore)
1152            .expect("shutdown flush must persist a snapshot with no CloseWindow");
1153        let tabs = snap["tabs"].as_array().expect("snapshot carries a tabs array");
1154        assert_eq!(
1155            tabs.len(),
1156            open_tabs,
1157            "every open tab must be captured, not just the active one"
1158        );
1159    }
1160
1161    /// Phase 0 must NOT tear down. The OS is about to reclaim everything, and
1162    /// `delete_workspace`'s per-shell grace does not fit the shutdown budget —
1163    /// running it would risk being killed mid-cascade for no benefit.
1164    #[tokio::test]
1165    async fn shutdown_flush_leaves_the_workspace_intact() {
1166        let state = test_state();
1167        let ws_id = bootstrapped_workspace(&state);
1168        let before = state.mstore.get::<Workspace>(&ws_id).unwrap().unwrap();
1169
1170        handle_save_session_snapshot(&state, &shutdown_call()).await;
1171
1172        let after = state
1173            .mstore
1174            .get::<Workspace>(&ws_id)
1175            .unwrap()
1176            .expect("shutdown flush must not delete the workspace");
1177        assert_eq!(
1178            (before.pinnedtabids, before.tabids),
1179            (after.pinnedtabids, after.tabids),
1180            "tabs must survive the flush untouched"
1181        );
1182    }
1183
1184    /// Repeated flushes are safe. The cef-side hook dedupes process-wide, but
1185    /// both `WM_QUERYENDSESSION` and `WM_ENDSESSION` can fire, and a
1186    /// cancelled-then-real shutdown produces two rounds — so the server side
1187    /// must tolerate it rather than rely on the caller being careful.
1188    #[tokio::test]
1189    async fn shutdown_flush_is_idempotent() {
1190        let state = test_state();
1191        let _ = bootstrapped_workspace(&state);
1192
1193        handle_save_session_snapshot(&state, &shutdown_call()).await;
1194        let first = load_last_session_snapshot(&state.mstore).unwrap();
1195        handle_save_session_snapshot(&state, &shutdown_call()).await;
1196        let second = load_last_session_snapshot(&state.mstore).unwrap();
1197
1198        assert_eq!(first, second, "a second flush must not corrupt the snapshot");
1199    }
1200
1201    /// Defensive path: the client's window points at a workspace that is gone.
1202    /// "Survives" means the handler returns promptly with no panic and no
1203    /// partial/corrupt write. Final reasoning, after two rounds of revision
1204    /// on #3106 (see git history if the "why" ever seems arbitrary):
1205    ///
1206    /// A single window whose workspace is dead is now caught by
1207    /// `current_workspace_id` itself (`shutdown_flush_skips_a_window_whose_
1208    /// workspace_is_gone`'s fix) — it's no longer "found a workspace id that
1209    /// then failed to snapshot," it's "found no live workspace among any
1210    /// window," the exact same bucket as
1211    /// `shutdown_flush_with_no_window_at_all_is_not_an_error`. Retrying a
1212    /// genuinely-deleted workspace can't produce a different outcome, so
1213    /// treating this as ordinary (not a failure worth the retry logic
1214    /// acting on) is correct, not a gap: the two tests are no longer "two
1215    /// sides of a fork," they're two different inputs that correctly
1216    /// converge on the same output.
1217    #[tokio::test]
1218    async fn shutdown_flush_survives_a_missing_workspace() {
1219        let state = test_state();
1220        let ws_id = bootstrapped_workspace(&state);
1221        state.mstore.delete::<Workspace>(&ws_id).unwrap();
1222
1223        let ret = handle_save_session_snapshot(&state, &shutdown_call()).await;
1224
1225        assert!(
1226            ret.error.is_none(),
1227            "no live workspace among any window is ordinary, not a failure"
1228        );
1229        assert!(
1230            load_last_session_snapshot(&state.mstore).is_none(),
1231            "nothing capturable means nothing written — not a partial snapshot"
1232        );
1233    }
1234
1235    /// The failure path `handle_save_session_snapshot` actually exists to
1236    /// report (reagentx P1): `current_workspace_id` finds a genuinely live
1237    /// window+workspace, but `snapshot_workspace` still can't build anything
1238    /// from it — every tab it walked was skipped (here: a tab with zero
1239    /// blocks, `snapshot_workspace`'s own `if blocks.is_empty() { continue }`
1240    /// followed by `if tabs.is_empty() { return None }`). Unlike the two
1241    /// tests above, this is NOT "nothing exists" — a real workspace is
1242    /// sitting right there — so this is exactly the "something existed but
1243    /// couldn't be captured" case the retry logic is meant to act on, and it
1244    /// must report failure.
1245    #[tokio::test]
1246    async fn shutdown_flush_reports_failure_when_the_workspace_has_no_capturable_tabs() {
1247        let state = test_state();
1248        let ws_id = bootstrapped_workspace(&state);
1249        let workspace = state.mstore.get::<Workspace>(&ws_id).unwrap().unwrap();
1250        for tab_id in workspace.pinnedtabids.iter().chain(workspace.tabids.iter()) {
1251            let mut tab = state.mstore.get::<Tab>(tab_id).unwrap().unwrap();
1252            for block_id in tab.blockids.drain(..) {
1253                let _ = state.mstore.delete::<Block>(&block_id);
1254            }
1255            state.mstore.update(&mut tab).unwrap();
1256        }
1257
1258        let ret = handle_save_session_snapshot(&state, &shutdown_call()).await;
1259
1260        assert!(
1261            ret.error.is_some(),
1262            "a live workspace with nothing capturable in it must report failure, not silent success"
1263        );
1264        assert!(
1265            load_last_session_snapshot(&state.mstore).is_none(),
1266            "nothing capturable means nothing written — not a partial snapshot"
1267        );
1268    }
1269
1270    /// A shutdown arriving before the first window exists at all (no
1271    /// client, or a client with no live window) is ordinary, not a failure —
1272    /// reporting error here would just be noise on every fresh launch that
1273    /// happens to shut down early. Same outcome and same reasoning as
1274    /// `shutdown_flush_survives_a_missing_workspace` now that
1275    /// `current_workspace_id` filters dead-workspace windows itself — kept
1276    /// as its own test anyway so a future change to either input shape is
1277    /// still checked independently.
1278    #[tokio::test]
1279    async fn shutdown_flush_with_no_window_at_all_is_not_an_error() {
1280        let state = test_state();
1281        let _ = bootstrapped_workspace(&state);
1282        let window_id = state
1283            .mstore
1284            .get_all::<Client>()
1285            .unwrap()
1286            .into_iter()
1287            .next()
1288            .unwrap()
1289            .windowids
1290            .first()
1291            .cloned()
1292            .expect("test_state seeds exactly one window");
1293        state
1294            .mstore
1295            .delete::<crate::backend::obj::Window>(&window_id)
1296            .unwrap();
1297
1298        let ret = handle_save_session_snapshot(&state, &shutdown_call()).await;
1299
1300        assert!(
1301            ret.error.is_none(),
1302            "no window to resolve a workspace from is ordinary, not a failure"
1303        );
1304        assert!(
1305            load_last_session_snapshot(&state.mstore).is_none(),
1306            "nothing was captured, so nothing should be written"
1307        );
1308    }
1309
1310    /// reagentx/Codex P2 on #3106: `current_workspace_id` used to check only
1311    /// `windowids[0]` and give up entirely if that one row was stale, even
1312    /// with a perfectly good workspace behind a later entry. The repo's own
1313    /// restart/reprojection paths already tolerate a polluted `windowids`
1314    /// list, so this is real reachable state, not a hypothetical.
1315    #[tokio::test]
1316    async fn shutdown_flush_skips_a_stale_leading_window_id() {
1317        let state = test_state();
1318        let ws_id = bootstrapped_workspace(&state);
1319
1320        // Prepend a window id with no backing Window row — the exact
1321        // "stale leading entry" shape the finding describes.
1322        let mut client = state
1323            .mstore
1324            .get_all::<Client>()
1325            .unwrap()
1326            .into_iter()
1327            .next()
1328            .unwrap();
1329        client
1330            .windowids
1331            .insert(0, "stale-window-id-no-row".to_string());
1332        state.mstore.update(&mut client).unwrap();
1333
1334        let ret = handle_save_session_snapshot(&state, &shutdown_call()).await;
1335
1336        assert!(
1337            ret.error.is_none(),
1338            "a stale leading window id must not fail the whole flush"
1339        );
1340        let snapshot = load_last_session_snapshot(&state.mstore)
1341            .expect("the live workspace behind the second window id must still be captured");
1342        let expected = snapshot_workspace(&state.mstore, &ws_id)
1343            .expect("the real workspace is independently snapshot-able");
1344        // The record holds every window; at its top level, the main one's.
1345        assert_eq!(
1346            super::super::session_windows::windows_of(&snapshot).len(),
1347            1,
1348            "only the live window is saved"
1349        );
1350        let mut top = snapshot;
1351        top.as_object_mut().unwrap().remove("windows");
1352        // It names the workspace, which the close keeps for the restore.
1353        assert_eq!(top.as_object_mut().unwrap().remove("workspaceid"), Some(json!(ws_id)));
1354        assert_eq!(
1355            top, expected,
1356            "must resolve to and capture the real workspace, not silently skip it"
1357        );
1358    }
1359
1360    /// Codex's follow-up P2 on the fix above: a stale *entry* isn't only "no
1361    /// `Window` row at all" — a `Window` row can exist and be perfectly
1362    /// readable while its `workspaceid` points at a `Workspace` that's gone
1363    /// (exactly the single-window shape
1364    /// `shutdown_flush_survives_a_missing_workspace` exercises). The first
1365    /// pass at walking `windowids` only checked that the `Window` row
1366    /// existed, so it would accept that dead workspace id as the answer and
1367    /// stop, even with a live workspace behind a later window.
1368    #[tokio::test]
1369    async fn shutdown_flush_skips_a_window_whose_workspace_is_gone() {
1370        let state = test_state();
1371        let live_ws_id = bootstrapped_workspace(&state);
1372
1373        let mut client = state
1374            .mstore
1375            .get_all::<Client>()
1376            .unwrap()
1377            .into_iter()
1378            .next()
1379            .unwrap();
1380        let live_window_id = client
1381            .windowids
1382            .first()
1383            .cloned()
1384            .expect("test_state seeds exactly one window");
1385
1386        // A second Window row, readable and legitimate, pointing at a
1387        // workspace id that was never created — indistinguishable from one
1388        // that existed and was later deleted, which is the real-world shape
1389        // this guards against.
1390        let mut dead_window = crate::backend::obj::Window {
1391            oid: "dead-window-with-deleted-workspace".to_string(),
1392            workspaceid: "workspace-that-was-deleted".to_string(),
1393            ..Default::default()
1394        };
1395        state.mstore.insert(&mut dead_window).unwrap();
1396
1397        // Leading: the resolver must not stop here.
1398        client.windowids.insert(0, dead_window.oid.clone());
1399        state.mstore.update(&mut client).unwrap();
1400
1401        let ret = handle_save_session_snapshot(&state, &shutdown_call()).await;
1402
1403        assert!(
1404            ret.error.is_none(),
1405            "a dead-workspace window must not fail the whole flush when a live one follows"
1406        );
1407        let snapshot = load_last_session_snapshot(&state.mstore)
1408            .expect("the live workspace behind the second window must still be captured");
1409        let expected = snapshot_workspace(&state.mstore, &live_ws_id)
1410            .expect("the real workspace is independently snapshot-able");
1411        // The record holds every window; at its top level, the main one's.
1412        assert_eq!(
1413            super::super::session_windows::windows_of(&snapshot).len(),
1414            1,
1415            "only the live window is saved"
1416        );
1417        let mut top = snapshot;
1418        top.as_object_mut().unwrap().remove("windows");
1419        // It names the workspace, which the close keeps for the restore.
1420        assert_eq!(top.as_object_mut().unwrap().remove("workspaceid"), Some(json!(live_ws_id)));
1421        assert_eq!(
1422            top, expected,
1423            "must resolve to and capture the live workspace, not the dead one it's paired with"
1424        );
1425        // Sanity: prove the two windows really do disagree, so a bug that
1426        // silently ignored windowids order couldn't pass by accident.
1427        assert_ne!(live_window_id, dead_window.oid);
1428    }
1429}