Files
AFFiNE/packages/frontend/mobile/tests/mobile_shell_e2e/sqlite_bridge.rs
T
DarkSky 438c5cff16 feat(editor,hosts): add create-linked-doc conversion with subdoc persistence
Page FormatToolbar `Create Linked Doc` opens the `Create linked doc` title
dialog. The dialog shows the first block as the title when that block is a
heading. `Confirm` moves the whole blocks that the selection touches, with
their subtrees and all their properties, into a new linked page. Code
text, table and database cells, marks, and inline references stay intact.
It puts an `affine:embed-linked-doc` card in their place. A blank title
gives `Untitled`. `Cancel`, `Escape`, or a press outside the dialog write
nothing.

The Edgeless `More` menu adds `Turn into linked doc` for one unlocked
note. This puts an `affine:embed-synced-doc` card with the frame, index,
and connectors of the note in its place. The menu also adds `Create linked
doc` for other unlocked selections. This moves the items, selected notes
included, into a new Edgeless document in their paint order. Then it puts
a 364 x 390 `vertical` card at their center. Both actions use the same
title dialog. Each conversion is one undo step in the source document. The
open-document group of the menu comes before the clipboard group. A menu
that does not fit scrolls its rows with the wheel and does not cover the
toolbar or the creation toolbar. `PageDocSession::export_block_tree`
exports a block subtree with every property for these copies and for
Edgeless copy and clone.

`WorkspaceDocDirectory::seed_created_doc` gives the complete Yjs V1 state
of a new document to the host, so that the content persists. The desktop
host replaces the initial blocks of the store with the seed blocks through
`PageDocSession::replace_blocks_update_v1`. It queues the change for the
connected session. The desktop directory keeps the snapshot of each loaded
document, and of a seeded document that the store does not have yet, so
synced cards show the content after a refresh or a reopen. The client
directory queues the seed with the pending updates of the workspace
database (`enqueue_pending_update`). The mobile host keeps the seed as the
cached CRDT state. The mobile bridge adds a document that the shell
created to the workspace root before it merges the content. New mobile
document IDs come from the intent, or from a random value, for each
workspace. They never reuse the ID of a document in the trash.
2026-12-05 01:01:17 +09:00

716 lines
26 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);
}
#[cfg(not(target_family = "wasm"))]
#[tokio::test]
async fn shell_created_linked_docs_stay_listed_with_their_content_across_trash_and_sqlite_reopens()
{
use affine_client::{SqliteWorkspaceStore, WorkspaceSession};
use affine_mobile::MobileDocRecord;
use affine_store::directory::{DocId, DocMode};
use blocksuite_playground_doc::{
schema::{BlockSpec, ParagraphType},
session::PageDocSession,
};
// Two linked documents that the shell creates one after the other, the first one trashed
// before the second one exists.
const FIRST: &str = "doc-linked-first";
const SECOND: &str = "doc-linked-second";
let base_dir =
std::env::temp_dir().join(format!("affine_mobile_linked_seed_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base_dir);
let ws_id = "ws-linked-seed";
async fn open(
base_dir: &std::path::Path,
ws_id: &str,
now_ms: i64,
) -> (SqliteWorkspaceStore, WorkspaceSession) {
let store = SqliteWorkspaceStore::open(base_dir, "workspace", "local", ws_id)
.await
.expect("open sqlite store");
let session = store
.load_workspace_session(
"u-linked",
9402,
HostKind::Native,
"local",
"https://app.affine.pro",
now_ms,
)
.await
.expect("load session");
(store, session)
}
fn seed(doc_id: &str, title: &str, body: &str) -> Vec<u8> {
let mut page = PageDocSession::new(doc_id, 31).expect("page");
page.add_block(
"seed-root",
BlockSpec::Page {
title: title.into(),
},
None,
None,
1,
)
.expect("root");
page.add_block(
"seed-note",
BlockSpec::Note { xywh: None },
Some("seed-root"),
None,
2,
)
.expect("note");
page.add_block(
"seed-p",
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Text,
text: body.into(),
},
Some("seed-note"),
None,
3,
)
.expect("paragraph");
page.encode_update_v1().expect("update")
}
let mut now = 6_000;
for (doc, title, mode, trash_before) in [
(FIRST, "Board", DocMode::Edgeless, None),
(SECOND, "Notes", DocMode::Page, Some(FIRST)),
] {
let (store, session) = open(&base_dir, ws_id, now).await;
let mut bridge = MobileWorkspaceBridge::new(session);
let mut state = seed_showcase_state(MobileLocale::En, ThemeMode::Light, "2026-12-04");
bridge.sync_into_state(&mut state, now + 10);
if let Some(trashed) = trash_before {
assert!(
bridge
.session_mut()
.trash_document(trashed, now + 15)
.expect("trash")
);
}
let ws = state.active_workspace_mut();
ws.docs_mut().push(MobileDocRecord {
id: doc.into(),
title: title.into(),
body_preview: String::new(),
tags: Vec::new(),
updated_at_ms: now + 20,
is_favorite: false,
trashed: false,
journal_date: None,
primary_mode: mode,
clock: 1,
outgoing_edges: Vec::new(),
blocks: Vec::new(),
});
ws.set_doc_crdt_update(doc, seed(doc, title, &format!("{title} body")));
bridge
.flush_session_mutations(&state, &store, now + 30)
.await
.expect("flush");
drop(bridge);
store.close().await;
now += 100;
}
let (store, mut session) = open(&base_dir, ws_id, now).await;
for (doc, title, mode, trashed) in [
(FIRST, "Board", DocMode::Edgeless, true),
(SECOND, "Notes", DocMode::Page, false),
] {
let listed = session
.directory()
.lock_directory()
.get_doc(&DocId::new(doc).expect("doc id"))
.expect("read directory")
.expect("linked doc listed in the workspace root");
assert_eq!(
(listed.title.as_str(), listed.mode, listed.trashed),
(title, mode, trashed)
);
store
.open_or_hydrate_document(&mut session, doc, now + 10)
.await
.expect("hydrate");
let snapshot = session.doc_snapshot(doc).expect("snapshot");
assert_eq!(snapshot.title(), title);
assert!(snapshot.block("seed-p").is_some(), "{doc} keeps its body");
}
store.close().await;
let _ = std::fs::remove_dir_all(&base_dir);
}