Files
AFFiNE/packages/frontend/mobile/tests/mobile_shell_e2e/sqlite_bridge.rs
T
DarkSky af83a5a38c perf(mobile): mount visible explorer rows and drop deleted documents
The mobile shell now removes a document when the document leaves the root document in the workspace session. Another session can trash and delete a document permanently. The shell then drops it from the list, the CRDT cache, the history, and the open page. Drafts that exist only in the shell stay. Documents with the same ID in other workspaces stay.

Workspace documents and CRDT caches change only through accessors. Each change gets a revision stamp that is unique in the process. These stamps key the caches for search hits, drawer sections, Explorer rows, breadcrumb snapshots, and the editor directory. A frame without changes rebuilds none of them.

A document lookup by ID now takes constant time. Explorer lists and folder lists mount only the rows inside the viewport plus a small overscan. The lists use ui_kit::VirtualList, and spacers keep the content height. The accessibility tree reads the same rows and the same window.

The bridge syncs the shell to the session by CRDT revision and by changed document IDs. When nothing changed, it reads no cached bytes. The sync timer repaints the shell only when the projection changed what the shell shows. The timer also checks that the bridge that ran the tick is still bound.

The editor directory keys its snapshot by workspace ID, docs revision, bulk revision, and locale. It refreshes in place only when all keys except the docs revision match. A workspace switch, a bulk change, or a locale change rebuilds it. The directory never lists or previews a trashed document.

The page editor reads the trash state directly. It encodes a state vector only when the document revision advances. The Explorer shows the empty trash text only for the trash target. A pending delete confirmation closes only for a document of the active workspace.

The views share one row_dir helper. The palette reads typed theme fields, and pure white uses ui::white(). The mobile-harness scale-probe command reports frame costs and work counts with 10, 100, and 1,000 documents. The invariants script checks mobile views for test branches. It links the ui-tokens test executable for the linker flag check.
2026-12-02 05:41:17 +09:00

571 lines
21 KiB
Rust

//! SQLite WAL persistence and embedded editor bridge integration tests.
use affine_client::HostKind;
use affine_mobile::{
MobileLocale, MobileRoute, MobileShellView, MobileWorkspaceBridge, register_mobile_fonts,
seed_showcase_state,
};
use ui::{
Application, Bounds, HeadlessPlatform, WindowBounds, WindowHandle, WindowOptions, point,
prelude::*, px, size,
};
use ui_tokens::ThemeMode;
#[cfg(not(target_family = "wasm"))]
#[tokio::test]
async fn bridge_open_document_preserves_embedded_editor_edits_and_persists_to_sqlite() {
use affine_client::{HostKind, SqliteWorkspaceStore};
use affine_mobile::MobileWorkspaceBridge;
use blocksuite_playground_doc::{
read::BlockContent,
schema::{BlockSpec, ParagraphType},
};
use ui::{
Application, Bounds, HeadlessPlatform, WindowBounds, WindowHandle, WindowOptions, point,
prelude::*, px, size,
};
let base_dir =
std::env::temp_dir().join(format!("affine-mobile-bridge-e2e-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base_dir);
std::fs::create_dir_all(&base_dir).unwrap();
let store = SqliteWorkspaceStore::open(&base_dir, "workspace", "local", "ws-bridge-e2e")
.await
.unwrap();
let session = store
.load_workspace_session(
"u-bridge",
8080,
HostKind::Native,
"local",
"https://app.affine.pro",
1_000,
)
.await
.unwrap();
let mut bridge = MobileWorkspaceBridge::new(session);
let mut state = seed_showcase_state(MobileLocale::En, ThemeMode::Light, "2026-11-28");
let (doc_a, pending_a) = bridge
.create_and_open_document(&mut state, "Doc A", None, 1_100)
.unwrap();
store
.persist_pending_updates(&pending_a, None, 1_100)
.await
.unwrap();
let (doc_b, pending_b) = bridge
.create_and_open_document(&mut state, "Doc B", None, 1_200)
.unwrap();
store
.persist_pending_updates(&pending_b, None, 1_200)
.await
.unwrap();
let doc_a_id = doc_a.id.as_str().to_string();
let doc_b_id = doc_b.id.as_str().to_string();
bridge
.open_document(&mut state, &doc_a_id, 1_700_000_000_000)
.unwrap();
let platform = HeadlessPlatform::new(390, 844, 1.0);
let handle_cell: std::rc::Rc<std::cell::RefCell<Option<WindowHandle<MobileShellView>>>> =
std::rc::Rc::new(std::cell::RefCell::new(None));
let handle_out = handle_cell.clone();
let app = Application::with_platform(platform.clone()).run_embedded(move |cx| {
register_mobile_fonts(cx).expect("register mobile fonts");
let win = cx
.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(Bounds::new(
point(px(0.0), px(0.0)),
size(px(390.0), px(844.0)),
))),
..WindowOptions::default()
},
|_, cx| cx.new(|cx| MobileShellView::new(state, cx)),
)
.expect("open mobile window");
*handle_out.borrow_mut() = Some(win);
});
let window_handle = handle_cell.borrow_mut().take().unwrap();
let headless_win = platform.windows().into_iter().next().unwrap();
headless_win.request_frame();
platform.run_until_parked();
// Edit doc-a inside the embedded PlaygroundView (including a nested child block).
app.update(|cx| {
window_handle
.update(cx, |v, _, cx| {
let editor = v.page_editor().expect("embedded PlaygroundView").clone();
editor.update(cx, |pv, cx| {
pv.edit_document(cx, |ds| {
let page = ds.workspace.page_mut(&doc_a_id).unwrap();
let note_id = page
.read_page_snapshot()
.unwrap()
.root
.as_ref()
.unwrap()
.children
.iter()
.find(|n| n.is_page_visible_note())
.unwrap()
.id
.clone();
page.add_block(
"p-edited",
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: "EDITED_IN_EMBEDDED_EDITOR".into(),
},
Some(&note_id),
None,
2_000,
)
.unwrap();
page.add_block(
"p-nested",
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: "NESTED_CHILD_BLOCK".into(),
},
Some("p-edited"),
None,
2_100,
)
.unwrap();
});
});
})
.unwrap();
});
platform.run_until_parked();
// Production bridge switch: doc-a -> doc-b -> doc-a must merge and preserve live edits.
app.update(|cx| {
window_handle
.update(cx, |v, _, cx| {
bridge
.open_document(&mut v.state, &doc_b_id, 1_700_000_000_000)
.unwrap();
cx.notify();
})
.unwrap();
});
headless_win.request_frame();
platform.run_until_parked();
app.update(|cx| {
window_handle
.update(cx, |v, _, cx| {
bridge
.open_document(&mut v.state, &doc_a_id, 1_700_000_000_000)
.unwrap();
cx.notify();
})
.unwrap();
});
headless_win.request_frame();
platform.run_until_parked();
// Verify PlaygroundView still has EDITED_IN_EMBEDDED_EDITOR + nested child after round-trip.
app.update(|cx| {
window_handle
.update(cx, |v, _, cx| {
let editor = v.page_editor().expect("embedded PlaygroundView");
let snap = editor.read(cx).page_snapshot().expect("snapshot");
let edited = snap
.block("p-edited")
.expect("edited paragraph must survive bridge.open_document round-trip");
assert!(matches!(
&edited.content,
BlockContent::Paragraph { text, .. } if text.plain == "EDITED_IN_EMBEDDED_EDITOR"
));
assert_eq!(edited.children.len(), 1);
assert_eq!(edited.children[0].id, "p-nested");
bridge.sync_from_state(&v.state, 3_000).unwrap();
})
.unwrap()
});
// Flush the session into SQLite, close, reopen fresh store, and verify 100% readback.
let written = store
.flush_session_mutations(bridge.session_mut(), None, 3_200)
.await
.unwrap();
assert!(written > 0, "bridge edits must reach SQLite");
// A flush with no new edits must write 0 duplicate rows.
let dup = store
.flush_session_mutations(bridge.session_mut(), None, 3_300)
.await
.unwrap();
assert_eq!(dup, 0, "idempotent flush must not write duplicate rows");
store.checkpoint().await.unwrap();
store.close().await;
let reopened = SqliteWorkspaceStore::open(&base_dir, "workspace", "local", "ws-bridge-e2e")
.await
.unwrap();
let reloaded_page = reopened
.load_doc_session(&doc_a_id, 9090)
.await
.unwrap()
.expect("reloaded doc-a from SQLite");
let reloaded_snap = reloaded_page.read_page_snapshot().unwrap();
let reloaded_edited = reloaded_snap
.block("p-edited")
.expect("persisted edited paragraph must reload from SQLite");
assert!(matches!(
&reloaded_edited.content,
BlockContent::Paragraph { text, .. } if text.plain == "EDITED_IN_EMBEDDED_EDITOR"
));
assert_eq!(reloaded_edited.children.len(), 1);
assert_eq!(reloaded_edited.children[0].id, "p-nested");
// Delete-only mutation test (modifies Yjs DeleteSet without advancing StateVector):
// delete leading 'E' -> "DITED_IN_EMBEDDED_EDITOR", verify SQLite reopen and idempotent
// replay writing 0 duplicate rows.
let mut session2 = reopened
.load_workspace_session(
"u-bridge",
9292,
HostKind::Native,
"local",
"https://app.affine.pro",
4_000,
)
.await
.unwrap();
reopened
.open_or_hydrate_document(&mut session2, &doc_a_id, 4_010)
.await
.unwrap();
let mut bridge2 = MobileWorkspaceBridge::new(session2);
let mut state2 = seed_showcase_state(MobileLocale::En, ThemeMode::Light, "2026-11-28");
bridge2
.open_document(&mut state2, &doc_a_id, 4_050)
.unwrap();
let platform2 = HeadlessPlatform::new(390, 844, 1.0);
let handle_cell2: std::rc::Rc<std::cell::RefCell<Option<WindowHandle<MobileShellView>>>> =
std::rc::Rc::new(std::cell::RefCell::new(None));
let handle_out2 = handle_cell2.clone();
let app2 = Application::with_platform(platform2.clone()).run_embedded(move |cx| {
register_mobile_fonts(cx).expect("register mobile fonts");
let win = cx
.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(Bounds::new(
point(px(0.0), px(0.0)),
size(px(390.0), px(844.0)),
))),
..WindowOptions::default()
},
|_, cx| cx.new(|cx| MobileShellView::new(state2, cx)),
)
.expect("open mobile window 2");
*handle_out2.borrow_mut() = Some(win);
});
let window_handle2 = handle_cell2.borrow_mut().take().unwrap();
let headless_win2 = platform2.windows().into_iter().next().unwrap();
headless_win2.request_frame();
platform2.run_until_parked();
app2.update(|cx| {
window_handle2
.update(cx, |v, _, cx| {
let editor = v.page_editor().expect("embedded PlaygroundView").clone();
editor.update(cx, |pv, cx| {
pv.edit_document(cx, |ds| {
let page = ds.workspace.page_mut(&doc_a_id).unwrap();
page.remove_text("p-edited", "prop:text", 0, 1, 4_100)
.unwrap();
});
});
})
.unwrap();
});
platform2.run_until_parked();
app2.update(|cx| {
window_handle2
.update(cx, |v, _, _| {
assert!(
bridge2.sync_from_state(&v.state, 4_200).unwrap() > 0,
"delete-only edit must merge despite unchanged StateVector"
);
assert_eq!(
bridge2.sync_from_state(&v.state, 4_250).unwrap(),
0,
"replaying identical delete state must merge nothing"
);
})
.unwrap()
});
let del_written = reopened
.flush_session_mutations(bridge2.session_mut(), None, 4_300)
.await
.unwrap();
assert!(del_written > 0);
assert_eq!(
reopened
.flush_session_mutations(bridge2.session_mut(), None, 4_400)
.await
.unwrap(),
0,
"replaying identical delete state must write 0 duplicate rows"
);
reopened.checkpoint().await.unwrap();
reopened.close().await;
let reopened_after_del =
SqliteWorkspaceStore::open(&base_dir, "workspace", "local", "ws-bridge-e2e")
.await
.unwrap();
let after_del_page = reopened_after_del
.load_doc_session(&doc_a_id, 9393)
.await
.unwrap()
.expect("reloaded doc-a after delete");
let after_del_snap = after_del_page.read_page_snapshot().unwrap();
assert!(matches!(
&after_del_snap.block("p-edited").unwrap().content,
BlockContent::Paragraph { text, .. } if text.plain == "DITED_IN_EMBEDDED_EDITOR"
));
reopened_after_del.close().await;
let _ = std::fs::remove_dir_all(&base_dir);
}
#[tokio::test]
async fn mobile_shell_home_new_document_button_persists_to_sqlite_and_reopens() {
use affine_client::sqlite_session::SqliteWorkspaceStore;
use blocksuite_playground_doc::read::BlockContent;
let base_dir =
std::env::temp_dir().join(format!("affine_mobile_home_new_doc_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base_dir);
let ws_id = "ws-home-new";
let store = SqliteWorkspaceStore::open(&base_dir, "workspace", "local", ws_id)
.await
.expect("open sqlite store");
let session = store
.load_workspace_session(
"u-home",
9401,
HostKind::Native,
"local",
"https://app.affine.pro",
5_000,
)
.await
.expect("load session");
let bridge = MobileWorkspaceBridge::new(session);
let state = seed_showcase_state(MobileLocale::En, ThemeMode::Light, "2026-11-28");
let platform = HeadlessPlatform::new(390, 844, 1.0);
let handle_cell: std::rc::Rc<std::cell::RefCell<Option<WindowHandle<MobileShellView>>>> =
std::rc::Rc::new(std::cell::RefCell::new(None));
let handle_out = handle_cell.clone();
let app = Application::with_platform(platform.clone()).run_embedded(move |cx| {
register_mobile_fonts(cx).expect("register mobile fonts");
let win = cx
.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(Bounds::new(
point(px(0.0), px(0.0)),
size(px(390.0), px(844.0)),
))),
..WindowOptions::default()
},
|_, cx| cx.new(|cx| MobileShellView::with_workspace_bridge(state, bridge, cx)),
)
.expect("open mobile window");
*handle_out.borrow_mut() = Some(win);
});
let window_handle = handle_cell.borrow_mut().take().unwrap();
let headless_win = platform.windows().into_iter().next().unwrap();
headless_win.request_frame();
platform.run_until_parked();
// Real UI click on the Home "New document" button (`mobile.home.new_doc_btn`).
let btn_center = app.update(|cx| {
window_handle
.update(cx, |v, _, _| {
let node = v
.published_a11y_tree()
.nodes
.get("mobile.home.new_doc_btn")
.expect("mobile.home.new_doc_btn must exist in Home a11y tree");
let b = node.bounds;
point(px(b.x + b.width * 0.5), px(b.y + b.height * 0.5))
})
.unwrap()
});
headless_win.simulate_click(btn_center);
headless_win.request_frame();
platform.run_until_parked();
let new_doc_id = app.update(|cx| {
window_handle
.update(cx, |v, _, cx| {
let MobileRoute::Page(doc_id) = v.state.route.clone() else {
panic!("clicking Home New document must open Page route");
};
let editor = v
.page_editor()
.expect("embedded PlaygroundView must mount for new doc")
.clone();
editor.update(cx, |pv, cx| {
assert_eq!(pv.active_page_id(), Some(doc_id.as_str()));
pv.edit_document(cx, |ds| {
let page = ds.workspace.page_mut(&doc_id).unwrap();
page.insert_text("root", "prop:title", 0, "Home Created Note", 5_050)
.unwrap();
page.insert_text(
"p-1",
"prop:text",
0,
"CREATED_FROM_HOME_NEW_DOC_BTN",
5_060,
)
.unwrap();
});
});
doc_id
})
.unwrap()
});
platform.run_until_parked();
let mut bridge = app.update(|cx| {
window_handle
.update(cx, |v, _, _| {
v.take_workspace_bridge(5_100)
.expect("workspace_bridge mounted")
.expect("merge shell edits")
})
.unwrap()
});
let written = store
.flush_session_mutations(bridge.session_mut(), None, 5_150)
.await
.unwrap();
assert!(
written > 0,
"flushing Home-created doc must write SQLite rows"
);
for doc_id in [ws_id, new_doc_id.as_str()] {
assert!(
store
.storage()
.get_doc_clock(doc_id)
.await
.unwrap()
.is_some(),
"flushing Home-created doc must persist `{doc_id}`"
);
}
store.checkpoint().await.unwrap();
store.close().await;
// Cold-reopen SQLite into a brand-new MobileShellView on Home route.
let reopened = SqliteWorkspaceStore::open(&base_dir, "workspace", "local", ws_id)
.await
.unwrap();
let mut session2 = reopened
.load_workspace_session(
"u-home-reopen",
9402,
HostKind::Native,
"local",
"https://app.affine.pro",
5_500,
)
.await
.unwrap();
reopened
.open_or_hydrate_document(&mut session2, &new_doc_id, 5_510)
.await
.unwrap();
let bridge2 = MobileWorkspaceBridge::new(session2);
let state2 = seed_showcase_state(MobileLocale::En, ThemeMode::Light, "2026-11-28");
let platform2 = HeadlessPlatform::new(390, 844, 1.0);
let handle_cell2: std::rc::Rc<std::cell::RefCell<Option<WindowHandle<MobileShellView>>>> =
std::rc::Rc::new(std::cell::RefCell::new(None));
let handle_out2 = handle_cell2.clone();
let app2 = Application::with_platform(platform2.clone()).run_embedded(move |cx| {
register_mobile_fonts(cx).expect("register mobile fonts");
let win = cx
.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(Bounds::new(
point(px(0.0), px(0.0)),
size(px(390.0), px(844.0)),
))),
..WindowOptions::default()
},
|_, cx| cx.new(|cx| MobileShellView::with_workspace_bridge(state2, bridge2, cx)),
)
.expect("open mobile window 2");
*handle_out2.borrow_mut() = Some(win);
});
let window_handle2 = handle_cell2.borrow_mut().take().unwrap();
let headless_win2 = platform2.windows().into_iter().next().unwrap();
headless_win2.request_frame();
platform2.run_until_parked();
app2.update(|cx| {
window_handle2
.update(cx, |v, _, cx| {
let rec = v
.state
.active_workspace()
.docs()
.iter()
.find(|d| d.id == new_doc_id)
.expect("reopened Home doc list must contain doc created via New document");
assert_eq!(rec.title, "Home Created Note");
assert!(
rec.body_preview.contains("CREATED_FROM_HOME_NEW_DOC_BTN"),
"reopened Home preview must reflect typed body, got `{}`",
rec.body_preview
);
assert!(v.open_doc_action(&new_doc_id, 1_700_000_000_000));
cx.notify();
})
.unwrap();
});
headless_win2.request_frame();
platform2.run_until_parked();
app2.update(|cx| {
window_handle2
.update(cx, |v, _, cx| {
let editor = v.page_editor().expect("reopened embedded PlaygroundView");
let pv = editor.read(cx);
let snap = pv.page_snapshot().expect("reopened page snapshot");
let root = snap.root.as_ref().expect("root block");
assert!(matches!(
&root.content,
BlockContent::Page { title } if title.plain == "Home Created Note"
));
assert!(matches!(
&snap.block("p-1").expect("p-1 block").content,
BlockContent::Paragraph { text, .. } if text.plain == "CREATED_FROM_HOME_NEW_DOC_BTN"
));
})
.unwrap();
});
reopened.close().await;
let _ = std::fs::remove_dir_all(&base_dir);
}