feat(mobile): add atomic 0.27.5 share block ingest, deterministic probe lifecycle, and durable share inbox

This commit is contained in:
DarkSky committed 2026-11-30 13:41:09 +09:00
1 parent 9244320f20
commit f21fa487cf
57 files changed
+9304 -290

No files matched your search

+8 -1
View File
@@ -279,8 +279,11 @@ jobs:
packages/frontend/hosts/android/kotlin/app/affine/pro/host/LegacyLocalStorageProbe.kt \
packages/frontend/hosts/android/kotlin/app/affine/pro/host/AndroidBootstrapCoordinator.kt \
packages/frontend/hosts/android/kotlin/app/affine/pro/host/AuthDataStore.kt \
packages/frontend/hosts/android/kotlin/app/affine/pro/host/ShareIntentBridge.kt \
packages/frontend/hosts/android/kotlin/app/affine/pro/host/ShareReceiverActivity.kt \
packages/frontend/hosts/android/tests/ImeHostParityCheck.kt
test -s /tmp/affine-android-kotlin/app/affine/pro/host/MainActivity.class
test -s /tmp/affine-android-kotlin/app/affine/pro/host/ShareReceiverActivity.class
test -s /tmp/affine-android-kotlin/app/affine/pro/host/AffineImeController.class
test -s /tmp/affine-android-kotlin/app/affine/pro/host/AffineInputConnection.class
test -s /tmp/affine-android-kotlin/app/affine/pro/host/LegacyLocalStorageProbe.class
@@ -347,7 +350,7 @@ jobs:
echo "iOS staticlib libaffine_ios_host.a bytes: ${IOS_LIB_BYTES}"
test "$IOS_LIB_BYTES" -le 650000000
- name: Link zero-CocoaPods Swift iOS host and run 6/6 Simulator smoke tests
- name: Link zero-CocoaPods Swift iOS host and run 7/7 Simulator smoke tests
run: |
(
SIM_UDID=$(xcrun simctl list devices available -j | python3 -c '
@@ -394,6 +397,8 @@ jobs:
-framework CoreFoundation \
-framework Foundation \
-framework UniformTypeIdentifiers \
-framework StoreKit \
-framework AuthenticationServices \
-o /tmp/AffineIosHost \
packages/frontend/hosts/ios/Sources/*.swift &
PID_APP=$!
@@ -415,6 +420,8 @@ jobs:
-framework CoreFoundation \
-framework Foundation \
-framework UniformTypeIdentifiers \
-framework StoreKit \
-framework AuthenticationServices \
-o /tmp/IosHostS3SmokeTest \
"${SMOKE_SOURCES[@]}" \
packages/frontend/hosts/ios/tests/IosHostS3SmokeTest.swift &
+33 -23
View File
@@ -606,31 +606,41 @@ fn parse_views(value: Option<&JsonValue>) -> Vec<DatabaseView> {
.get("groupProperties")
.and_then(JsonValue::as_array)
.map(|props| {
props
.iter()
.filter_map(|p| {
let pobj = p.as_object()?;
let key = pobj.get("key")?.as_str()?.to_string();
let hide = pobj
.get("hide")
.and_then(JsonValue::as_bool)
.unwrap_or(false);
let manually_card_sort = pobj
.get("manuallyCardSort")
.and_then(JsonValue::as_array)
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(str::to_string))
.collect()
})
.unwrap_or_default();
Some(DatabaseGroupProperty {
key,
let mut merged: Vec<DatabaseGroupProperty> = Vec::with_capacity(props.len());
for p in props {
let Some(pobj) = p.as_object() else { continue };
let Some(key) = pobj.get("key").and_then(JsonValue::as_str) else {
continue;
};
let hide = pobj
.get("hide")
.and_then(JsonValue::as_bool)
.unwrap_or(false);
let manually_card_sort: Vec<String> = pobj
.get("manuallyCardSort")
.and_then(JsonValue::as_array)
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(str::to_string))
.collect()
})
.unwrap_or_default();
if let Some(existing) = merged.iter_mut().find(|g| g.key == key) {
existing.hide |= hide;
if existing.manually_card_sort.is_empty()
&& !manually_card_sort.is_empty()
{
existing.manually_card_sort = manually_card_sort;
}
} else {
merged.push(DatabaseGroupProperty {
key: key.to_string(),
hide,
manually_card_sort,
})
})
.collect()
});
}
}
merged
})
.unwrap_or_default();
let header =
+6 -1
View File
@@ -646,6 +646,11 @@ impl BlockSpec {
caption,
embed,
} => {
let style = if embed && mime_type.eq_ignore_ascii_case("application/pdf") {
"pdf"
} else {
"horizontalThin"
};
entries.extend([
(
"prop:name".to_string(),
@@ -681,7 +686,7 @@ impl BlockSpec {
),
(
"prop:style".to_string(),
SessionValue::Any(Any::String("horizontalThin".to_string())),
SessionValue::Any(Any::String(style.to_string())),
),
(
"prop:footnoteIdentifier".to_string(),
@@ -14,6 +14,7 @@ pub(super) fn read_group_card_sort_in_array_tx(
arr_target: &TypeTarget,
group_key: &str,
) -> DocResult<Option<Vec<String>>> {
let mut found: Option<Vec<String>> = None;
for item in page.inner().read_array(arr_target)? {
match item {
SessionReadValue::Map(gp_map_id) => {
@@ -22,31 +23,37 @@ pub(super) fn read_group_card_sort_in_array_tx(
page.inner().get_map_value(&gp_target, "key")?,
Some(SessionReadValue::Any(Any::String(ref k))) if k == group_key
) {
let sort = match page.inner().get_map_value(&gp_target, "manuallyCardSort")? {
Some(SessionReadValue::Array(s_id)) => page
.inner()
.read_array(&TypeTarget::Identity(s_id))?
.into_iter()
.filter_map(|v| match v {
SessionReadValue::Any(Any::String(s)) => Some(s),
_ => None,
})
.collect(),
Some(SessionReadValue::Any(Any::Array(arr))) => arr
.into_iter()
.filter_map(|v| match v {
Any::String(s) => Some(s),
_ => None,
})
.collect(),
_ => Vec::new(),
};
return Ok(Some(sort));
let sort: Vec<String> =
match page.inner().get_map_value(&gp_target, "manuallyCardSort")? {
Some(SessionReadValue::Array(s_id)) => page
.inner()
.read_array(&TypeTarget::Identity(s_id))?
.into_iter()
.filter_map(|v| match v {
SessionReadValue::Any(Any::String(s)) => Some(s),
_ => None,
})
.collect(),
Some(SessionReadValue::Any(Any::Array(arr))) => arr
.into_iter()
.filter_map(|v| match v {
Any::String(s) => Some(s),
_ => None,
})
.collect(),
_ => Vec::new(),
};
if !sort.is_empty() {
return Ok(Some(sort));
}
if found.is_none() {
found = Some(sort);
}
}
}
SessionReadValue::Any(Any::Object(obj)) => {
if matches!(obj.get("key"), Some(Any::String(k)) if k == group_key) {
let sort = match obj.get("manuallyCardSort") {
let sort: Vec<String> = match obj.get("manuallyCardSort") {
Some(Any::Array(arr)) => arr
.iter()
.filter_map(|v| match v {
@@ -56,13 +63,18 @@ pub(super) fn read_group_card_sort_in_array_tx(
.collect(),
_ => Vec::new(),
};
return Ok(Some(sort));
if !sort.is_empty() {
return Ok(Some(sort));
}
if found.is_none() {
found = Some(sort);
}
}
}
_ => {}
}
}
Ok(None)
Ok(found)
}
pub(super) fn upsert_group_card_sort_in_array_tx(
@@ -81,8 +93,45 @@ pub(super) fn upsert_group_card_sort_in_array_tx(
)
};
let items = page.inner().read_array(arr_target)?;
let mut key_counts: std::collections::BTreeMap<String, usize> =
std::collections::BTreeMap::new();
let mut key_hide_or: std::collections::BTreeMap<String, bool> =
std::collections::BTreeMap::new();
for item in &items {
let (maybe_key, maybe_hide) = match item {
SessionReadValue::Map(gp_map_id) => {
let tgt = TypeTarget::Identity(gp_map_id.clone());
let k = match page.inner().get_map_value(&tgt, "key")? {
Some(SessionReadValue::Any(Any::String(k))) => Some(k),
_ => None,
};
let h = matches!(
page.inner().get_map_value(&tgt, "hide")?,
Some(SessionReadValue::Any(Any::True))
);
(k, h)
}
SessionReadValue::Any(Any::Object(obj)) => {
let k = match obj.get("key") {
Some(Any::String(k)) => Some(k.clone()),
_ => None,
};
let h = matches!(obj.get("hide"), Some(Any::True));
(k, h)
}
_ => (None, false),
};
if let Some(k) = maybe_key {
*key_counts.entry(k.clone()).or_insert(0) += 1;
if maybe_hide {
key_hide_or.insert(k, true);
}
}
}
let mut existing_keys: Vec<Option<String>> = Vec::with_capacity(items.len());
let mut seen_keys = std::collections::BTreeSet::new();
let mut updated_target = false;
let mut duplicate_indices: Vec<usize> = Vec::new();
for (idx, item) in items.into_iter().enumerate() {
match item {
SessionReadValue::Map(gp_map_id) => {
@@ -91,13 +140,43 @@ pub(super) fn upsert_group_card_sort_in_array_tx(
Some(SessionReadValue::Any(Any::String(k))) => Some(k),
_ => None,
};
if !updated_target && item_key.as_deref() == Some(group_key) {
page.inner_mut().map_set(
&gp_target,
"manuallyCardSort".to_string(),
make_sort_array(sort_ids),
)?;
updated_target = true;
if let Some(ref key_str) = item_key {
let has_dups = key_counts.get(key_str).copied().unwrap_or(0) > 1;
if !seen_keys.insert(key_str.clone()) {
duplicate_indices.push(idx);
} else if key_str == group_key {
page.inner_mut().map_set(
&gp_target,
"manuallyCardSort".to_string(),
make_sort_array(sort_ids),
)?;
if has_dups && key_hide_or.get(key_str).copied().unwrap_or(false) {
page.inner_mut().map_set(
&gp_target,
"hide".to_string(),
SessionValue::Any(Any::True),
)?;
}
updated_target = true;
} else if has_dups {
if let Some(merged) =
read_group_card_sort_in_array_tx(page, arr_target, key_str)?
&& !merged.is_empty()
{
page.inner_mut().map_set(
&gp_target,
"manuallyCardSort".to_string(),
make_sort_array(&merged),
)?;
}
if key_hide_or.get(key_str).copied().unwrap_or(false) {
page.inner_mut().map_set(
&gp_target,
"hide".to_string(),
SessionValue::Any(Any::True),
)?;
}
}
}
existing_keys.push(item_key);
}
@@ -106,26 +185,67 @@ pub(super) fn upsert_group_card_sort_in_array_tx(
Some(Any::String(k)) => Some(k.clone()),
_ => None,
};
if !updated_target && item_key.as_deref() == Some(group_key) {
obj.remove("manuallyCardSort");
let mut entries: Vec<(String, SessionValue)> = obj
.into_iter()
.map(|(k, v)| (k, any_to_session_value(v)))
.collect();
entries.push(("manuallyCardSort".to_string(), make_sort_array(sort_ids)));
page.inner_mut().array_remove(arr_target, idx as u64, 1)?;
page.inner_mut().array_insert(
arr_target,
idx as u64,
vec![SessionValue::Map(entries)],
)?;
updated_target = true;
if let Some(ref key_str) = item_key {
let has_dups = key_counts.get(key_str).copied().unwrap_or(0) > 1;
if !seen_keys.insert(key_str.clone()) {
duplicate_indices.push(idx);
} else if key_str == group_key {
obj.remove("manuallyCardSort");
if has_dups && key_hide_or.get(key_str).copied().unwrap_or(false) {
obj.insert("hide".to_string(), Any::True);
}
let mut entries: Vec<(String, SessionValue)> = obj
.into_iter()
.map(|(k, v)| (k, any_to_session_value(v)))
.collect();
entries.push(("manuallyCardSort".to_string(), make_sort_array(sort_ids)));
page.inner_mut().array_remove(arr_target, idx as u64, 1)?;
page.inner_mut().array_insert(
arr_target,
idx as u64,
vec![SessionValue::Map(entries)],
)?;
updated_target = true;
} else if has_dups {
let merged = read_group_card_sort_in_array_tx(page, arr_target, key_str)?
.unwrap_or_default();
let force_hide = key_hide_or.get(key_str).copied().unwrap_or(false);
if !merged.is_empty() || force_hide {
if !merged.is_empty() {
obj.remove("manuallyCardSort");
}
if force_hide {
obj.insert("hide".to_string(), Any::True);
}
let mut entries: Vec<(String, SessionValue)> = obj
.into_iter()
.map(|(k, v)| (k, any_to_session_value(v)))
.collect();
if !merged.is_empty() {
entries.push((
"manuallyCardSort".to_string(),
make_sort_array(&merged),
));
}
page.inner_mut().array_remove(arr_target, idx as u64, 1)?;
page.inner_mut().array_insert(
arr_target,
idx as u64,
vec![SessionValue::Map(entries)],
)?;
}
}
}
existing_keys.push(item_key);
}
_ => existing_keys.push(None),
}
}
for dup_idx in duplicate_indices.into_iter().rev() {
page.inner_mut()
.array_remove(arr_target, dup_idx as u64, 1)?;
existing_keys.remove(dup_idx);
}
if !create_if_missing {
return Ok(());
}
+31 -2
View File
@@ -1,7 +1,7 @@
use serde_json::{Map as JsonMap, Value as JsonValue};
use y_octo::{
Any, RelativePosition, SessionCommit, SessionReadValue, TextDeltaOp, TextInsert, TypePath,
TypeTarget,
Any, RelativePosition, SessionCommit, SessionReadValue, SessionValue, TextDeltaOp, TextInsert,
TypePath, TypeTarget,
};
use crate::{DocError, DocResult, schema::UnknownBlock};
@@ -9,6 +9,35 @@ use crate::{DocError, DocResult, schema::UnknownBlock};
use super::{PageDocSession, ResolvedSelection, SelectionSnapshot, block_target};
impl PageDocSession {
/// Update `prop:size` on an existing `affine:image` or `affine:attachment` block so imported
/// blobs persist exact byte lengths (`0.27.5` `import.ts:322`) instead of `-1`.
pub fn set_block_size_bytes(
&mut self,
block_id: &str,
size_bytes: i64,
now_ms: u64,
) -> DocResult<Option<SessionCommit<SelectionSnapshot>>> {
let target = block_target(block_id);
if self
.session
.get_map_value(&self.blocks_target, block_id)
.ok()
.flatten()
.is_none()
{
return Err(DocError::BlockNotFound(block_id.to_string()));
}
self.advance_time(now_ms);
let val = if let Ok(v) = i32::try_from(size_bytes) {
Any::Integer(v)
} else {
Any::Float64((size_bytes as f64).into())
};
let commit =
self.session
.map_set(&target, "prop:size".to_string(), SessionValue::Any(val))?;
Ok(self.record_commit(commit))
}
/// Capture a relative-position selection snapshot on a text property and attach
/// it to the top undo item of this page's `blocks` undo stack.
pub fn capture_selection_snapshot(
+11
View File
@@ -467,6 +467,17 @@ impl PageDocSession {
index: Option<u64>,
now_ms: u64,
) -> DocResult<Option<SessionCommit<SelectionSnapshot>>> {
if self
.session
.get_map_value(&self.blocks_target, &block_id)
.ok()
.flatten()
.is_some()
{
return Err(DocError::InvalidState(format!(
"duplicate block id: {block_id}"
)));
}
let mut index_had_dups = false;
if let Some(pid) = parent_id {
let parent_target = TypeTarget::Path(TypePath::root("blocks").key(pid));
+46 -16
View File
@@ -195,7 +195,7 @@ impl PageDocSession {
}
pub fn dedent_block(&mut self, id: &str, now_ms: u64) -> DocResult<PageCommit> {
let (parent, slot) = self.parent_slot(id)?;
let (parent, slot, parent_had_dups) = self.parent_slot_with_dups(id)?;
let p_flavour = self.read_unknown_block(&parent)?.flavour;
if !matches!(p_flavour.as_str(), "affine:paragraph" | "affine:list") {
return Err(DocError::InvalidState(
@@ -203,11 +203,16 @@ impl PageDocSession {
));
}
let p_children = self.unique_children(&parent)?;
let p_child_count = self.unique_children(id)?.len();
let (id_children, id_had_dups) = self.unique_children_with_dups(id)?;
let p_child_count = id_children.len();
let (grandparent, parent_slot) = self.parent_slot(&parent)?;
self.structural_edit(now_ms, |page| {
page.dedup_children_in_tx(&parent)?;
page.dedup_children_in_tx(id)?;
if parent_had_dups {
page.dedup_children_in_tx(&parent)?;
}
if id_had_dups {
page.dedup_children_in_tx(id)?;
}
let tail = &p_children[slot as usize + 1..];
if !tail.is_empty() {
page.session.array_remove(
@@ -357,7 +362,7 @@ impl PageDocSession {
locally_collapsed: bool,
now_ms: u64,
) -> DocResult<PageCommit> {
let graph = self.child_graph()?;
let (graph, dup_parents) = self.child_graph_with_dups()?;
if graph.contains_key(new_block_id) {
return Err(DocError::InvalidState("duplicate block id".into()));
}
@@ -429,6 +434,8 @@ impl PageDocSession {
.find(|(key, _)| key == "prop:text")
.ok_or_else(|| DocError::InvalidState("split requires a text block".into()))?;
text.1 = SessionValue::Text(tail);
let parent_had_dups = dup_parents.contains(parent);
let block_had_dups = dup_parents.contains(block_id);
self.structural_edit(now_ms, |page| {
if length > split_utf16 {
page.session
@@ -439,14 +446,18 @@ impl PageDocSession {
new_block_id.to_owned(),
SessionValue::Map(entries),
)?;
page.dedup_children_in_tx(parent)?;
if parent_had_dups {
page.dedup_children_in_tx(parent)?;
}
page.session.array_insert(
&children_target(parent),
index as u64,
vec![SessionValue::Any(Any::String(new_block_id.into()))],
)?;
if split_utf16 == 0 && !is_page && !children.is_empty() {
page.dedup_children_in_tx(block_id)?;
if block_had_dups {
page.dedup_children_in_tx(block_id)?;
}
page.session
.array_remove(&children_target(block_id), 0, children.len() as u64)?;
page.session
@@ -503,11 +514,19 @@ impl PageDocSession {
survivors: &[String],
now_ms: u64,
) -> DocResult<PageCommit> {
let graph = self.child_graph()?;
let (graph, dup_parents) = self.child_graph_with_dups()?;
let mut removed = intermediate.to_vec();
removed.push(end.0.to_owned());
self.join_range(
&graph, start.0, start.1, end.0, end.1, &removed, survivors, now_ms,
&graph,
&dup_parents,
start.0,
start.1,
end.0,
end.1,
&removed,
survivors,
now_ms,
)
}
@@ -515,6 +534,7 @@ impl PageDocSession {
fn join_range(
&mut self,
graph: &ChildGraph,
dup_parents: &BTreeSet<String>,
start: &str,
from: u64,
end: &str,
@@ -583,7 +603,9 @@ impl PageDocSession {
.map(|(index, _)| index as u64)
.collect();
if !to_remove.is_empty() {
page.dedup_children_in_tx(id)?;
if dup_parents.contains(id.as_str()) {
page.dedup_children_in_tx(id)?;
}
for index in to_remove {
page.session.array_remove(&children_target(id), index, 1)?;
}
@@ -591,19 +613,25 @@ impl PageDocSession {
}
if !moved.is_empty() {
if title {
page.dedup_children_in_tx(&dest)?;
if dup_parents.contains(dest.as_str()) {
page.dedup_children_in_tx(&dest)?;
}
page.session
.array_insert(&children_target(&dest), 0, child_values(moved))?;
} else if crate::schema::is_leaf_flavour(&flavour) {
let (parent, slot) = page.parent_slot(start)?;
page.dedup_children_in_tx(&parent)?;
let (parent, slot, parent_had_dups) = page.parent_slot_with_dups(start)?;
if parent_had_dups {
page.dedup_children_in_tx(&parent)?;
}
page.session.array_insert(
&children_target(&parent),
slot + 1,
child_values(moved),
)?;
} else {
page.dedup_children_in_tx(&dest)?;
if dup_parents.contains(dest.as_str()) {
page.dedup_children_in_tx(&dest)?;
}
page.session
.array_push(&children_target(&dest), child_values(moved))?;
}
@@ -667,7 +695,7 @@ impl PageDocSession {
);
let old_flavour = self.read_unknown_block(id)?.flavour;
let old_children = self.unique_children(id)?;
let (parent, slot) = self.parent_slot(id)?;
let (parent, slot, parent_had_dups) = self.parent_slot_with_dups(id)?;
let same = old_flavour == spec.flavour();
if !same
&& self
@@ -704,7 +732,9 @@ impl PageDocSession {
let align = page
.session
.get_map_value(&block_target(id), "prop:textAlign")?;
page.dedup_children_in_tx(&parent)?;
if parent_had_dups {
page.dedup_children_in_tx(&parent)?;
}
page.add_block(replacement_id, spec, Some(&parent), Some(slot), now_ms)?;
if !delta.is_empty() {
page.apply_text_delta(replacement_id, "prop:text", &delta, now_ms)?;
+139 -24
View File
@@ -2141,15 +2141,143 @@ fn structural_edits_under_parent_with_duplicated_child_id_heal_raw_array_accurat
}
#[test]
fn append_and_structural_edits_under_large_parent_stay_fast() -> DocResult<()> {
let mut last_mid_insert_ms = 0.0_f64;
let mut last_build_ms = 0.0_f64;
fn two_replicas_concurrent_first_drag_preserves_both_lanes_and_display_order() -> DocResult<()> {
let (mut p1, db_id) = seed_authoring_database()?;
p1.add_database_row_with_cells(
&db_id,
"r2",
"Todo B",
vec![(
"col-status".into(),
DatabaseCellSpec::Text("opt-todo".into()),
)],
900,
)?;
p1.add_database_row_with_cells(
&db_id,
"r3",
"Done A",
vec![(
"col-status".into(),
DatabaseCellSpec::Text("opt-done".into()),
)],
901,
)?;
p1.add_database_row_with_cells(
&db_id,
"r4",
"Done B",
vec![(
"col-status".into(),
DatabaseCellSpec::Text("opt-done".into()),
)],
902,
)?;
// Enable groupBy on `v-table` so `groupProperties` starts as an empty shared `Y.Array`
// on both replicas (matching a fresh Kanban or grouped Table view before any manual drag).
p1.set_database_view_group_by(
&db_id,
"v-table",
Some(DatabaseGroupBy {
kind: "group".into(),
column_id: "col-status".into(),
name: "select".into(),
sort: None,
hide_empty: None,
}),
903,
)?;
let mut p2 = PageDocSession::new("page-concurrent-gp", 202)?;
p2.apply_remote_update_v1(&p1.encode_update_v1()?)?;
let sv1 = p1.encode_state_vector_v1()?;
let sv2 = p2.encode_state_vector_v1()?;
let ordered_lanes = vec![
"Ungroups".to_string(),
"opt-todo".to_string(),
"opt-doing".to_string(),
"opt-done".to_string(),
];
let todo_bucket = vec!["r1".to_string(), "r2".to_string()];
let todo_reordered = vec!["r2".to_string(), "r1".to_string()];
let done_bucket = vec!["r3".to_string(), "r4".to_string()];
let done_reordered = vec!["r4".to_string(), "r3".to_string()];
// Replica 1 does the first drag in "opt-todo" (`r2` before `r1`).
assert!(
p1.move_database_grouped_card(
&db_id,
"v-table",
"r2",
&ordered_lanes,
None,
"opt-todo",
&todo_bucket,
&todo_reordered,
blocksuite_playground_doc::session::DatabaseRowGroupUpdate::None,
910,
)?
.is_some()
);
// Concurrently, Replica 2 does the first drag in "opt-done" (`r4` before `r3`).
assert!(
p2.move_database_grouped_card(
&db_id,
"v-table",
"r4",
&ordered_lanes,
None,
"opt-done",
&done_bucket,
&done_reordered,
blocksuite_playground_doc::session::DatabaseRowGroupUpdate::None,
911,
)?
.is_some()
);
let d1 = p1.encode_diff_v1(&sv2)?;
let d2 = p2.encode_diff_v1(&sv1)?;
p1.apply_remote_update_v1(&d2)?;
p2.apply_remote_update_v1(&d1)?;
for replica in [&p1, &p2] {
let db = read_db(replica, &db_id);
let kanban = db.views.iter().find(|v| v.id == "v-table").unwrap();
let keys: Vec<&str> = kanban
.group_properties
.iter()
.map(|gp| gp.key.as_str())
.collect();
assert_eq!(
keys,
vec!["Ungroups", "opt-todo", "opt-doing", "opt-done"],
"lane display order must stay intact without duplicate keys"
);
let todo_gp = kanban
.group_properties
.iter()
.find(|gp| gp.key == "opt-todo")
.unwrap();
let done_gp = kanban
.group_properties
.iter()
.find(|gp| gp.key == "opt-done")
.unwrap();
assert_eq!(todo_gp.manually_card_sort, vec!["r2", "r1"]);
assert_eq!(done_gp.manually_card_sort, vec!["r4", "r3"]);
}
Ok(())
}
#[test]
fn append_and_structural_edits_under_large_parent_stay_deterministic() -> DocResult<()> {
for n in [500_usize, 1_000, 2_000] {
let mut p = PageDocSession::new("page-time", 77)?;
let mut p = PageDocSession::new("page-scale", 77)?;
p.add_block(
"root",
BlockSpec::Page {
title: "Timing".into(),
title: "Scale".into(),
},
None,
None,
@@ -2162,7 +2290,6 @@ fn append_and_structural_edits_under_large_parent_stay_fast() -> DocResult<()> {
None,
2,
)?;
let t = std::time::Instant::now();
for i in 0..n {
p.add_block(
&format!("p{i}"),
@@ -2175,9 +2302,7 @@ fn append_and_structural_edits_under_large_parent_stay_fast() -> DocResult<()> {
10 + i as u64,
)?;
}
let build_ms = t.elapsed().as_secs_f64() * 1000.0;
p.stop_capturing()?;
let t = std::time::Instant::now();
p.add_block(
"one-more",
BlockSpec::Paragraph {
@@ -2188,27 +2313,17 @@ fn append_and_structural_edits_under_large_parent_stay_fast() -> DocResult<()> {
Some((n / 2) as u64),
1_000_000,
)?;
let insert_ms = t.elapsed().as_secs_f64() * 1000.0;
let t = std::time::Instant::now();
assert_eq!(p.read_unknown_block("note")?.children[n / 2], "one-more");
assert!(
p.reparent_block("one-more", "note", "note", 0, 1_000_001)?
.is_some()
);
let move_ms = t.elapsed().as_secs_f64() * 1000.0;
let t = std::time::Instant::now();
assert_eq!(p.read_unknown_block("note")?.children[0], "one-more");
assert!(p.remove_lifting_children("one-more", 1_000_002)?.is_some());
let remove_ms = t.elapsed().as_secs_f64() * 1000.0;
assert_eq!(p.read_unknown_block("note")?.children.len(), n);
println!(
"LINEAR_PROBE n={n}: append={build_ms:.1}ms ({:.3}ms/blk) | mid_insert={insert_ms:.2}ms | move_front={move_ms:.2}ms | remove_lift={remove_ms:.2}ms",
build_ms / n as f64
);
last_mid_insert_ms = insert_ms;
last_build_ms = build_ms;
let final_children = p.read_unknown_block("note")?.children;
assert_eq!(final_children.len(), n);
assert_eq!(final_children[0], "p0");
assert_eq!(final_children[n - 1], format!("p{}", n - 1));
}
assert!(
last_build_ms < 5_000.0 && last_mid_insert_ms < 20.0,
"2k append ({last_build_ms:.2}ms) and mid_insert ({last_mid_insert_ms:.2}ms) regressed"
);
Ok(())
}
@@ -271,6 +271,9 @@ pub fn layout_database_block(
// Phone / Tablet: single-row horizontal scroll strip with clean clipping;
// auto-scroll into view runs only when `reveal_active_tab` is set by a view switch
// so manual horizontal scrolling can freely browse distant inactive tabs.
const FADE_STEP_W: f32 = 2.0;
const FADE_STEPS: usize = 4;
const FADE_W: f32 = FADE_STEP_W * FADE_STEPS as f32;
let total_w: f32 = measured_tabs.iter().map(|t| t.w).sum::<f32>()
+ measured_tabs.len().saturating_sub(1) as f32 * tab_gap;
let max_scroll = (total_w - strip_w).max(0.0);
@@ -278,13 +281,25 @@ pub fn layout_database_block(
let mut scroll_x = (ui_state.view_tabs_scroll_px as f32).clamp(0.0, max_scroll);
if ui_state.reveal_active_tab {
let mut tab_offset = 0.0_f32;
for tab in &measured_tabs {
let last_idx = measured_tabs.len().saturating_sub(1);
for (idx, tab) in measured_tabs.iter().enumerate() {
if tab.is_active {
let left_pad = if idx > 0 && max_scroll > FADE_W {
FADE_W + 4.0
} else {
0.0
};
let right_pad = if idx < last_idx && max_scroll > FADE_W {
FADE_W + 4.0
} else {
0.0
};
let tab_end = tab_offset + tab.w;
if tab_end > scroll_x + strip_w {
scroll_x = (tab_end - strip_w).clamp(0.0, max_scroll);
} else if tab_offset < scroll_x {
scroll_x = tab_offset.clamp(0.0, max_scroll);
if tab_end + right_pad > scroll_x + strip_w {
scroll_x = (tab_end + right_pad - strip_w).clamp(0.0, max_scroll);
}
if tab_offset - left_pad < scroll_x {
scroll_x = (tab_offset - left_pad).clamp(0.0, max_scroll);
}
break;
}
@@ -294,13 +309,49 @@ pub fn layout_database_block(
view_tabs_scroll_px = scroll_x.round() as i32;
let clip_rect = axis.map_rect(FlowRect::new(strip_left, y, strip_w, tab_h));
let mut cursor = strip_left - scroll_x;
let mut active_bounds: Option<(f32, f32)> = None;
for tab in &measured_tabs {
let tab_right = cursor + tab.w;
if tab.is_active {
active_bounds = Some((cursor, tab_right));
}
if tab_right > strip_left + 1.0 && cursor < strip_right - 1.0 {
emit_tab(tab, cursor, y, Some(clip_rect));
}
cursor += tab.w + tab_gap;
}
let right_overlaps_active =
active_bounds.is_some_and(|(l, r)| r > strip_right - FADE_W && l < strip_right);
let left_overlaps_active =
active_bounds.is_some_and(|(l, r)| l < strip_left + FADE_W && r > strip_left);
if max_scroll - scroll_x > FADE_W && !right_overlaps_active {
for (i, a) in [0.15_f32, 0.38, 0.65, 0.88].into_iter().enumerate() {
let rx = strip_right - FADE_STEP_W * (FADE_STEPS - i) as f32;
if rx >= strip_left {
prims.push(DatabasePrim::Quad {
rect: axis.map_rect(FlowRect::new(rx, y, FADE_STEP_W, tab_h)),
fill: Some(palette.background.opacity(a)),
border: None,
radius: 0.0,
dashed: false,
});
}
}
}
if scroll_x > FADE_W && !left_overlaps_active {
for (i, a) in [0.88_f32, 0.65, 0.38, 0.15].into_iter().enumerate() {
let rx = strip_left + i as f32 * FADE_STEP_W;
if rx + FADE_STEP_W <= strip_right {
prims.push(DatabasePrim::Quad {
rect: axis.map_rect(FlowRect::new(rx, y, FADE_STEP_W, tab_h)),
fill: Some(palette.background.opacity(a)),
border: None,
radius: 0.0,
dashed: false,
});
}
}
}
} else {
// Desktop: single horizontal toolbar row when wide enough; wraps Filter/Sort/Group onto
// a dedicated second row on narrow containers (`390px`) so tabs never collide with tools.
@@ -275,7 +275,7 @@ pub(super) fn render_db_visual_evidence(
(PlaygroundTheme::Dark, "dark"),
] {
for (view_id, view_name) in views {
let (state, db_id) = build_db_visual_doc()?;
let (state, db_id) = build_db_visual_doc_ext(false)?;
let session = start_headless_session(
1280,
860,
@@ -296,7 +296,7 @@ pub(super) fn render_db_visual_evidence(
if include_phone {
for (view_id, view_name) in views {
let (state, db_id) = build_db_visual_doc()?;
let (state, db_id) = build_db_visual_doc_ext(false)?;
let session = start_headless_session(
390,
844,
@@ -315,6 +315,51 @@ pub(super) fn render_db_visual_evidence(
let stem = format!("{prefix}-db-phone-{view_name}-light");
save_session_png(&session, &out_dir.join(format!("{stem}.png")), &stem)?;
}
for (theme, theme_name) in [
(PlaygroundTheme::Light, "light"),
(PlaygroundTheme::Dark, "dark"),
] {
let (state, db_id) = build_db_visual_doc_ext(true)?;
let session = start_headless_session(
390,
844,
PlaygroundOptions {
theme,
form_factor: playground::FormFactor::Phone,
database_readonly: false,
..Default::default()
},
)?;
session.view(|v, cx| {
v.set_document(state, cx);
v.set_database_active_view(&db_id, "v-roadmap", cx);
})?;
session.settle(120);
let stem = format!("{prefix}-db-phone-tabs-overflow-{theme_name}");
save_session_png(&session, &out_dir.join(format!("{stem}.png")), &stem)?;
// Showcase 3-tab strip (`Table View / Kanban View / Calendar View`) at 390x844:
// verifies `Calendar View` is 100% uncovered when non-overflowing or within 12px threshold.
let showcase_session = start_headless_session(
390,
844,
PlaygroundOptions {
theme,
form_factor: playground::FormFactor::Phone,
..Default::default()
},
)?;
showcase_session.view(|v, cx| {
let _ = v.scroll_to_block("showcase-database", cx);
})?;
showcase_session.settle(120);
let showcase_stem = format!("{prefix}-db-phone-showcase-3views-{theme_name}");
save_session_png(
&showcase_session,
&out_dir.join(format!("{showcase_stem}.png")),
&showcase_stem,
)?;
}
}
Ok(())
@@ -28,6 +28,7 @@ mod tests_slash_linked_table;
#[cfg(test)]
mod tests_tree_dnd_and_marquee;
mod view_scrollbar;
mod view_share_ingest;
mod view_slash_blocks;
mod view_slash_extended;
mod view_table_cell;
@@ -36,6 +37,7 @@ mod wasm_html_embeds;
pub use blocksuite_editor::overlays::*;
pub(crate) use view_context_menu::{ContextTargetKind, ContextTargetSnapshot};
pub use view_share_ingest::{SharedNoteBlockItem, SharedNoteBlockKind};
pub(crate) use view_table_cell::InlineTargetEnd;
impl OverlayHost for crate::PlaygroundView {
@@ -0,0 +1,252 @@
//! Non-destructive share-item block ingestion on [`PlaygroundView`]:
//! appends `Bookmark`, `Paragraph::Quote`, and SHA-256 `Image` blocks into the
//! active Page-visible `affine:note` without touching `DocumentSelection` or IME state.
use std::sync::Arc;
use blocksuite_playground_doc::{
read::BlockNode,
schema::{BlockSpec, ParagraphType},
};
use ui::{Context, Window};
use crate::PlaygroundView;
use super::sha256_base64url;
fn block_node_to_json(node: &BlockNode) -> serde_json::Value {
serde_json::json!({
"id": node.id,
"flavour": node.flavour,
"version": node.version,
"props": node.props,
"children": node.children.iter().map(block_node_to_json).collect::<Vec<_>>(),
})
}
/// One pre-validated shared item to append as a real BlockSuite block.
#[derive(Debug, Clone)]
pub struct SharedNoteBlockItem {
/// Original queue identifier returned on successful or idempotent commit.
pub queue_id: String,
/// Sanitized identifier component used to derive the deterministic `block_id`.
pub share_id: String,
pub spec: SharedNoteBlockKind,
}
/// Supported shared block kinds for live `PlaygroundView` append.
#[derive(Debug, Clone)]
pub enum SharedNoteBlockKind {
Bookmark {
url: String,
title: String,
},
Quote {
text: String,
},
Image {
caption: String,
bytes: Vec<u8>,
},
Pdf {
file_name: String,
mime_type: String,
bytes: Vec<u8>,
},
}
impl PlaygroundView {
/// Returns `true` when the active Page surface is locked read-only.
pub fn is_page_readonly(&self) -> bool {
self.page_readonly
}
/// Serializes the active `PageSnapshot` as JSON for host verification.
pub fn active_page_snapshot_json(&self) -> Option<String> {
let snap = self.snapshot.as_ref()?;
let val = serde_json::json!({
"docId": snap.doc_id,
"root": snap.root.as_ref().map(block_node_to_json),
"detached": snap.detached.iter().map(block_node_to_json).collect::<Vec<_>>(),
});
serde_json::to_string(&val).ok()
}
/// Inserts `items` at the top of the active Page-visible `affine:note` while preserving
/// any active `DocumentSelection` (`[anchor, focus)` and IME focused block) untouched.
/// Returns the exact `queue_id`s committed (or already idempotently present), never
/// marking skipped/failed items as consumed.
pub fn append_shared_blocks_preserving_selection(
&mut self,
items: &[SharedNoteBlockItem],
now_ms: u64,
window: &mut Window,
cx: &mut Context<Self>,
) -> Vec<String> {
if self.page_readonly || items.is_empty() {
return Vec::new();
}
let Some(note_id) = self.snapshot.as_ref().and_then(|snap| {
snap.root
.as_ref()?
.children
.iter()
.find(|c| c.is_page_visible_note())
.map(|c| c.id.clone())
}) else {
return Vec::new();
};
let mut prepared: Vec<(String, String, BlockSpec, Option<usize>)> =
Vec::with_capacity(items.len());
for item in items {
let block_id = format!("share-{}-live", item.share_id);
match &item.spec {
SharedNoteBlockKind::Bookmark { url, title } => {
if url.trim().is_empty() {
continue;
}
prepared.push((
item.queue_id.clone(),
block_id,
BlockSpec::Bookmark {
url: url.clone(),
title: (!title.is_empty()).then(|| title.clone()),
description: None,
},
None,
));
}
SharedNoteBlockKind::Quote { text } => {
if text.trim().is_empty() {
continue;
}
prepared.push((
item.queue_id.clone(),
block_id,
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Quote,
text: text.clone(),
},
None,
));
}
SharedNoteBlockKind::Image { caption, bytes } => {
if bytes.is_empty() || bytes.len() > 64 * 1024 * 1024 {
continue;
}
let source_id = sha256_base64url(bytes);
let shared = Arc::new(bytes.clone());
self.state.blobs.insert(source_id.clone(), shared.clone());
self.queue_blob_upload(source_id.clone(), shared, cx);
prepared.push((
item.queue_id.clone(),
block_id,
BlockSpec::Image {
source_id,
caption: caption.clone(),
width: 0.0,
height: 0.0,
xywh: None,
},
Some(bytes.len()),
));
}
SharedNoteBlockKind::Pdf {
file_name,
mime_type,
bytes,
} => {
if bytes.is_empty() || bytes.len() > 64 * 1024 * 1024 {
continue;
}
let source_id = sha256_base64url(bytes);
let shared = Arc::new(bytes.clone());
self.state.blobs.insert(source_id.clone(), shared.clone());
self.queue_blob_upload(source_id.clone(), shared, cx);
let clean_name = if file_name.trim().is_empty() {
"shared-document.pdf".to_string()
} else {
file_name.trim().to_string()
};
let clean_mime = if mime_type.trim().is_empty() {
"application/pdf".to_string()
} else {
mime_type.trim().to_string()
};
prepared.push((
item.queue_id.clone(),
block_id,
BlockSpec::Attachment {
name: clean_name,
size: bytes.len() as i64,
mime_type: clean_mime,
source_id,
caption: String::new(),
embed: true,
},
None,
));
}
}
}
if prepared.is_empty() {
return Vec::new();
}
let before = self.selection_snapshot();
let preserved_selection = self.editor.selection.clone();
let mut committed_ids = Vec::with_capacity(prepared.len());
let mut inserted_any = false;
let commit = self.page_mut().ok().and_then(|page| {
let _ = page.stop_capturing();
let sv_before = page.encode_state_vector_v1().ok()?;
let mut last_commit = None;
for (slot, (queue_id, block_id, spec, image_size)) in prepared.iter().enumerate() {
if page.read_page_snapshot().ok()?.block(block_id).is_some() {
committed_ids.push(queue_id.clone());
continue;
}
if let Some(c) = page
.add_block(
block_id,
spec.clone(),
Some(&note_id),
Some(slot as u64),
now_ms,
)
.ok()
.flatten()
{
if let Some(sz) = image_size {
let _ = page.set_block_size_bytes(block_id, *sz as i64, now_ms);
}
last_commit = Some(c);
inserted_any = true;
committed_ids.push(queue_id.clone());
}
}
if let Some(mut final_c) = last_commit {
if let Ok(diff) = page.encode_diff_v1(&sv_before) {
final_c.update = diff;
}
if let Some(before) = before {
let _ = page.set_undo_selection_snapshot(before);
}
let _ = page.stop_capturing();
Some(final_c)
} else {
let _ = page.stop_capturing();
None
}
});
if commit.is_some() && inserted_any {
self.did_edit(commit, None, window, cx);
if let Some(sel) = preserved_selection {
self.editor.selection = Some(sel);
}
}
committed_ids
}
}
+1
View File
@@ -8,6 +8,7 @@ pub mod directory;
pub mod error;
pub mod id_converter;
pub mod idb;
pub mod share_ingest;
#[cfg(not(target_family = "wasm"))]
pub mod sqlite;
pub mod sync;
@@ -0,0 +1,217 @@
//! Idempotent `0.27.5` `hasValidSharePlan` block-authoring helper for share imports.
use std::collections::BTreeMap;
use blocksuite_playground_doc::{
schema::{BlockSpec, ParagraphType},
session::PageDocSession,
};
use super::{
ShareIngestAttachmentSpec, ShareIngestRequest, SharePayloadKind, share_url_title,
sqlite_exec::check_plan_block,
};
use crate::error::{StoreError, StoreResult};
pub(super) fn author_share_blocks_idempotent(
session: &mut PageDocSession,
existing_blocks: &BTreeMap<String, (String, Option<String>)>,
note_id: &str,
prefix: &str,
req: &ShareIngestRequest,
attachment_slices: &[(&ShareIngestAttachmentSpec, &[u8], String)],
mut ts: u64,
) -> StoreResult<(String, bool)> {
let title = req.title.trim();
let primary = req.text_or_url.trim();
let secondary = req.secondary_text.trim();
let mut mutated = false;
match req.kind {
SharePayloadKind::Url => {
let b_id = format!("{prefix}-bookmark");
if !check_plan_block(existing_blocks, &b_id, "affine:bookmark", Some(note_id))? {
let b_title = (!title.is_empty()).then(|| title.to_string());
session
.add_block(
&b_id,
BlockSpec::Bookmark {
url: primary.to_string(),
title: b_title,
description: None,
},
Some(note_id),
None,
ts,
)
.map_err(|e| StoreError::YOcto(e.to_string()))?;
mutated = true;
}
ts = ts.saturating_add(1);
if !secondary.is_empty() {
let q_id = format!("{prefix}-selected-text");
if !check_plan_block(existing_blocks, &q_id, "affine:paragraph", Some(note_id))? {
session
.add_block(
&q_id,
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Quote,
text: secondary.to_string(),
},
Some(note_id),
None,
ts,
)
.map_err(|e| StoreError::YOcto(e.to_string()))?;
mutated = true;
}
}
Ok((primary.to_string(), mutated))
}
SharePayloadKind::Text => {
let q_id = format!("{prefix}-selected-text");
if !check_plan_block(existing_blocks, &q_id, "affine:paragraph", Some(note_id))? {
session
.add_block(
&q_id,
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Quote,
text: primary.to_string(),
},
Some(note_id),
None,
ts,
)
.map_err(|e| StoreError::YOcto(e.to_string()))?;
mutated = true;
}
ts = ts.saturating_add(1);
if secondary.starts_with("https://") || secondary.starts_with("http://") {
let s_id = format!("{prefix}-source-link");
if !check_plan_block(existing_blocks, &s_id, "affine:bookmark", Some(note_id))? {
let link_title = if title.is_empty() {
Some(share_url_title(secondary))
} else {
Some(title.to_string())
};
session
.add_block(
&s_id,
BlockSpec::Bookmark {
url: secondary.to_string(),
title: link_title,
description: None,
},
Some(note_id),
None,
ts,
)
.map_err(|e| StoreError::YOcto(e.to_string()))?;
mutated = true;
}
}
Ok((primary.to_string(), mutated))
}
SharePayloadKind::Image | SharePayloadKind::Pdf => {
if !secondary.is_empty() {
let q_id = format!("{prefix}-selected-text");
if !check_plan_block(existing_blocks, &q_id, "affine:paragraph", Some(note_id))? {
session
.add_block(
&q_id,
BlockSpec::Paragraph {
paragraph_type: ParagraphType::Quote,
text: secondary.to_string(),
},
Some(note_id),
None,
ts,
)
.map_err(|e| StoreError::YOcto(e.to_string()))?;
mutated = true;
}
ts = ts.saturating_add(1);
}
if primary.starts_with("https://") || primary.starts_with("http://") {
let s_id = format!("{prefix}-source-link");
if !check_plan_block(existing_blocks, &s_id, "affine:bookmark", Some(note_id))? {
let link_title = if title.is_empty() {
Some(share_url_title(primary))
} else {
Some(title.to_string())
};
session
.add_block(
&s_id,
BlockSpec::Bookmark {
url: primary.to_string(),
title: link_title,
description: None,
},
Some(note_id),
None,
ts,
)
.map_err(|e| StoreError::YOcto(e.to_string()))?;
mutated = true;
}
ts = ts.saturating_add(1);
}
let mut summary_keys = Vec::with_capacity(attachment_slices.len());
for (idx, &(spec, data, ref content_key)) in attachment_slices.iter().enumerate() {
let (block_id, expected_flavour) = match (req.kind, idx) {
(SharePayloadKind::Image, 0) => (format!("{prefix}-image"), "affine:image"),
(SharePayloadKind::Image, n) => (format!("{prefix}-image-{n}"), "affine:image"),
(_, 0) => (format!("{prefix}-attachment"), "affine:attachment"),
(_, n) => (format!("{prefix}-attachment-{n}"), "affine:attachment"),
};
if !check_plan_block(existing_blocks, &block_id, expected_flavour, Some(note_id))? {
match req.kind {
SharePayloadKind::Image => {
session
.add_block(
&block_id,
BlockSpec::Image {
source_id: content_key.clone(),
caption: String::new(),
width: 0.0,
height: 0.0,
xywh: None,
},
Some(note_id),
None,
ts,
)
.map_err(|e| StoreError::YOcto(e.to_string()))?;
session
.set_block_size_bytes(&block_id, data.len() as i64, ts)
.map_err(|e| StoreError::YOcto(e.to_string()))?;
}
_ => {
session
.add_block(
&block_id,
BlockSpec::Attachment {
name: spec.file_name.clone(),
size: data.len() as i64,
mime_type: spec.mime_type.clone(),
source_id: content_key.clone(),
caption: String::new(),
embed: true,
},
Some(note_id),
None,
ts,
)
.map_err(|e| StoreError::YOcto(e.to_string()))?;
}
}
mutated = true;
}
ts = ts.saturating_add(1);
summary_keys.push(content_key.clone());
}
Ok((summary_keys.join("\n"), mutated))
}
}
}
@@ -0,0 +1,283 @@
//! Canonical `0.27.5`-compatible ShareExtension / `ACTION_SEND` ingestion coordinator shared by
//! iOS and Android thin hosts (`ImportClipperService.importShareToWorkspace`, `import.ts:94-379`).
//!
//! Persists SHA-256 content-addressed attachment blobs (`blobs`), incremental CRDT updates
//! (`updates` + `clocks` for `<docId>`, `<workspaceId>`, and `db$docProperties`), destination
//! tags & collection membership (`meta.pages[doc].tags` + `setting.collections[id].allowList`),
//! the `0.27.5` `affine:share-import-receipt-v1` property, and `share_ingest_receipts` inside a
//! single `BEGIN IMMEDIATE ... COMMIT` SQLite transaction.
#[cfg(not(target_family = "wasm"))]
mod author_blocks;
#[cfg(not(target_family = "wasm"))]
mod sqlite_exec;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use crate::error::{StoreError, StoreResult};
#[cfg(not(target_family = "wasm"))]
pub use sqlite_exec::{ingest_share_item_into_sqlite, is_share_durably_committed};
/// Canonical App Group identifier shared between the iOS app and ShareExtension.
pub const IOS_APP_GROUP_ID: &str = "group.app.affine.pro";
/// Maximum per-attachment and per-item total attachment payload size (`64 MiB`),
/// matching `0.27.5` `maxShareAttachmentBytes` (`import.ts:46`).
pub const MAX_SHARE_ATTACHMENT_BYTES: usize = 64 * 1024 * 1024;
/// Custom doc-property key written by `0.27.5` `ImportClipperService` (`share-import-receipt.ts:1`).
pub const SHARE_IMPORT_RECEIPT_PROPERTY_ID: &str = "affine:share-import-receipt-v1";
/// Supported share payload kinds matching `ShareInboxContentKind`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SharePayloadKind {
Url,
Text,
Image,
Pdf,
}
/// Metadata for one attachment slice inside the contiguous `blob_bytes` buffer.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ShareIngestAttachmentSpec {
#[serde(default)]
pub blob_key: String,
pub file_name: String,
pub mime_type: String,
pub byte_offset: usize,
pub byte_len: usize,
}
/// Request payload passed to `ingest_share_item_into_sqlite`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ShareIngestRequest {
pub share_id: String,
#[serde(default)]
pub import_attempt_id: String,
pub doc_id: String,
pub kind: SharePayloadKind,
#[serde(default)]
pub title: String,
#[serde(default)]
pub text_or_url: String,
#[serde(default)]
pub secondary_text: String,
#[serde(default)]
pub tag_ids: Vec<String>,
#[serde(default)]
pub collection_id: Option<String>,
#[serde(default)]
pub attachments: Vec<ShareIngestAttachmentSpec>,
#[serde(default)]
pub client_id: u64,
pub now_ms: i64,
}
/// Result returned from the atomic SQLite share-ingest transaction.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ShareIngestOutcome {
pub already_committed: bool,
pub doc_id: String,
pub inserted_text: String,
pub blob_keys: Vec<String>,
}
/// Encodes a 32-byte SHA-256 digest as 44-character padded base64url (`[A-Za-z0-9_-]{43}=`),
/// matching BlockSuite `0.27.5` `sha()` / `blobSync.set` (`import.ts:212`).
pub fn sha256_base64url(bytes: &[u8]) -> String {
const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
let digest = Sha256::digest(bytes);
let mut out = String::with_capacity(44);
let mut i = 0usize;
while i + 3 <= 32 {
let n = ((digest[i] as u32) << 16) | ((digest[i + 1] as u32) << 8) | (digest[i + 2] as u32);
out.push(TABLE[((n >> 18) & 0x3f) as usize] as char);
out.push(TABLE[((n >> 12) & 0x3f) as usize] as char);
out.push(TABLE[((n >> 6) & 0x3f) as usize] as char);
out.push(TABLE[(n & 0x3f) as usize] as char);
i += 3;
}
let rem = ((digest[30] as u32) << 16) | ((digest[31] as u32) << 8);
out.push(TABLE[((rem >> 18) & 0x3f) as usize] as char);
out.push(TABLE[((rem >> 12) & 0x3f) as usize] as char);
out.push(TABLE[((rem >> 6) & 0x3f) as usize] as char);
out.push('=');
out
}
/// Reconcile `(rootTitle, pageTitle, importTitle)` 1:1 with `0.27.5` `reconcileShareTitles`
/// (`share-block-plan.ts:53-70`): empty titles remain `""`, never falling back to `doc_id`.
pub fn reconcile_share_titles(
root_title: &str,
page_title: &str,
import_title: &str,
) -> (String, String) {
let root = root_title.trim();
let page = page_title.trim();
if !root.is_empty() && !page.is_empty() {
return (root_title.to_string(), page_title.to_string());
}
let chosen = if !root.is_empty() {
root
} else if !page.is_empty() {
page
} else {
import_title.trim()
};
(
if !root.is_empty() {
root_title.to_string()
} else {
chosen.to_string()
},
if !page.is_empty() {
page_title.to_string()
} else {
chosen.to_string()
},
)
}
/// Fallback bookmark title matching `0.27.5` `shareUrlTitle(url)` (`share-block-plan.ts:31-37`).
pub fn share_url_title(raw_url: &str) -> String {
url::Url::parse(raw_url)
.ok()
.and_then(|u| u.host_str().map(str::to_string))
.filter(|h| !h.is_empty())
.unwrap_or_else(|| raw_url.to_string())
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum JsShareReceiptState {
Preparing,
Committed,
}
/// Parse `affine:share-import-receipt-v1` strictly matching `parseShareImportReceipt`
/// (`share-import-receipt.ts:17-41`).
pub fn parse_js_share_receipt(raw: &str) -> Option<(String, JsShareReceiptState)> {
let parsed: serde_json::Value = serde_json::from_str(raw).ok()?;
let obj = parsed.as_object()?;
if obj.len() != 3 {
return None;
}
if obj.get("version")?.as_i64() != Some(1) {
return None;
}
let attempt_id = obj.get("attemptId")?.as_str()?;
if attempt_id.is_empty() {
return None;
}
let state = match obj.get("state")?.as_str()? {
"preparing" => JsShareReceiptState::Preparing,
"committed" => JsShareReceiptState::Committed,
_ => return None,
};
Some((attempt_id.to_string(), state))
}
pub fn serialize_js_share_receipt(attempt_id: &str, state: JsShareReceiptState) -> String {
let state_str = match state {
JsShareReceiptState::Preparing => "preparing",
JsShareReceiptState::Committed => "committed",
};
serde_json::json!({
"version": 1,
"attemptId": attempt_id,
"state": state_str,
})
.to_string()
}
pub fn effective_attempt_id(req: &ShareIngestRequest) -> &str {
let attempt = req.import_attempt_id.trim();
if attempt.is_empty() {
req.share_id.trim()
} else {
attempt
}
}
pub fn validate_share_request<'a>(
req: &'a ShareIngestRequest,
blob_bytes: &'a [u8],
) -> StoreResult<Vec<(&'a ShareIngestAttachmentSpec, &'a [u8], String)>> {
if req.share_id.trim().is_empty() {
return Err(StoreError::InvalidProtocol(
"share_id must be non-empty".into(),
));
}
if req.doc_id.trim().is_empty()
|| req.doc_id.starts_with("db$")
|| req.doc_id.starts_with("userdata$")
{
return Err(StoreError::InvalidProtocol(
"doc_id must be a valid canonical document ID".into(),
));
}
if blob_bytes.len() > MAX_SHARE_ATTACHMENT_BYTES {
return Err(StoreError::InvalidProtocol(
"total attachment bytes exceed 64 MiB limit".into(),
));
}
let mut total_slice_bytes = 0usize;
let mut slices = Vec::with_capacity(req.attachments.len());
for att in &req.attachments {
if att.byte_len == 0 || att.byte_len > MAX_SHARE_ATTACHMENT_BYTES {
return Err(StoreError::InvalidProtocol(
"attachment byte_len empty or exceeds 64 MiB limit".into(),
));
}
total_slice_bytes = total_slice_bytes
.checked_add(att.byte_len)
.ok_or_else(|| StoreError::InvalidProtocol("attachment byte total overflow".into()))?;
if total_slice_bytes > MAX_SHARE_ATTACHMENT_BYTES {
return Err(StoreError::InvalidProtocol(
"cumulative attachment bytes exceed 64 MiB limit".into(),
));
}
let end = att
.byte_offset
.checked_add(att.byte_len)
.ok_or_else(|| StoreError::InvalidProtocol("attachment slice overflow".into()))?;
if end > blob_bytes.len() {
return Err(StoreError::InvalidProtocol(
"attachment byte slice out of bounds".into(),
));
}
let data = &blob_bytes[att.byte_offset..end];
let content_key = sha256_base64url(data);
slices.push((att, data, content_key));
}
match req.kind {
SharePayloadKind::Url => {
let url = req.text_or_url.trim();
if !(url.starts_with("https://") || url.starts_with("http://")) {
return Err(StoreError::InvalidProtocol(
"share url must use http(s) scheme".into(),
));
}
}
SharePayloadKind::Text => {
if req.text_or_url.trim().is_empty() {
return Err(StoreError::InvalidProtocol(
"share text must be non-empty".into(),
));
}
}
SharePayloadKind::Image | SharePayloadKind::Pdf => {
if slices.is_empty() {
return Err(StoreError::InvalidProtocol(
"image/pdf share item requires at least one attachment blob".into(),
));
}
}
}
Ok(slices)
}
@@ -0,0 +1,595 @@
//! Atomic `BEGIN IMMEDIATE ... COMMIT` SQLite share-ingestion transaction.
use std::collections::BTreeMap;
use std::path::Path;
use std::time::Duration;
use blocksuite_playground_doc::{
read::{BlockNode, PageSnapshot},
schema::BlockSpec,
session::PageDocSession,
};
use sqlx::{
Connection, Row, SqliteConnection,
sqlite::{SqliteConnectOptions, SqliteJournalMode, SqliteSynchronous},
};
use super::{
JsShareReceiptState, SHARE_IMPORT_RECEIPT_PROPERTY_ID, ShareIngestAttachmentSpec,
ShareIngestOutcome, ShareIngestRequest, author_blocks::author_share_blocks_idempotent,
effective_attempt_id, parse_js_share_receipt, reconcile_share_titles,
serialize_js_share_receipt, validate_share_request,
};
use crate::{
error::{StoreError, StoreResult},
sqlite::millis_to_naive_utc,
workspace_db::{PageIdSource, WorkspaceDbTableName, WorkspaceRootDoc, YjsTableDoc},
};
const BUSY_TIMEOUT_MS: u64 = 5_000;
fn pick_yjs_client_id(requested: u64) -> u64 {
let masked = (requested & u64::from(u32::MAX)) as u32;
if masked != 0 {
return u64::from(masked);
}
let rnd = (blocksuite_playground_doc::random_client_id() & u64::from(u32::MAX)) as u32;
u64::from(if rnd == 0 { 1 } else { rnd })
}
pub async fn ingest_share_item_into_sqlite(
db_path: &Path,
workspace_id: &str,
req: &ShareIngestRequest,
blob_bytes: &[u8],
) -> StoreResult<ShareIngestOutcome> {
let attachment_slices = validate_share_request(req, blob_bytes)?;
let opts = SqliteConnectOptions::new()
.filename(db_path)
.foreign_keys(true)
.synchronous(SqliteSynchronous::Full)
.journal_mode(SqliteJournalMode::Wal)
.busy_timeout(Duration::from_millis(BUSY_TIMEOUT_MS));
let mut conn = SqliteConnection::connect_with(&opts).await?;
sqlx::query(
"CREATE TABLE IF NOT EXISTS share_ingest_receipts (\
share_id TEXT PRIMARY KEY NOT NULL,\
doc_id TEXT NOT NULL,\
committed_at INTEGER NOT NULL\
);",
)
.execute(&mut conn)
.await?;
sqlx::query("BEGIN IMMEDIATE;").execute(&mut conn).await?;
let tx_res = run_share_ingest_tx(&mut conn, workspace_id, req, &attachment_slices).await;
match tx_res {
Ok(outcome) => {
sqlx::query("COMMIT;").execute(&mut conn).await?;
let _ = conn.close().await;
Ok(outcome)
}
Err(err) => {
let _ = sqlx::query("ROLLBACK;").execute(&mut conn).await;
let _ = conn.close().await;
Err(err)
}
}
}
/// Returns `true` when `share_id` has a committed receipt row in `share_ingest_receipts`.
pub async fn is_share_durably_committed(db_path: &Path, share_id: &str) -> StoreResult<bool> {
let trimmed = share_id.trim();
if trimmed.is_empty() || !db_path.is_file() {
return Ok(false);
}
let opts = SqliteConnectOptions::new()
.filename(db_path)
.read_only(true)
.busy_timeout(Duration::from_millis(BUSY_TIMEOUT_MS));
let mut conn = SqliteConnection::connect_with(&opts).await?;
let table_exists = sqlx::query(
"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'share_ingest_receipts';",
)
.fetch_optional(&mut conn)
.await?
.is_some();
if !table_exists {
let _ = conn.close().await;
return Ok(false);
}
let found = sqlx::query("SELECT 1 FROM share_ingest_receipts WHERE share_id = $1;")
.bind(trimmed)
.fetch_optional(&mut conn)
.await?
.is_some();
let _ = conn.close().await;
Ok(found)
}
async fn read_doc_updates(
conn: &mut SqliteConnection,
doc_id: &str,
) -> StoreResult<(Option<Vec<u8>>, Vec<Vec<u8>>)> {
let snap_row = sqlx::query("SELECT data FROM snapshots WHERE doc_id = $1;")
.bind(doc_id)
.fetch_optional(&mut *conn)
.await?;
let snap = match snap_row {
Some(r) => {
let bin: Vec<u8> = r.try_get("data")?;
(!bin.is_empty() && bin != [0, 0]).then_some(bin)
}
None => None,
};
let rows = sqlx::query("SELECT data FROM updates WHERE doc_id = $1 ORDER BY created_at;")
.bind(doc_id)
.fetch_all(&mut *conn)
.await?;
let mut updates = Vec::with_capacity(rows.len());
for r in rows {
let bin: Vec<u8> = r.try_get("data")?;
if !bin.is_empty() && bin != [0, 0] {
updates.push(bin);
}
}
Ok((snap, updates))
}
async fn append_doc_update_and_clock(
conn: &mut SqliteConnection,
doc_id: &str,
delta: &[u8],
base_ts: chrono::NaiveDateTime,
) -> StoreResult<()> {
if delta.is_empty() || delta == [0, 0] {
return Ok(());
}
let existing_clock: Option<chrono::NaiveDateTime> =
sqlx::query("SELECT timestamp FROM clocks WHERE doc_id = $1;")
.bind(doc_id)
.fetch_optional(&mut *conn)
.await?
.map(|row| row.try_get("timestamp"))
.transpose()?;
let effective_ts = match existing_clock {
Some(clock_ts) if clock_ts >= base_ts => clock_ts + chrono::Duration::milliseconds(1),
_ => base_ts,
};
sqlx::query("INSERT INTO updates (doc_id, data, created_at) VALUES ($1, $2, $3);")
.bind(doc_id)
.bind(delta)
.bind(effective_ts)
.execute(&mut *conn)
.await?;
sqlx::query(
"INSERT INTO clocks (doc_id, timestamp) VALUES ($1, $2) \
ON CONFLICT(doc_id) DO UPDATE SET timestamp = MAX(clocks.timestamp, excluded.timestamp);",
)
.bind(doc_id)
.bind(effective_ts)
.execute(&mut *conn)
.await?;
Ok(())
}
fn collect_existing_blocks(snap: &PageSnapshot) -> BTreeMap<String, (String, Option<String>)> {
let mut map = BTreeMap::new();
fn visit(
node: &BlockNode,
parent: Option<&str>,
out: &mut BTreeMap<String, (String, Option<String>)>,
) {
out.insert(
node.id.clone(),
(node.flavour.clone(), parent.map(str::to_string)),
);
for child in &node.children {
visit(child, Some(&node.id), out);
}
}
if let Some(ref root) = snap.root {
visit(root, None, &mut map);
}
for det in &snap.detached {
visit(det, None, &mut map);
}
map
}
pub(super) fn check_plan_block(
existing: &BTreeMap<String, (String, Option<String>)>,
block_id: &str,
expected_flavour: &str,
expected_parent: Option<&str>,
) -> StoreResult<bool> {
let Some((flavour, parent)) = existing.get(block_id) else {
return Ok(false);
};
if flavour != expected_flavour || parent.as_deref() != expected_parent {
return Err(StoreError::InvalidProtocol(format!(
"import-conflict: block {block_id:?} shape mismatch"
)));
}
Ok(true)
}
async fn run_share_ingest_tx(
conn: &mut SqliteConnection,
workspace_id: &str,
req: &ShareIngestRequest,
attachment_slices: &[(&ShareIngestAttachmentSpec, &[u8], String)],
) -> StoreResult<ShareIngestOutcome> {
if let Some(row) = sqlx::query("SELECT doc_id FROM share_ingest_receipts WHERE share_id = $1;")
.bind(&req.share_id)
.fetch_optional(&mut *conn)
.await?
{
let existing_doc_id: String = row.try_get("doc_id")?;
return Ok(ShareIngestOutcome {
already_committed: true,
doc_id: existing_doc_id,
inserted_text: String::new(),
blob_keys: Vec::new(),
});
}
let client_id = pick_yjs_client_id(req.client_id);
let attempt_id = effective_attempt_id(req);
let prefix = format!("share-{attempt_id}");
// 1. Load `db$docProperties` to honor `0.27.5` `affine:share-import-receipt-v1`.
let doc_props_id = WorkspaceDbTableName::DocProperties.local_doc_id();
let (dp_snap, dp_updates) = read_doc_updates(conn, &doc_props_id).await?;
let mut dp_table = YjsTableDoc::new(
&doc_props_id,
WorkspaceDbTableName::DocProperties.primary_key_field(),
WorkspaceDbTableName::DocProperties.known_fields(),
client_id,
);
if let Some(ref bin) = dp_snap {
dp_table.apply_update_v1(bin)?;
}
for bin in &dp_updates {
dp_table.apply_update_v1(bin)?;
}
let (doc_snap, doc_updates) = read_doc_updates(conn, &req.doc_id).await?;
let doc_exists_on_disk = doc_snap.is_some() || !doc_updates.is_empty();
let existing_js_receipt = dp_table
.get_raw_row(&req.doc_id)
.and_then(|row| row.get(SHARE_IMPORT_RECEIPT_PROPERTY_ID).cloned());
if let Some(raw_val) = existing_js_receipt {
let Some(raw_str) = raw_val.as_str() else {
return Err(StoreError::InvalidProtocol(
"import-conflict: malformed share import receipt".into(),
));
};
let Some((rec_attempt, rec_state)) = parse_js_share_receipt(raw_str) else {
return Err(StoreError::InvalidProtocol(
"import-conflict: invalid share import receipt JSON".into(),
));
};
if rec_attempt != attempt_id {
return Err(StoreError::InvalidProtocol(
"import-conflict: receipt attemptId mismatch".into(),
));
}
if rec_state == JsShareReceiptState::Committed {
if !doc_exists_on_disk {
return Err(StoreError::InvalidProtocol(
"import-conflict: committed receipt without document".into(),
));
}
sqlx::query(
"INSERT INTO share_ingest_receipts (share_id, doc_id, committed_at) VALUES ($1, $2, $3);",
)
.bind(&req.share_id)
.bind(&req.doc_id)
.bind(req.now_ms)
.execute(&mut *conn)
.await?;
return Ok(ShareIngestOutcome {
already_committed: true,
doc_id: req.doc_id.clone(),
inserted_text: String::new(),
blob_keys: Vec::new(),
});
}
}
// 2. Load workspace root doc early to validate `tag_ids` & `collection_id` before mutating.
let mut root_opt = if !workspace_id.is_empty() && workspace_id != req.doc_id {
let (root_snap, root_updates) = read_doc_updates(conn, workspace_id).await?;
let mut root = WorkspaceRootDoc::new(workspace_id, client_id);
if let Some(ref bin) = root_snap {
root.apply_remote_update(bin)?;
}
for bin in &root_updates {
root.apply_remote_update(bin)?;
}
let has_existing_page = root
.get_page(&req.doc_id)
.map_err(|e| StoreError::YOcto(e.to_string()))?
.is_some();
if !has_existing_page && !doc_exists_on_disk {
let defined_tags = root.defined_tag_ids()?;
for tag_id in req
.tag_ids
.iter()
.map(|s| s.trim())
.filter(|s| !s.is_empty())
{
if !defined_tags.contains(tag_id) {
return Err(StoreError::InvalidProtocol(format!(
"destination-not-found: missing tag {tag_id:?}"
)));
}
}
if let Some(col_id) = req
.collection_id
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
&& root.collection_allow_list(col_id)?.is_none()
{
return Err(StoreError::InvalidProtocol(format!(
"destination-not-found: missing collection {col_id:?}"
)));
}
}
Some(root)
} else {
None
};
// 3. Persist SHA-256 content-addressed blobs (`blobs`).
let mut blob_keys = Vec::with_capacity(attachment_slices.len());
for &(spec, data, ref content_key) in attachment_slices {
sqlx::query(
"INSERT INTO blobs (key, data, mime, size) VALUES ($1, $2, $3, $4) \
ON CONFLICT(key) DO UPDATE SET data = $2, mime = $3, size = $4, deleted_at = NULL;",
)
.bind(content_key)
.bind(data)
.bind(&spec.mime_type)
.bind(data.len() as i64)
.execute(&mut *conn)
.await?;
blob_keys.push(content_key.clone());
}
// 4. Reconstruct `PageDocSession`, validate `hasValidSharePlan`, and author missing blocks.
let mut session = PageDocSession::new(&req.doc_id, client_id)
.map_err(|e| StoreError::YOcto(e.to_string()))?;
if let Some(ref bin) = doc_snap {
session
.apply_remote_update_v1(bin)
.map_err(|e| StoreError::InvalidBinary(e.to_string()))?;
}
for bin in &doc_updates {
session
.apply_remote_update_v1(bin)
.map_err(|e| StoreError::InvalidBinary(e.to_string()))?;
}
let sv_before = if doc_exists_on_disk {
session
.encode_state_vector_v1()
.map_err(|e| StoreError::YOcto(e.to_string()))?
} else {
Vec::new()
};
let page_block_id = format!("{prefix}-page");
let surface_block_id = format!("{prefix}-surface");
let note_block_id = format!("{prefix}-note");
let (existing_blocks, current_page_title) = if doc_exists_on_disk {
let snap = session
.read_page_snapshot()
.map_err(|e| StoreError::YOcto(e.to_string()))?;
let map = collect_existing_blocks(&snap);
for (bid, (flav, _)) in &map {
if flav == "affine:page" && bid != &page_block_id {
return Err(StoreError::InvalidProtocol(
"import-conflict: foreign affine:page block in target document".into(),
));
}
if flav == "affine:surface" && bid != &surface_block_id {
return Err(StoreError::InvalidProtocol(
"import-conflict: foreign affine:surface block in target document".into(),
));
}
}
(map, snap.title().to_string())
} else {
(BTreeMap::new(), String::new())
};
let root_existing_title = root_opt
.as_ref()
.and_then(|r| r.get_page(&req.doc_id).ok().flatten())
.map(|p| p.title)
.unwrap_or_default();
let (next_root_title, next_page_title) =
reconcile_share_titles(&root_existing_title, &current_page_title, &req.title);
let mut ts = req.now_ms.max(0) as u64;
let mut did_mutate_doc = false;
if !check_plan_block(&existing_blocks, &page_block_id, "affine:page", None)? {
session
.add_block(
&page_block_id,
BlockSpec::Page {
title: next_page_title.clone(),
},
None,
None,
ts,
)
.map_err(|e| StoreError::YOcto(e.to_string()))?;
did_mutate_doc = true;
} else if next_page_title != current_page_title {
let old_utf16 = current_page_title.encode_utf16().count() as u64;
if old_utf16 > 0 {
session
.remove_text(&page_block_id, "prop:title", 0, old_utf16, ts)
.map_err(|e| StoreError::YOcto(e.to_string()))?;
}
if !next_page_title.is_empty() {
session
.insert_text(&page_block_id, "prop:title", 0, &next_page_title, ts)
.map_err(|e| StoreError::YOcto(e.to_string()))?;
}
did_mutate_doc = true;
}
ts = ts.saturating_add(1);
if !check_plan_block(
&existing_blocks,
&surface_block_id,
"affine:surface",
Some(&page_block_id),
)? {
session
.add_block(
&surface_block_id,
BlockSpec::Surface,
Some(&page_block_id),
None,
ts,
)
.map_err(|e| StoreError::YOcto(e.to_string()))?;
did_mutate_doc = true;
}
ts = ts.saturating_add(1);
if !check_plan_block(
&existing_blocks,
&note_block_id,
"affine:note",
Some(&page_block_id),
)? {
session
.add_block(
&note_block_id,
BlockSpec::Note {
xywh: Some("[0,0,800,600]".into()),
},
Some(&page_block_id),
None,
ts,
)
.map_err(|e| StoreError::YOcto(e.to_string()))?;
did_mutate_doc = true;
}
ts = ts.saturating_add(1);
let (inserted_text, leaf_mutated) = author_share_blocks_idempotent(
&mut session,
&existing_blocks,
&note_block_id,
&prefix,
req,
attachment_slices,
ts,
)?;
did_mutate_doc |= leaf_mutated;
let base_ts = millis_to_naive_utc(req.now_ms);
if did_mutate_doc {
let doc_delta = if doc_exists_on_disk {
session
.encode_diff_v1(&sv_before)
.map_err(|e| StoreError::YOcto(e.to_string()))?
} else {
session
.encode_update_v1()
.map_err(|e| StoreError::YOcto(e.to_string()))?
};
append_doc_update_and_clock(conn, &req.doc_id, &doc_delta, base_ts).await?;
}
// 5. Register page, reconcile root title, and apply `tag_ids` + `collection_id` via
// incremental transaction commits (zero historical delete-set re-encoding).
if let Some(ref mut root) = root_opt {
if !root.is_meta_initialized()
&& let Some(init_delta) = root.initialize_meta()?
{
append_doc_update_and_clock(conn, workspace_id, &init_delta, base_ts).await?;
}
let created = root.create_page(
PageIdSource::Explicit(&req.doc_id),
&next_root_title,
req.now_ms,
)?;
if let Some(create_delta) = created.update {
append_doc_update_and_clock(conn, workspace_id, &create_delta, base_ts).await?;
} else if next_root_title != root_existing_title
&& let Some(rename_delta) = root.rename_page(&req.doc_id, &next_root_title)?
{
append_doc_update_and_clock(conn, workspace_id, &rename_delta, base_ts).await?;
}
if let Some(dest_delta) = root.apply_share_destinations(
&req.doc_id,
&req.tag_ids,
req.collection_id.as_deref(),
false,
)? {
append_doc_update_and_clock(conn, workspace_id, &dest_delta, base_ts).await?;
}
}
// 6. Write `affine:share-import-receipt-v1` (`committed`) in `db$docProperties` and
// `share_ingest_receipts` inside the same SQLite transaction.
let receipt_json = serialize_js_share_receipt(attempt_id, JsShareReceiptState::Committed);
let dp_delta =
if dp_table.get_raw_row(&req.doc_id).is_some() && !dp_table.is_soft_deleted(&req.doc_id)? {
dp_table
.patch_row_fields(
&req.doc_id,
&[(
SHARE_IMPORT_RECEIPT_PROPERTY_ID,
Some(serde_json::Value::String(receipt_json)),
)],
)?
.unwrap_or_default()
} else {
let mut row_obj = serde_json::Map::new();
row_obj.insert("id".into(), serde_json::Value::String(req.doc_id.clone()));
row_obj.insert(
"primaryMode".into(),
serde_json::Value::String("page".into()),
);
row_obj.insert(
SHARE_IMPORT_RECEIPT_PROPERTY_ID.into(),
serde_json::Value::String(receipt_json),
);
dp_table.upsert_row(&serde_json::Value::Object(row_obj))?
};
append_doc_update_and_clock(conn, &doc_props_id, &dp_delta, base_ts).await?;
sqlx::query(
"INSERT INTO share_ingest_receipts (share_id, doc_id, committed_at) VALUES ($1, $2, $3);",
)
.bind(&req.share_id)
.bind(&req.doc_id)
.bind(req.now_ms)
.execute(&mut *conn)
.await?;
Ok(ShareIngestOutcome {
already_committed: false,
doc_id: req.doc_id.clone(),
inserted_text,
blob_keys,
})
}
@@ -1,4 +1,5 @@
pub mod root_doc;
pub mod share_destinations;
pub mod tables;
pub use root_doc::{
@@ -78,7 +78,7 @@ pub struct RemoteRootApply {
/// Authoritative coordinator for the AFFiNE workspace root YDoc (`meta.pages` + `spaces[pageId]`).
pub struct WorkspaceRootDoc {
space_id: String,
root: DocSession<()>,
pub(super) root: DocSession<()>,
baseline_sv: Vec<u8>,
local_writeback: bool,
revision: u64,
@@ -549,7 +549,7 @@ impl WorkspaceRootDoc {
/// even when `f` returns an error so subsequent `apply_update_v1` calls are never locked out.
///
/// Callers must finish all read-only validation before entering `with_tx`.
fn with_tx<F>(&mut self, f: F) -> StoreResult<Option<Vec<u8>>>
pub(super) fn with_tx<F>(&mut self, f: F) -> StoreResult<Option<Vec<u8>>>
where
F: FnOnce(&mut DocSession<()>) -> StoreResult<()>,
{
@@ -570,7 +570,7 @@ impl WorkspaceRootDoc {
Ok(commit.map(|c| c.update))
}
fn find_page_map_target(&self, page_id: &str) -> StoreResult<Option<TypeTarget>> {
pub(super) fn find_page_map_target(&self, page_id: &str) -> StoreResult<Option<TypeTarget>> {
let pages_target = TypeTarget::Path(TypePath::root("meta").key("pages"));
let Ok(items) = self.root.read_array(&pages_target) else {
return Ok(None);
@@ -0,0 +1,541 @@
//! `0.27.5` `ImportClipperService` destination metadata support (`meta.properties.tags.options`,
//! `meta.pages[doc].tags`, and `setting.collections[id].allowList`) for [`WorkspaceRootDoc`].
use std::collections::BTreeSet;
use y_octo::{Any, DocSession, SessionReadValue, SessionValue, TypePath, TypeTarget, YTypeKind};
use super::WorkspaceRootDoc;
use crate::error::{StoreError, StoreResult};
impl WorkspaceRootDoc {
/// Return all defined tag IDs in `meta.properties.tags.options` (supporting both `Y.Map`/`Y.Array`
/// written by BlockSuite proxies and plain `Any::Object`/`Any::Array` entries).
pub fn defined_tag_ids(&self) -> StoreResult<BTreeSet<String>> {
let mut out = BTreeSet::new();
let meta_target = TypeTarget::Path(TypePath::root("meta"));
let Ok(Some(props_val)) = self.root.get_map_value(&meta_target, "properties") else {
return Ok(out);
};
match props_val {
SessionReadValue::Map(props_id) => {
let props_target = TypeTarget::Identity(props_id);
let Ok(Some(tags_val)) = self.root.get_map_value(&props_target, "tags") else {
return Ok(out);
};
match tags_val {
SessionReadValue::Map(tags_id) => {
let tags_target = TypeTarget::Identity(tags_id);
let Ok(Some(opts_val)) = self.root.get_map_value(&tags_target, "options")
else {
return Ok(out);
};
collect_tag_ids_from_value(&self.root, &opts_val, &mut out)?;
}
SessionReadValue::Any(Any::Object(tags_obj)) => {
if let Some(opts_any) = tags_obj.get("options") {
collect_tag_ids_from_any(opts_any, &mut out);
}
}
_ => {}
}
}
SessionReadValue::Any(Any::Object(props_obj)) => {
if let Some(Any::Object(tags_obj)) = props_obj.get("tags")
&& let Some(opts_any) = tags_obj.get("options")
{
collect_tag_ids_from_any(opts_any, &mut out);
}
}
_ => {}
}
Ok(out)
}
/// Return the `allowList` document IDs of `collection_id` in `setting.collections`, or `None`
/// if the collection does not exist.
pub fn collection_allow_list(&self, collection_id: &str) -> StoreResult<Option<Vec<String>>> {
let collections_target = TypeTarget::Path(TypePath::root("setting").key("collections"));
let Ok(items) = self.root.read_array(&collections_target) else {
return Ok(None);
};
for item in items {
match item {
SessionReadValue::Any(Any::Object(obj)) => {
if matches!(obj.get("id"), Some(Any::String(id)) if id == collection_id) {
let mut allow = Vec::new();
if let Some(Any::Array(arr)) = obj.get("allowList") {
for v in arr {
if let Any::String(s) = v {
allow.push(s.clone());
}
}
}
return Ok(Some(allow));
}
}
SessionReadValue::Map(map_id) => {
let target = TypeTarget::Identity(map_id);
if matches!(
self.root
.get_map_value(&target, "id")
.map_err(|e| StoreError::YOcto(e.to_string()))?,
Some(SessionReadValue::Any(Any::String(ref id))) if id == collection_id
) {
let mut allow = Vec::new();
if let Some(allow_val) = self
.root
.get_map_value(&target, "allowList")
.map_err(|e| StoreError::YOcto(e.to_string()))?
{
match allow_val {
SessionReadValue::Array(arr_id) => {
for v in self
.root
.read_array(&TypeTarget::Identity(arr_id))
.map_err(|e| StoreError::YOcto(e.to_string()))?
{
if let SessionReadValue::Any(Any::String(s)) = v {
allow.push(s);
}
}
}
SessionReadValue::Any(Any::Array(arr)) => {
for v in arr {
if let Any::String(s) = v {
allow.push(s);
}
}
}
_ => {}
}
}
return Ok(Some(allow));
}
}
_ => {}
}
}
Ok(None)
}
/// Seed a tag definition into `meta.properties.tags.options` (matching `TagStore.createNewTag`
/// in `0.27.5`) so share-destination tests and local workspaces can register tags cleanly.
pub fn define_tag(
&mut self,
tag_id: &str,
name: &str,
color: &str,
now_ms: i64,
) -> StoreResult<Option<Vec<u8>>> {
if self.defined_tag_ids()?.contains(tag_id) {
return Ok(None);
}
let meta_id = self
.root
.ensure_root("meta", YTypeKind::Map)
.map_err(|e| StoreError::YOcto(e.to_string()))?;
let meta_target = TypeTarget::from(meta_id);
let existing_opts_arr = match self
.root
.get_map_value(&meta_target, "properties")
.map_err(|e| StoreError::YOcto(e.to_string()))?
{
Some(SessionReadValue::Map(props_id)) => {
let props_target = TypeTarget::Identity(props_id);
match self
.root
.get_map_value(&props_target, "tags")
.map_err(|e| StoreError::YOcto(e.to_string()))?
{
Some(SessionReadValue::Map(tags_id)) => {
let tags_target = TypeTarget::Identity(tags_id);
match self
.root
.get_map_value(&tags_target, "options")
.map_err(|e| StoreError::YOcto(e.to_string()))?
{
Some(SessionReadValue::Array(arr_id)) => {
Some(TypeTarget::Identity(arr_id))
}
_ => None,
}
}
_ => None,
}
}
_ => None,
};
let tag_entry = SessionValue::Map(vec![
("id".into(), SessionValue::Any(Any::String(tag_id.into()))),
("value".into(), SessionValue::Any(Any::String(name.into()))),
("color".into(), SessionValue::Any(Any::String(color.into()))),
(
"createDate".into(),
SessionValue::Any(Any::Float64((now_ms as f64).into())),
),
(
"updateDate".into(),
SessionValue::Any(Any::Float64((now_ms as f64).into())),
),
]);
self.with_tx(|root| {
if let Some(arr_target) = existing_opts_arr {
root.array_push(&arr_target, vec![tag_entry])
.map_err(|e| StoreError::YOcto(e.to_string()))?;
} else {
root.map_set(
&meta_target,
"properties".into(),
SessionValue::Map(vec![(
"tags".into(),
SessionValue::Map(vec![(
"options".into(),
SessionValue::Array(vec![tag_entry]),
)]),
)]),
)
.map_err(|e| StoreError::YOcto(e.to_string()))?;
}
Ok(())
})
}
/// Seed a collection in `setting.collections` (matching `CollectionStore.createCollection`
/// in `0.27.5`: `{ id, name, rules: { filters: [] }, allowList: [] }`).
pub fn define_collection(
&mut self,
collection_id: &str,
name: &str,
) -> StoreResult<Option<Vec<u8>>> {
if self.collection_allow_list(collection_id)?.is_some() {
return Ok(None);
}
let setting_id = self
.root
.ensure_root("setting", YTypeKind::Map)
.map_err(|e| StoreError::YOcto(e.to_string()))?;
let setting_target = TypeTarget::from(setting_id);
let existing_arr = match self
.root
.get_map_value(&setting_target, "collections")
.map_err(|e| StoreError::YOcto(e.to_string()))?
{
Some(SessionReadValue::Array(arr_id)) => Some(TypeTarget::Identity(arr_id)),
_ => None,
};
let mut obj = y_octo::AHashMap::default();
obj.insert("id".into(), Any::String(collection_id.into()));
obj.insert("name".into(), Any::String(name.into()));
let mut rules = y_octo::AHashMap::default();
rules.insert("filters".into(), Any::Array(Vec::new()));
obj.insert("rules".into(), Any::Object(Box::new(rules)));
obj.insert("allowList".into(), Any::Array(Vec::new()));
let entry = SessionValue::Any(Any::Object(Box::new(obj)));
self.with_tx(|root| {
if let Some(arr_target) = existing_arr {
root.array_push(&arr_target, vec![entry])
.map_err(|e| StoreError::YOcto(e.to_string()))?;
} else {
root.map_set(
&setting_target,
"collections".into(),
SessionValue::Array(vec![entry]),
)
.map_err(|e| StoreError::YOcto(e.to_string()))?;
}
Ok(())
})
}
/// Validate and apply `tag_ids` (`meta.pages[doc].tags`) and `collection_id`
/// (`setting.collections[id].allowList`) atomically in a single transaction, matching
/// `0.27.5` `ImportClipperService` (`import.ts:173-193, 339-355`).
///
/// When `require_destinations_exist` is `true`, returns `Err(StoreError::InvalidProtocol)`
/// without mutating the document if any requested tag ID or `collection_id` is absent.
pub fn apply_share_destinations(
&mut self,
page_id: &str,
tag_ids: &[String],
collection_id: Option<&str>,
require_destinations_exist: bool,
) -> StoreResult<Option<Vec<u8>>> {
let dedup_tags: Vec<String> = {
let mut seen = BTreeSet::new();
tag_ids
.iter()
.map(|t| t.trim())
.filter(|t| !t.is_empty() && seen.insert((*t).to_string()))
.map(str::to_string)
.collect()
};
let clean_col = collection_id.map(str::trim).filter(|c| !c.is_empty());
if dedup_tags.is_empty() && clean_col.is_none() {
return Ok(None);
}
let defined_tags = self.defined_tag_ids()?;
if require_destinations_exist {
for tag_id in &dedup_tags {
if !defined_tags.contains(tag_id) {
return Err(StoreError::InvalidProtocol(format!(
"destination-not-found: missing tag {tag_id:?}"
)));
}
}
if let Some(col_id) = clean_col
&& self.collection_allow_list(col_id)?.is_none()
{
return Err(StoreError::InvalidProtocol(format!(
"destination-not-found: missing collection {col_id:?}"
)));
}
}
let Some(page_target) = self.find_page_map_target(page_id)? else {
return Err(StoreError::DocNotFound(page_id.to_string()));
};
let page_meta = self
.get_page(page_id)?
.ok_or_else(|| StoreError::DocNotFound(page_id.to_string()))?;
let existing_page_tags: BTreeSet<String> = page_meta.tags.into_iter().collect();
let tags_to_append: Vec<String> = dedup_tags
.into_iter()
.filter(|id| !existing_page_tags.contains(id) && defined_tags.contains(id))
.collect();
let existing_tags_arr = match self
.root
.get_map_value(&page_target, "tags")
.map_err(|e| StoreError::YOcto(e.to_string()))?
{
Some(SessionReadValue::Array(arr_id)) => Some(TypeTarget::Identity(arr_id)),
_ => None,
};
let col_mutation = if let Some(col_id) = clean_col {
prepare_collection_allowlist_addition(&self.root, col_id, page_id)?
} else {
None
};
if tags_to_append.is_empty() && col_mutation.is_none() {
return Ok(None);
}
self.with_tx(|root| {
if !tags_to_append.is_empty() {
let tag_vals: Vec<SessionValue> = tags_to_append
.into_iter()
.map(|s| SessionValue::Any(Any::String(s)))
.collect();
if let Some(arr_target) = existing_tags_arr {
root.array_push(&arr_target, tag_vals)
.map_err(|e| StoreError::YOcto(e.to_string()))?;
} else {
root.map_set(&page_target, "tags".into(), SessionValue::Array(tag_vals))
.map_err(|e| StoreError::YOcto(e.to_string()))?;
}
}
if let Some(mutation) = col_mutation {
apply_collection_mutation_in_tx(root, mutation)?;
}
Ok(())
})
}
}
enum CollectionMutation {
ReplaceObject {
collections_target: TypeTarget,
index: u64,
updated: Any,
},
AppendToMapArray {
allow_target: TypeTarget,
doc_id: String,
},
SetMapAllowList {
map_target: TypeTarget,
next_allow: Vec<String>,
},
}
fn prepare_collection_allowlist_addition(
root: &DocSession<()>,
collection_id: &str,
doc_id: &str,
) -> StoreResult<Option<CollectionMutation>> {
let collections_target = TypeTarget::Path(TypePath::root("setting").key("collections"));
let Ok(items) = root.read_array(&collections_target) else {
return Ok(None);
};
for (idx, item) in items.into_iter().enumerate() {
match item {
SessionReadValue::Any(Any::Object(mut obj)) => {
if matches!(obj.get("id"), Some(Any::String(id)) if id == collection_id) {
let mut allow_vec: Vec<Any> = match obj.remove("allowList") {
Some(Any::Array(arr)) => arr,
_ => Vec::new(),
};
if allow_vec
.iter()
.any(|v| matches!(v, Any::String(s) if s == doc_id))
{
return Ok(None);
}
allow_vec.push(Any::String(doc_id.to_string()));
obj.insert("allowList".into(), Any::Array(allow_vec));
return Ok(Some(CollectionMutation::ReplaceObject {
collections_target,
index: idx as u64,
updated: Any::Object(obj),
}));
}
}
SessionReadValue::Map(map_id) => {
let map_target = TypeTarget::Identity(map_id);
if matches!(
root.get_map_value(&map_target, "id")
.map_err(|e| StoreError::YOcto(e.to_string()))?,
Some(SessionReadValue::Any(Any::String(ref id))) if id == collection_id
) {
match root
.get_map_value(&map_target, "allowList")
.map_err(|e| StoreError::YOcto(e.to_string()))?
{
Some(SessionReadValue::Array(arr_id)) => {
let allow_target = TypeTarget::Identity(arr_id);
let existing = root
.read_array(&allow_target)
.map_err(|e| StoreError::YOcto(e.to_string()))?;
if existing.iter().any(|v| {
matches!(v, SessionReadValue::Any(Any::String(s)) if s == doc_id)
}) {
return Ok(None);
}
return Ok(Some(CollectionMutation::AppendToMapArray {
allow_target,
doc_id: doc_id.to_string(),
}));
}
Some(SessionReadValue::Any(Any::Array(arr))) => {
let mut next: Vec<String> = arr
.into_iter()
.filter_map(|v| match v {
Any::String(s) => Some(s),
_ => None,
})
.collect();
if next.iter().any(|s| s == doc_id) {
return Ok(None);
}
next.push(doc_id.to_string());
return Ok(Some(CollectionMutation::SetMapAllowList {
map_target,
next_allow: next,
}));
}
_ => {
return Ok(Some(CollectionMutation::SetMapAllowList {
map_target,
next_allow: vec![doc_id.to_string()],
}));
}
}
}
}
_ => {}
}
}
Ok(None)
}
fn apply_collection_mutation_in_tx(
root: &mut DocSession<()>,
mutation: CollectionMutation,
) -> StoreResult<()> {
match mutation {
CollectionMutation::ReplaceObject {
collections_target,
index,
updated,
} => {
root.array_remove(&collections_target, index, 1)
.map_err(|e| StoreError::YOcto(e.to_string()))?;
root.array_insert(&collections_target, index, vec![SessionValue::Any(updated)])
.map_err(|e| StoreError::YOcto(e.to_string()))?;
}
CollectionMutation::AppendToMapArray {
allow_target,
doc_id,
} => {
root.array_push(&allow_target, vec![SessionValue::Any(Any::String(doc_id))])
.map_err(|e| StoreError::YOcto(e.to_string()))?;
}
CollectionMutation::SetMapAllowList {
map_target,
next_allow,
} => {
let vals: Vec<Any> = next_allow.into_iter().map(Any::String).collect();
root.map_set(
&map_target,
"allowList".into(),
SessionValue::Any(Any::Array(vals)),
)
.map_err(|e| StoreError::YOcto(e.to_string()))?;
}
}
Ok(())
}
fn collect_tag_ids_from_value(
root: &DocSession<()>,
val: &SessionReadValue,
out: &mut BTreeSet<String>,
) -> StoreResult<()> {
match val {
SessionReadValue::Array(arr_id) => {
for item in root
.read_array(&TypeTarget::Identity(arr_id.clone()))
.map_err(|e| StoreError::YOcto(e.to_string()))?
{
match item {
SessionReadValue::Map(map_id) => {
if let Some(SessionReadValue::Any(Any::String(id))) = root
.get_map_value(&TypeTarget::Identity(map_id), "id")
.map_err(|e| StoreError::YOcto(e.to_string()))?
{
out.insert(id);
}
}
SessionReadValue::Any(Any::Object(obj)) => {
if let Some(Any::String(id)) = obj.get("id") {
out.insert(id.clone());
}
}
_ => {}
}
}
}
SessionReadValue::Any(any) => collect_tag_ids_from_any(any, out),
_ => {}
}
Ok(())
}
fn collect_tag_ids_from_any(any: &Any, out: &mut BTreeSet<String>) {
if let Any::Array(items) = any {
for item in items {
if let Any::Object(obj) = item
&& let Some(Any::String(id)) = obj.get("id")
{
out.insert(id.clone());
}
}
}
}
+212 -61
View File
@@ -308,36 +308,85 @@ impl YjsTableDoc {
.map_err(|err| StoreError::YOcto(err.to_string()))
}
/// Capture only the incremental Yjs V1 update emitted by `f` (without re-encoding the
/// document's entire historical delete set on every row mutation).
fn capture_local_mutation<F>(&mut self, f: F) -> StoreResult<Option<Vec<u8>>>
where
F: FnOnce(&mut Doc) -> StoreResult<bool>,
{
let updates = std::sync::Arc::new(std::sync::Mutex::new(Vec::<Vec<u8>>::new()));
let sink = std::sync::Arc::clone(&updates);
let sub = self.doc.subscribe(move |event| {
if event.local && !event.update.is_empty() {
sink.lock()
.unwrap_or_else(|e| e.into_inner())
.push(event.update.clone());
}
});
let mutated = f(&mut self.doc)?;
drop(sub);
if !mutated {
return Ok(None);
}
let mut collected = updates
.lock()
.map_err(|e| StoreError::YOcto(e.to_string()))?;
let merged = match collected.len() {
0 => {
return Err(StoreError::YOcto(
"table mutation reported changes but emitted no CRDT update".into(),
));
}
1 => collected.pop(),
_ => {
let refs: Vec<&[u8]> = collected.iter().map(Vec::as_slice).collect();
let merged = y_octo::merge_updates_v1(refs)
.and_then(|u| u.encode_v1())
.map_err(|err| StoreError::YOcto(err.to_string()))?;
Some(merged)
}
};
self.local_writeback = true;
self.revision = self.revision.wrapping_add(1);
Ok(merged)
}
/// Upsert a typed row by primary key, removing `$$DELETED` if previously soft-deleted.
pub fn upsert_row<T: Serialize>(&mut self, row: &T) -> StoreResult<Vec<u8>> {
let before_sv = self.doc.get_state_vector();
let JsonValue::Object(obj) = serde_json::to_value(row)? else {
return Err(StoreError::InvalidProtocol(
"table row must serialize as a JSON object".into(),
));
};
let Some(key) = obj.get(self.key_field).and_then(JsonValue::as_str) else {
let Some(key) = obj
.get(self.key_field)
.and_then(JsonValue::as_str)
.map(str::to_owned)
else {
return Err(StoreError::InvalidProtocol(format!(
"missing string primary key field `{}`",
self.key_field
)));
};
let mut map = self
.doc
.get_or_create_map(key)
.map_err(|err| StoreError::YOcto(err.to_string()))?;
for (field, val) in &obj {
map.insert(field.clone(), Value::Any(json_to_any(val)))
let delta = self.capture_local_mutation(|doc| {
let map = doc
.get_or_create_map(&key)
.map_err(|err| StoreError::YOcto(err.to_string()))?;
}
map.remove(DELETED_FLAG_KEY);
self.local_writeback = true;
self.revision = self.revision.wrapping_add(1);
self.doc
.encode_state_as_update_v1(&before_sv)
.map_err(|err| StoreError::YOcto(err.to_string()))
doc.transact_mut(None, |tx| {
let mut mw = tx.map(&map)?;
for (field, val) in &obj {
mw.insert(field.clone(), Value::Any(json_to_any(val)))?;
}
mw.remove(DELETED_FLAG_KEY);
Ok(())
})
.map_err(|err| StoreError::YOcto(err.to_string()))?;
Ok(true)
})?;
delta.ok_or_else(|| {
StoreError::YOcto("table upsert reported changes but emitted no CRDT update".into())
})
}
/// Partially update specific fields on an existing non-deleted row, matching `0.27.5`
@@ -350,72 +399,68 @@ impl YjsTableDoc {
primary_key: &str,
patches: &[(&str, Option<JsonValue>)],
) -> StoreResult<Option<Vec<u8>>> {
let Ok(mut map) = self.doc.get_map(primary_key) else {
let Ok(map) = self.doc.get_map(primary_key) else {
return Ok(None);
};
if is_map_deleted(&map) {
return Ok(None);
}
let before_sv = self.doc.get_state_vector();
let mut mutated = false;
for (field, value) in patches {
if *field == self.key_field || *field == DELETED_FLAG_KEY {
continue;
}
match value {
Some(val) => {
map.insert((*field).to_string(), Value::Any(json_to_any(val)))
.map_err(|err| StoreError::YOcto(err.to_string()))?;
mutated = true;
}
None => {
if map.get(field).is_some() {
map.remove(field);
mutated = true;
let key_field = self.key_field;
self.capture_local_mutation(|doc| {
let mut mutated = false;
doc.transact_mut(None, |tx| {
let mut mw = tx.map(&map)?;
for (field, value) in patches {
if *field == key_field || *field == DELETED_FLAG_KEY {
continue;
}
match value {
Some(val) => {
mw.insert((*field).to_string(), Value::Any(json_to_any(val)))?;
mutated = true;
}
None => {
if mw.get(field).is_some() {
mw.remove(field);
mutated = true;
}
}
}
}
}
}
if !mutated {
return Ok(None);
}
self.local_writeback = true;
self.revision = self.revision.wrapping_add(1);
let diff = self
.doc
.encode_state_as_update_v1(&before_sv)
Ok(())
})
.map_err(|err| StoreError::YOcto(err.to_string()))?;
Ok(Some(diff))
Ok(mutated)
})
}
/// Soft-delete a row matching `YjsTableAdapter.deleteTy` (`table.ts:288-295`): remove only
/// known non-key schema fields and set `$$DELETED = true`, preserving unknown extension keys.
pub fn soft_delete(&mut self, primary_key: &str) -> StoreResult<Option<Vec<u8>>> {
let Ok(mut map) = self.doc.get_map(primary_key) else {
let Ok(map) = self.doc.get_map(primary_key) else {
return Ok(None);
};
if is_map_deleted(&map) {
return Ok(None);
}
let before_sv = self.doc.get_state_vector();
for field in self.known_fields {
if *field != self.key_field {
map.remove(field);
}
}
map.insert(DELETED_FLAG_KEY.to_string(), Value::Any(Any::True))
let key_field = self.key_field;
let known_fields = self.known_fields;
self.capture_local_mutation(|doc| {
doc.transact_mut(None, |tx| {
let mut mw = tx.map(&map)?;
for field in known_fields {
if *field != key_field {
mw.remove(field);
}
}
mw.insert(DELETED_FLAG_KEY.to_string(), Value::Any(Any::True))?;
Ok(())
})
.map_err(|err| StoreError::YOcto(err.to_string()))?;
self.local_writeback = true;
self.revision = self.revision.wrapping_add(1);
let diff = self
.doc
.encode_state_as_update_v1(&before_sv)
.map_err(|err| StoreError::YOcto(err.to_string()))?;
Ok(Some(diff))
Ok(true)
})
}
/// Read a single non-deleted row by primary key via direct root map lookup.
@@ -918,4 +963,110 @@ mod tests {
assert_eq!(rows.len(), 1);
assert_eq!(rows[0].id, "f2");
}
#[test]
fn row_mutations_emit_compact_incremental_delta_without_historical_delete_set() {
let mut seed = YjsTableDoc::new(
WorkspaceDbTableName::DocProperties.local_doc_id(),
WorkspaceDbTableName::DocProperties.primary_key_field(),
WorkspaceDbTableName::DocProperties.known_fields(),
11,
);
// Accumulate a large historical delete set across 200 distinct client/row churn cycles.
for i in 0..200u64 {
seed.doc.set_client(1000 + i);
let id = format!("hist-doc-{i}");
seed.upsert_row(&json!({
"id": id,
"primaryMode": "page",
"updatedBy": "legacy-author",
}))
.unwrap();
seed.soft_delete(&id).unwrap();
}
let snapshot = seed.encode_update_v1().unwrap();
assert!(
snapshot.len() > 2_000,
"seeded historical snapshot must carry substantial delete-set history"
);
let mut writer = YjsTableDoc::from_update_v1(
WorkspaceDbTableName::DocProperties.local_doc_id(),
WorkspaceDbTableName::DocProperties.primary_key_field(),
WorkspaceDbTableName::DocProperties.known_fields(),
42,
&snapshot,
)
.unwrap();
let mut peer = YjsTableDoc::from_update_v1(
WorkspaceDbTableName::DocProperties.local_doc_id(),
WorkspaceDbTableName::DocProperties.primary_key_field(),
WorkspaceDbTableName::DocProperties.known_fields(),
99,
&snapshot,
)
.unwrap();
let upsert_delta = writer
.upsert_row(&json!({
"id": "share-doc-1",
"primaryMode": "page",
"affine:share-import-receipt-v1": "{\"attemptId\":\"att-1\",\"state\":\"committed\"}"
}))
.unwrap();
assert!(
upsert_delta.len() < 220,
"single-row upsert delta must stay compact without re-encoding 200 historical deletes (got {} B)",
upsert_delta.len()
);
peer.apply_update_v1(&upsert_delta).unwrap();
assert_eq!(
peer.get_raw_row("share-doc-1").unwrap()["primaryMode"],
"page"
);
let patch_delta = writer
.patch_row_fields("share-doc-1", &[("primaryMode", Some(json!("edgeless")))])
.unwrap()
.unwrap();
assert!(
patch_delta.len() < 160,
"single-field patch delta must stay compact (got {} B)",
patch_delta.len()
);
peer.apply_update_v1(&patch_delta).unwrap();
assert_eq!(
peer.get_raw_row("share-doc-1").unwrap()["primaryMode"],
"edgeless"
);
}
#[test]
fn capture_local_mutation_errors_without_bumping_revision_when_no_crdt_diff_emitted() {
let mut table = YjsTableDoc::new(
WorkspaceDbTableName::DocProperties.local_doc_id(),
WorkspaceDbTableName::DocProperties.primary_key_field(),
WorkspaceDbTableName::DocProperties.known_fields(),
17,
);
let rev_before = table.revision();
assert!(!table.has_local_writeback().unwrap());
let err = table
.capture_local_mutation(|_doc| Ok(true))
.expect_err("reporting mutated=true without emitting CRDT update must fail");
assert!(
matches!(err, StoreError::YOcto(_)),
"expected StoreError::YOcto, got {err:?}"
);
assert_eq!(
table.revision(),
rev_before,
"revision must not advance when no CRDT diff was emitted"
);
assert!(
!table.has_local_writeback().unwrap(),
"local_writeback must remain false when no CRDT diff was emitted"
);
}
}
@@ -45,6 +45,8 @@ kotlinc -classpath "$ANDROID_JAR" -d /tmp/affine-android-kotlin \
hosts/android/kotlin/app/affine/pro/host/LegacyLocalStorageProbe.kt \
hosts/android/kotlin/app/affine/pro/host/AndroidBootstrapCoordinator.kt \
hosts/android/kotlin/app/affine/pro/host/AuthDataStore.kt \
hosts/android/kotlin/app/affine/pro/host/ShareIntentBridge.kt \
hosts/android/kotlin/app/affine/pro/host/ShareReceiverActivity.kt \
hosts/android/tests/ImeHostParityCheck.kt
kotlin -J-Djava.library.path="$PWD/target/debug" -cp "/tmp/affine-android-kotlin:$ANDROID_JAR" ImeHostParityCheckKt
```
@@ -10,11 +10,45 @@
<activity
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTask"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboardHidden|density|uiMode">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".ShareReceiverActivity"
android:exported="true"
android:theme="@android:style/Theme.Translucent.NoTitleBar"
android:excludeFromRecents="true"
android:noHistory="true"
android:taskAffinity="">
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="application/pdf" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND_MULTIPLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="image/*" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND_MULTIPLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="application/pdf" />
</intent-filter>
</activity>
</application>
</manifest>
@@ -6,6 +6,7 @@ import android.content.ClipData
import android.content.ClipDescription
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
@@ -184,6 +185,11 @@ object NativeBridge {
connectionKey: String,
docId: String,
): String?
external fun nativeStorageGetBlobB64(
handle: Long,
connectionKey: String,
blobKey: String,
): String?
external fun nativeStorageCheckpoint(handle: Long, connectionKey: String): Boolean
external fun nativeStorageCheckpointAllPassive(handle: Long): Int
external fun nativeStorageClose(handle: Long, connectionKey: String): Boolean
@@ -368,6 +374,38 @@ object NativeBridge {
external fun nativeSelectionActionSelectAll(handle: Long)
external fun nativeTakePendingClipboardJson(handle: Long): String?
external fun nativeSetPageReadonly(handle: Long, readonly: Boolean)
external fun nativeShareEnqueue(
handle: Long,
id: String,
kind: Int,
title: String,
content: String,
mimeType: String,
): Boolean
external fun nativeShareEnqueueBytes(
handle: Long,
id: String,
kind: Int,
title: String,
content: String,
mimeType: String,
attachmentBytes: ByteArray?,
): Boolean
external fun nativeSharePendingCount(handle: Long): Int
external fun nativeShareIsConsumed(handle: Long, id: String): Boolean
external fun nativeShareIsDurablyCommitted(
handle: Long,
workspaceStorageKey: String,
shareId: String,
): Boolean
external fun nativeShareDrainJson(handle: Long): String?
external fun nativeGetActivePageSnapshotJson(handle: Long): String?
external fun nativeIngestSharedItems(
handle: Long,
targetWorkspaceKey: String = "",
targetDocId: String = "",
nowMs: Long = 0L,
): Int
}
private fun drainPendingOpenUrl(context: Context, handle: Long) {
@@ -2905,6 +2943,7 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
private lateinit var surfaceView: AffineSurfaceView
private lateinit var documentHandleView: DocumentSelectionHandleView
private lateinit var bootstrapCoordinator: AndroidBootstrapCoordinator
private lateinit var shareIntentBridge: ShareIntentBridge
private lateinit var backDispatcher: AndroidBackDispatcher
private lateinit var imeController: AffineImeController
private lateinit var clipboardAdapter: HostClipboard
@@ -2937,6 +2976,7 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
private var frameLoopActive: Boolean = false
private var frameCallbackPosted: Boolean = false
private var surfaceReady: Boolean = false
private var bootstrapCompleted: Boolean = false
private var backCallback: OnBackInvokedCallback? = null
private val mainHandler = Handler(Looper.getMainLooper())
private var lastWantsKeyboard: Boolean = false
@@ -3196,12 +3236,78 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
handleProvider = { nativeHandle },
filesDirProvider = { filesDir.absolutePath },
)
shareIntentBridge = ShareIntentBridge(handleProvider = { nativeHandle })
bootstrapCoordinator.start(LegacyLocalStorageProbe(this)) { outcome ->
lastBootstrapOutcome = outcome
bootstrapCompleted = true
drainPendingShareIntentIfReady()
requestFrameAndSchedule()
}
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
drainPendingShareIntentIfReady()
}
override fun onResume() {
super.onResume()
drainPendingShareIntentIfReady()
}
private fun drainPendingShareIntentIfReady() {
if (nativeHandle == 0L || !::shareIntentBridge.isInitialized || !bootstrapCompleted) {
return
}
val drainTargetProvider: () -> ShareIntentBridge.ShareDrainTarget = {
ShareIntentBridge.resolveDrainTarget(bootstrapCompleted, lastBootstrapOutcome)
}
val ingestNow: () -> Int = {
val targetWsKey = when (val target = drainTargetProvider()) {
is ShareIntentBridge.ShareDrainTarget.DurableWorkspace -> target.storageKey
else -> ""
}
val ingested = NativeBridge.nativeIngestSharedItems(
nativeHandle,
targetWsKey,
"",
System.currentTimeMillis(),
)
if (ingested > 0) {
requestFrameAndSchedule()
}
ingested
}
val inbox = ShareDiskInbox(java.io.File(filesDir, ShareDiskInbox.DEFAULT_DIR_NAME))
shareIntentBridge.triggerDiskInboxDrainAsync(
inbox = inbox,
drainTargetProvider = drainTargetProvider,
isReady = { nativeHandle != 0L && bootstrapCompleted },
ingestNative = ingestNow,
runNative = { block ->
val latch = java.util.concurrent.CountDownLatch(1)
mainHandler.post {
try {
block()
} finally {
latch.countDown()
}
}
latch.await(5L, java.util.concurrent.TimeUnit.SECONDS)
},
onBatchQuarantined = {
mainHandler.post {
android.widget.Toast.makeText(
applicationContext,
"Skipped a corrupted shared item batch",
android.widget.Toast.LENGTH_SHORT,
).show()
}
},
)
}
fun retryBootstrapIfNeeded(onComplete: (BootstrapOutcome) -> Unit = {}) {
if (nativeHandle == 0L) return
val current = lastBootstrapOutcome
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,140 @@
package app.affine.pro.host
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.Toast
import java.io.File
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
/**
* Dedicated zero-UI share-sheet trampoline (`@android:style/Theme.Translucent.NoTitleBar`,
* `excludeFromRecents="true"`, `noHistory="true"`, `taskAffinity=""`).
*
* Keeps the temporary `ClipData` / `FLAG_GRANT_READ_URI_PERMISSION` grant alive while copying
* bounded (`<= 64 MiB`) `content://` stream bytes into `<filesDir>/share-inbox/`, surfaces a
* visible `Toast` when an incoming share fails completely or partially, routes into the
* single `MainActivity` task (`singleTask`), and finishes once all queued intents complete
* so Recents never retains or replays a duplicate AFFiNE task.
*/
class ShareReceiverActivity : Activity() {
private val mainHandler = Handler(Looper.getMainLooper())
private val workerExecutor: ExecutorService = Executors.newSingleThreadExecutor()
private var inFlightTasks = 0
@Suppress("DEPRECATION")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
overridePendingTransition(0, 0)
if (savedInstanceState != null) {
finishSilently()
return
}
handleShareIntent(intent)
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
handleShareIntent(intent)
}
override fun onDestroy() {
workerExecutor.shutdown()
super.onDestroy()
}
private fun handleShareIntent(incoming: Intent?) {
if (
incoming == null ||
ShareIntentBridge.isHistoryLaunch(incoming.flags) ||
!ShareIntentBridge.isShareActionIntent(incoming)
) {
if (inFlightTasks == 0) {
finishSilently()
}
return
}
val action = incoming.action ?: run {
if (inFlightTasks == 0) {
finishSilently()
}
return
}
val mimeType = incoming.type ?: "text/plain"
val subject = incoming.getStringExtra(Intent.EXTRA_SUBJECT) ?: ""
val text = incoming.getStringExtra(Intent.EXTRA_TEXT)
val uris = ShareIntentBridge.extractStreamUrisStatic(incoming)
incoming.action = null
inFlightTasks += 1
val appCtx = applicationContext
val inboxDir = File(filesDir, ShareDiskInbox.DEFAULT_DIR_NAME)
workerExecutor.execute {
val resolver = contentResolver
val streamBytes = ShareIntentBridge.resolveStreamBytesStatic(resolver, uris)
val streamMimes = LinkedHashMap<String, String>()
for (uri in uris) {
val resolvedType = runCatching { resolver.getType(uri) }.getOrNull()
if (!resolvedType.isNullOrBlank()) {
streamMimes[uri.toString()] = resolvedType
}
}
val writeResult = ShareDiskInbox(inboxDir).writeBatchWithStats(
action = action,
mimeType = mimeType,
subject = subject,
text = text,
streamUris = uris.map { it.toString() },
streamBytes = streamBytes,
streamMimeTypes = streamMimes,
)
mainHandler.post {
inFlightTasks = (inFlightTasks - 1).coerceAtLeast(0)
val batch = writeResult.batch
if (batch == null) {
Toast.makeText(
appCtx,
"Unable to import shared content (unsupported format or exceeds 64 MB)",
Toast.LENGTH_SHORT,
).show()
if (inFlightTasks == 0) {
finishSilently()
}
return@post
}
if (writeResult.skippedCount > 0) {
Toast.makeText(
appCtx,
"Imported ${batch.items.size} shared item(s); skipped ${writeResult.skippedCount} unsupported or oversized item(s)",
Toast.LENGTH_SHORT,
).show()
}
val forward = Intent(this@ShareReceiverActivity, MainActivity::class.java).apply {
addFlags(
Intent.FLAG_ACTIVITY_NEW_TASK or
Intent.FLAG_ACTIVITY_SINGLE_TOP or
Intent.FLAG_ACTIVITY_CLEAR_TOP,
)
putExtra(ShareIntentBridge.EXTRA_FROM_SHARE_RECEIVER, batch.batchId)
}
startActivity(forward)
if (inFlightTasks == 0) {
finishSilently()
}
}
}
}
@Suppress("DEPRECATION")
private fun finishSilently() {
if (!isFinishing) {
finish()
}
overridePendingTransition(0, 0)
}
}
@@ -53,7 +53,9 @@ kotlinc -classpath "$ANDROID_JAR" \
"$ANDROID_HOST_DIR/kotlin/app/affine/pro/host/MainActivity.kt" \
"$ANDROID_HOST_DIR/kotlin/app/affine/pro/host/LegacyLocalStorageProbe.kt" \
"$ANDROID_HOST_DIR/kotlin/app/affine/pro/host/AndroidBootstrapCoordinator.kt" \
"$ANDROID_HOST_DIR/kotlin/app/affine/pro/host/AuthDataStore.kt"
"$ANDROID_HOST_DIR/kotlin/app/affine/pro/host/AuthDataStore.kt" \
"$ANDROID_HOST_DIR/kotlin/app/affine/pro/host/ShareIntentBridge.kt" \
"$ANDROID_HOST_DIR/kotlin/app/affine/pro/host/ShareReceiverActivity.kt"
echo "==> Converting bytecode to DEX with d8"
"$BUILD_TOOLS_DIR/d8" \
@@ -280,6 +280,47 @@ impl AndroidEditorRuntime {
self.read_bool(PlaygroundView::database_readonly, true)
}
pub(crate) fn is_page_readonly(&self) -> bool {
self.read_bool(PlaygroundView::is_page_readonly, false)
}
pub(crate) fn active_doc_id(&self) -> Option<String> {
self.app.update(|cx| {
self.view
.read_with(cx, |v, _| v.active_doc_id().map(str::to_string))
.ok()
.flatten()
})
}
pub(crate) fn active_page_snapshot_json(&self) -> Option<String> {
self.app.update(|cx| {
self.view
.read_with(cx, |v, _| v.active_page_snapshot_json())
.ok()
.flatten()
})
}
pub(crate) fn append_shared_blocks_preserving_selection(
&mut self,
items: &[playground::overlays::SharedNoteBlockItem],
now_ms: u64,
) -> Vec<String> {
let committed = self.app.update(|cx| {
self.view
.update(cx, |v, w, cx| {
v.append_shared_blocks_preserving_selection(items, now_ms, w, cx)
})
.unwrap_or_default()
});
if !committed.is_empty() {
let _ = self.dispatcher.drain_ready();
self.window.request_frame_now();
}
committed
}
pub(crate) fn set_mode(&mut self, mode: PlaygroundMode) {
let _ = self.app.update(|cx| {
let _ = self.view.update(cx, |v, w, cx| v.set_mode(mode, w, cx));
@@ -0,0 +1,527 @@
#![allow(unsafe_code)]
//! Hand-written JNI exports for Android native share-intent bridge (`ShareIntentBridge`).
//! Zero JNA, zero UniFFI, zero WebKit, zero IME-channel typing.
use core::ffi::c_void;
use affine_store::share_ingest::{
MAX_SHARE_ATTACHMENT_BYTES, ShareIngestAttachmentSpec, ShareIngestRequest, SharePayloadKind,
};
use playground::overlays::{SharedNoteBlockItem, SharedNoteBlockKind};
use crate::jni_bridge::{
JBoolean, JClass, JInt, JLong, JObject, JSize, JString, JniEnvPtr, new_jstring,
read_jstring_utf8, with_host_mut, with_host_ref,
};
use crate::native_islands::{AndroidShareItem, AndroidShareKind};
const JNI_GET_ARRAY_LENGTH_INDEX: usize = 171;
const JNI_GET_BYTE_ARRAY_REGION_INDEX: usize = 200;
const JNI_EXCEPTION_CHECK_INDEX: usize = 228;
type GetArrayLengthFn = unsafe extern "C" fn(JniEnvPtr, JObject) -> JSize;
type GetByteArrayRegionFn = unsafe extern "C" fn(JniEnvPtr, JObject, JSize, JSize, *mut i8);
type ExceptionCheckFn = unsafe extern "C" fn(JniEnvPtr) -> JBoolean;
/// Reads a JNI `jbyteArray` up to `max_len` bytes (`None` if null, negative, oversized, or JNI exception).
/// Rejects arrays exceeding `max_len` with zero heap allocation.
unsafe fn read_jbyte_array_bounded(
env: JniEnvPtr,
arr: JObject,
max_len: usize,
) -> Option<Vec<u8>> {
if env.is_null() || arr.is_null() {
return None;
}
let vtable = unsafe { *(env as *const *const *const c_void) };
if vtable.is_null() {
return None;
}
let get_len_ptr = unsafe { *vtable.add(JNI_GET_ARRAY_LENGTH_INDEX) };
let get_region_ptr = unsafe { *vtable.add(JNI_GET_BYTE_ARRAY_REGION_INDEX) };
let exc_check_ptr = unsafe { *vtable.add(JNI_EXCEPTION_CHECK_INDEX) };
if get_len_ptr.is_null() || get_region_ptr.is_null() || exc_check_ptr.is_null() {
return None;
}
let get_len: GetArrayLengthFn = unsafe { core::mem::transmute(get_len_ptr) };
let get_region: GetByteArrayRegionFn = unsafe { core::mem::transmute(get_region_ptr) };
let exc_check: ExceptionCheckFn = unsafe { core::mem::transmute(exc_check_ptr) };
let len = unsafe { get_len(env, arr) };
if len < 0 {
return None;
}
if len == 0 {
return Some(Vec::new());
}
let usize_len = len as usize;
if usize_len > max_len {
return None;
}
let mut out = vec![0u8; usize_len];
unsafe {
get_region(env, arr, 0, len, out.as_mut_ptr() as *mut i8);
}
if unsafe { exc_check(env) } != 0 {
return None;
}
Some(out)
}
fn sanitize_doc_id_component(raw: &str) -> String {
let mut out = String::with_capacity(raw.len());
for ch in raw.chars() {
if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' {
out.push(ch);
} else {
out.push('-');
}
}
if out.is_empty() {
"item".to_string()
} else {
out
}
}
fn build_share_ingest_request(
item: &AndroidShareItem,
doc_id: &str,
now_ms: i64,
) -> ShareIngestRequest {
match item.kind {
AndroidShareKind::Url => ShareIngestRequest {
share_id: item.id.clone(),
import_attempt_id: item.id.clone(),
doc_id: doc_id.to_string(),
kind: SharePayloadKind::Url,
title: item.title.clone(),
text_or_url: item.content.trim().to_string(),
secondary_text: String::new(),
tag_ids: Vec::new(),
collection_id: None,
attachments: Vec::new(),
client_id: 0,
now_ms,
},
AndroidShareKind::Text => ShareIngestRequest {
share_id: item.id.clone(),
import_attempt_id: item.id.clone(),
doc_id: doc_id.to_string(),
kind: SharePayloadKind::Text,
title: item.title.clone(),
text_or_url: item.content.trim().to_string(),
secondary_text: String::new(),
tag_ids: Vec::new(),
collection_id: None,
attachments: Vec::new(),
client_id: 0,
now_ms,
},
AndroidShareKind::Image => ShareIngestRequest {
share_id: item.id.clone(),
import_attempt_id: item.id.clone(),
doc_id: doc_id.to_string(),
kind: SharePayloadKind::Image,
title: item.title.clone(),
text_or_url: String::new(),
secondary_text: String::new(),
tag_ids: Vec::new(),
collection_id: None,
attachments: vec![ShareIngestAttachmentSpec {
blob_key: String::new(),
file_name: "shared-image".to_string(),
mime_type: item.mime_type.clone(),
byte_offset: 0,
byte_len: item.attachment_bytes.len(),
}],
client_id: 0,
now_ms,
},
AndroidShareKind::Pdf => ShareIngestRequest {
share_id: item.id.clone(),
import_attempt_id: item.id.clone(),
doc_id: doc_id.to_string(),
kind: SharePayloadKind::Pdf,
title: item.title.clone(),
text_or_url: String::new(),
secondary_text: String::new(),
tag_ids: Vec::new(),
collection_id: None,
attachments: vec![ShareIngestAttachmentSpec {
blob_key: String::new(),
file_name: if item.title.trim().is_empty() {
"shared-document.pdf".to_string()
} else if item.title.trim().to_ascii_lowercase().ends_with(".pdf") {
item.title.trim().to_string()
} else {
format!("{}.pdf", item.title.trim())
},
mime_type: if item.mime_type.trim().is_empty() {
"application/pdf".to_string()
} else {
item.mime_type.trim().to_string()
},
byte_offset: 0,
byte_len: item.attachment_bytes.len(),
}],
client_id: 0,
now_ms,
},
}
}
fn to_live_shared_block(item: &AndroidShareItem) -> SharedNoteBlockItem {
let spec = match item.kind {
AndroidShareKind::Url => SharedNoteBlockKind::Bookmark {
url: item.content.trim().to_string(),
title: item.title.trim().to_string(),
},
AndroidShareKind::Text => SharedNoteBlockKind::Quote {
text: item.content.trim().to_string(),
},
AndroidShareKind::Image => SharedNoteBlockKind::Image {
caption: item.title.trim().to_string(),
bytes: item.attachment_bytes.clone(),
},
AndroidShareKind::Pdf => SharedNoteBlockKind::Pdf {
file_name: if item.title.trim().is_empty() {
"shared-document.pdf".to_string()
} else if item.title.trim().to_ascii_lowercase().ends_with(".pdf") {
item.title.trim().to_string()
} else {
format!("{}.pdf", item.title.trim())
},
mime_type: if item.mime_type.trim().is_empty() {
"application/pdf".to_string()
} else {
item.mime_type.trim().to_string()
},
bytes: item.attachment_bytes.clone(),
},
};
SharedNoteBlockItem {
queue_id: item.id.clone(),
share_id: sanitize_doc_id_component(&item.id),
spec,
}
}
/// Enqueues an incoming Android `ACTION_SEND` payload without attachment bytes (`0 = url`, `1 = text`).
///
/// # Safety
/// Called by the JVM/ART runtime with valid JNI pointers.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeShareEnqueue(
env: JniEnvPtr,
class: JClass,
handle: JLong,
id: JString,
kind: JInt,
title: JString,
content: JString,
mime_type: JString,
) -> JBoolean {
unsafe {
Java_app_affine_pro_host_NativeBridge_nativeShareEnqueueBytes(
env,
class,
handle,
id,
kind,
title,
content,
mime_type,
core::ptr::null_mut(),
)
}
}
/// Enqueues an incoming Android `ACTION_SEND` payload with optional attachment bytes (`2 = image`).
///
/// # Safety
/// Called by the JVM/ART runtime with valid JNI pointers.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeShareEnqueueBytes(
env: JniEnvPtr,
_class: JClass,
handle: JLong,
id: JString,
kind: JInt,
title: JString,
content: JString,
mime_type: JString,
attachment_bytes: JObject,
) -> JBoolean {
let Some(id_str) = (unsafe { read_jstring_utf8(env, id) }) else {
return 0;
};
let Some(content_str) = (unsafe { read_jstring_utf8(env, content) }) else {
return 0;
};
let title_str = unsafe { read_jstring_utf8(env, title) }.unwrap_or_default();
let mime_str =
unsafe { read_jstring_utf8(env, mime_type) }.unwrap_or_else(|| "text/plain".to_string());
let share_kind = match kind {
0 => AndroidShareKind::Url,
1 => AndroidShareKind::Text,
2 => AndroidShareKind::Image,
3 => AndroidShareKind::Pdf,
_ => return 0,
};
let bytes = if attachment_bytes.is_null() {
Vec::new()
} else {
match unsafe { read_jbyte_array_bounded(env, attachment_bytes, MAX_SHARE_ATTACHMENT_BYTES) }
{
Some(b) => b,
None => return 0,
}
};
let ok = with_host_mut(handle, |host| {
let has_sqlite = host.sqlite.has_any_connection();
host.islands
.share_queue
.enqueue_for_target(
AndroidShareItem {
id: id_str,
kind: share_kind,
title: title_str,
content: content_str,
mime_type: mime_str,
attachment_bytes: bytes,
},
has_sqlite,
)
.is_ok()
})
.unwrap_or(false);
u8::from(ok)
}
/// Returns the number of queued share items waiting to be ingested.
///
/// # Safety
/// Called by the JVM/ART runtime with valid JNI pointers.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeSharePendingCount(
_env: JniEnvPtr,
_class: JClass,
handle: JLong,
) -> JInt {
with_host_ref(handle, |host| {
host.islands
.share_queue
.pending_count()
.min(i32::MAX as usize) as JInt
})
.unwrap_or(0)
}
/// Returns `true` when `id` has already been durably committed and marked consumed.
///
/// # Safety
/// Called by the JVM/ART runtime with valid JNI pointers.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeShareIsConsumed(
env: JniEnvPtr,
_class: JClass,
handle: JLong,
id: JString,
) -> JBoolean {
let Some(id_str) = (unsafe { read_jstring_utf8(env, id) }) else {
return 0;
};
let consumed = with_host_ref(handle, |host| host.islands.share_queue.is_consumed(&id_str))
.unwrap_or(false);
u8::from(consumed)
}
/// Returns `true` only when `share_id` has a durable receipt row in the mounted workspace's
/// SQLite `share_ingest_receipts` table (`false` when no persistent workspace DB is mounted).
///
/// # Safety
/// Called by the JVM/ART runtime with valid JNI pointers.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeShareIsDurablyCommitted(
env: JniEnvPtr,
_class: JClass,
handle: JLong,
workspace_storage_key: JString,
share_id: JString,
) -> JBoolean {
let Some(share_id_str) = (unsafe { read_jstring_utf8(env, share_id) }) else {
return 0;
};
let explicit_ws_key = unsafe { read_jstring_utf8(env, workspace_storage_key) }
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
let committed = with_host_mut(handle, |host| {
let resolved_ws = match &explicit_ws_key {
Some(key) => host.sqlite.has_connection(key).then(|| key.clone()),
None => host.sqlite.first_connected_local_workspace_key(),
};
let Some(ws_key) = resolved_ws else {
return false;
};
host.sqlite
.is_share_durably_committed(&ws_key, &share_id_str)
.unwrap_or(false)
})
.unwrap_or(false);
u8::from(committed)
}
/// Atomically drains all queued Android share items as a JSON array.
///
/// # Safety
/// Called by the JVM/ART runtime with valid JNI pointers.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeShareDrainJson(
env: JniEnvPtr,
_class: JClass,
handle: JLong,
) -> JString {
let json = with_host_mut(handle, |host| {
let items = host.islands.share_queue.drain_all();
serde_json::to_string(&items).unwrap_or_else(|_| "[]".to_string())
})
.unwrap_or_else(|| "[]".to_string());
unsafe { new_jstring(env, &json) }
}
/// Returns the active `PlaygroundView` `PageSnapshot` as JSON for host verification.
///
/// # Safety
/// Called by the JVM/ART runtime with valid JNI pointers.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetActivePageSnapshotJson(
env: JniEnvPtr,
_class: JClass,
handle: JLong,
) -> JString {
let snap = crate::editor_runtime::with_editor_mut(handle, |ed| ed.active_page_snapshot_json())
.flatten();
match snap {
Some(json) => unsafe { new_jstring(env, &json) },
None => core::ptr::null_mut(),
}
}
/// Atomically ingests pending Android share items into a single authoritative target:
/// - **Connected SQLite workspace (`resolved_ws == Some(ws_key)`)**: commits structured blocks
/// (`affine_store::share_ingest`) strictly to `target_doc_id` (or newly created `share-doc-<id>`
/// when `target_doc_id` is empty) and never dual-writes into `PlaygroundView`.
/// - **Standalone in-memory editor (`resolved_ws == None` and `target_workspace_key` empty)**:
/// appends structured blocks to the open writable `PlaygroundView` preserving selection and
/// marks ONLY the exact `share_id`s delivered in-session (without durable SQLite receipt).
///
/// # Safety
/// Called by the JVM/ART runtime with valid JNI pointers.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeIngestSharedItems(
env: JniEnvPtr,
_class: JClass,
handle: JLong,
target_workspace_key: JString,
target_doc_id: JString,
now_ms: JLong,
) -> JInt {
let explicit_ws_key = unsafe { read_jstring_utf8(env, target_workspace_key) }
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
let explicit_doc_id = unsafe { read_jstring_utf8(env, target_doc_id) }
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
if now_ms <= 0 {
return 0;
}
let effective_now_ms = now_ms;
let editor_state = crate::editor_runtime::with_editor_mut(handle, |ed| {
(!ed.is_page_readonly(), ed.active_doc_id())
});
let editor_writable = editor_state.as_ref().map(|(w, _)| *w);
let active_doc_id = editor_state.and_then(|(_, d)| d);
let targets_active_editor_doc = explicit_doc_id.is_some() && explicit_doc_id == active_doc_id;
let Some((sqlite_committed_items, fallback_live_candidates)) = with_host_mut(handle, |host| {
let pending = host.islands.share_queue.peek_pending();
if pending.is_empty() {
return (Vec::new(), Vec::new());
}
let resolved_ws = match &explicit_ws_key {
Some(key) => host.sqlite.has_connection(key).then(|| key.clone()),
None => host.sqlite.first_connected_local_workspace_key(),
};
if explicit_ws_key.is_some() && resolved_ws.is_none() {
return (Vec::new(), Vec::new());
}
if let Some(ws_key) = resolved_ws {
if targets_active_editor_doc && editor_writable == Some(false) {
return (Vec::new(), Vec::new());
}
let mut ok_items = Vec::with_capacity(pending.len());
for item in pending {
let doc_id = explicit_doc_id.clone().unwrap_or_else(|| {
format!("share-doc-{}", sanitize_doc_id_component(&item.id))
});
let req = build_share_ingest_request(&item, &doc_id, effective_now_ms);
if host
.sqlite
.ingest_share_item(&ws_key, &req, &item.attachment_bytes)
.is_ok()
{
ok_items.push(item);
}
}
if !ok_items.is_empty() {
let _ = host.sqlite.checkpoint_passive(&ws_key);
}
(ok_items, Vec::new())
} else if editor_writable == Some(true)
&& (explicit_doc_id.is_none() || explicit_doc_id == active_doc_id)
{
(Vec::new(), pending)
} else {
(Vec::new(), Vec::new())
}
}) else {
return 0;
};
let (consumed_ids, durably_committed): (Vec<String>, bool) =
if !sqlite_committed_items.is_empty() {
(
sqlite_committed_items.into_iter().map(|i| i.id).collect(),
true,
)
} else if !fallback_live_candidates.is_empty() {
let live_specs: Vec<SharedNoteBlockItem> = fallback_live_candidates
.iter()
.map(to_live_shared_block)
.collect();
let delivered = crate::editor_runtime::with_editor_mut(handle, |ed| {
ed.append_shared_blocks_preserving_selection(&live_specs, effective_now_ms as u64)
})
.unwrap_or_default();
(delivered, false)
} else {
(Vec::new(), false)
};
if consumed_ids.is_empty() {
return 0;
}
let count = consumed_ids.len().min(i32::MAX as usize) as JInt;
let _ = with_host_mut(handle, |host| {
if durably_committed {
host.islands.share_queue.mark_consumed(&consumed_ids);
} else {
host.islands.share_queue.mark_live_delivered(&consumed_ids);
}
});
count
}
@@ -286,6 +286,33 @@ pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeStorageGetD
}
}
/// # Safety
/// `env` must be null or a valid `JNIEnv*`; string args must be null or valid `jstring`s.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeStorageGetBlobB64(
env: JniEnvPtr,
_class: JClass,
handle: JLong,
connection_key: JString,
blob_key: JString,
) -> JString {
let (Some(conn_key), Some(bkey)) =
(unsafe { read_jstring_utf8(env, connection_key) }, unsafe {
read_jstring_utf8(env, blob_key)
})
else {
return core::ptr::null_mut();
};
let data = with_host_mut(handle, |host| {
host.sqlite.get_blob(&conn_key, &bkey).ok().flatten()
})
.flatten();
match data {
Some(bin) => unsafe { new_jstring(env, &STANDARD.encode(bin)) },
None => core::ptr::null_mut(),
}
}
/// # Safety
/// `env` must be null or a valid `JNIEnv*`; string args must be null or valid `jstring`s.
#[unsafe(no_mangle)]
+7 -49
View File
@@ -21,6 +21,7 @@ pub(crate) mod editor_runtime;
#[cfg(any(target_os = "android", test, feature = "host-jni"))]
pub(crate) mod editor_selection;
mod ime;
pub mod native_islands;
pub mod pdf;
pub mod selection;
pub mod storage;
@@ -34,6 +35,8 @@ pub mod jni_editor;
#[cfg(any(target_os = "android", test, feature = "host-jni"))]
pub mod jni_interaction;
#[cfg(any(target_os = "android", test, feature = "host-jni"))]
pub mod jni_islands;
#[cfg(any(target_os = "android", test, feature = "host-jni"))]
pub mod jni_storage;
pub use autofill::{
@@ -51,7 +54,8 @@ pub use storage::{
AndroidSqliteBridge, AndroidWorkspaceCatalog, LOCAL_WORKSPACE_LOCAL_STORAGE_KEY,
};
pub use surface::{
AndroidRenderBackend, DEFAULT_CLEAR_COLOR_ARGB, SurfaceLifecycleState, SurfacePresentError,
AndroidRenderBackend, DEFAULT_CLEAR_COLOR_ARGB, LogicalWindowInsets, SurfaceLifecycleState,
SurfacePresentError, physical_insets_to_logical_dp,
};
/// Legacy Capacitor Android WebView origin used for one-shot `localStorage` probing.
@@ -71,26 +75,6 @@ pub const fn should_expose_autofill(sdk_int: u32) -> bool {
sdk_int >= AUTOFILL_MIN_SDK_INT
}
/// Logical-dp window insets forwarded across the Android JNI boundary.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct LogicalWindowInsets {
pub safe_top: f32,
pub safe_right: f32,
pub safe_bottom: f32,
pub safe_left: f32,
/// Absolute keyboard overlap height from the window bottom edge in logical `dp`.
/// Does not subtract `safe_bottom`; `ui::WindowInsets::effective()` takes the max.
pub ime_bottom: f32,
}
impl LogicalWindowInsets {
/// Returns keyboard height strictly above the bottom navigation bar in logical `dp`,
/// preventing double-deduction when combining `safe_bottom` and `ime_bottom`.
pub fn effective_ime_above_nav_bar(&self) -> f32 {
(self.ime_bottom - self.safe_bottom).max(0.0)
}
}
/// Android back navigation dispatch strategy by API level.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(i32)]
@@ -114,34 +98,6 @@ pub const fn back_dispatch_mode(sdk_int: u32) -> BackDispatchMode {
}
}
/// Converts Android `WindowInsets` physical pixel measurements into logical `dp`.
pub fn physical_insets_to_logical_dp(
safe_top_px: i32,
safe_right_px: i32,
safe_bottom_px: i32,
safe_left_px: i32,
ime_bottom_px: i32,
density: f32,
) -> LogicalWindowInsets {
let safe_density = if density.is_finite() && density > 0.0 {
density
} else {
1.0
};
let top = safe_top_px.max(0);
let right = safe_right_px.max(0);
let bottom = safe_bottom_px.max(0);
let left = safe_left_px.max(0);
let ime = ime_bottom_px.max(0);
LogicalWindowInsets {
safe_top: top as f32 / safe_density,
safe_right: right as f32 / safe_density,
safe_bottom: bottom as f32 / safe_density,
safe_left: left as f32 / safe_density,
ime_bottom: ime as f32 / safe_density,
}
}
/// Four-phase predictive back gesture protocol (plus legacy single-shot `Commit`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(i32)]
@@ -590,6 +546,7 @@ pub struct AndroidHostState {
pub selected_len: usize,
pub composing_start: Option<usize>,
pub composing_len: usize,
pub islands: native_islands::AndroidNativeIslandsState,
}
impl Default for AndroidHostState {
@@ -614,6 +571,7 @@ impl Default for AndroidHostState {
selected_len: 0,
composing_start: None,
composing_len: 0,
islands: native_islands::AndroidNativeIslandsState::default(),
}
}
}
@@ -0,0 +1,250 @@
//! Zero-JNA / zero-UniFFI Android native-island narrow state machines:
//! `ShareIntent`: Incoming `ACTION_SEND` / `ACTION_SEND_MULTIPLE` queue with scheme allowlists,
//! 64 MiB per-item & cumulative attachment caps, non-destructive `peek_pending`, and
//! commit-gated `mark_consumed` deduplication.
use std::collections::{BTreeSet, VecDeque};
use affine_store::share_ingest::MAX_SHARE_ATTACHMENT_BYTES;
use serde::{Deserialize, Serialize};
/// Supported Android `ACTION_SEND` payload kinds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AndroidShareKind {
Url,
Text,
Image,
Pdf,
}
/// One queued item received from Android `ACTION_SEND` / `ACTION_SEND_MULTIPLE`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AndroidShareItem {
pub id: String,
pub kind: AndroidShareKind,
pub title: String,
pub content: String,
pub mime_type: String,
#[serde(default, skip_serializing)]
pub attachment_bytes: Vec<u8>,
}
/// Pure-Rust incoming share queue with scheme, size, and idempotent duplicate validation.
#[derive(Debug, Default)]
pub struct AndroidShareQueue {
items: VecDeque<AndroidShareItem>,
consumed_ids: BTreeSet<String>,
live_delivered_ids: BTreeSet<String>,
}
impl AndroidShareQueue {
pub fn enqueue(&mut self, item: AndroidShareItem) -> Result<(), &'static str> {
self.enqueue_for_target(item, false)
}
pub fn enqueue_for_target(
&mut self,
item: AndroidShareItem,
allow_upgrade_from_live_delivery: bool,
) -> Result<(), &'static str> {
if item.id.trim().is_empty() {
return Err("share id must be non-empty");
}
let trimmed = item.content.trim();
if trimmed.is_empty() {
return Err("share content must be non-empty");
}
match item.kind {
AndroidShareKind::Url => {
if !(trimmed.starts_with("https://") || trimmed.starts_with("http://")) {
return Err("share url must use http(s) scheme");
}
}
AndroidShareKind::Image | AndroidShareKind::Pdf => {
if !(trimmed.starts_with("content://")
|| trimmed.starts_with("https://")
|| trimmed.starts_with("http://"))
{
return Err("share attachment uri must use content:// or http(s):// scheme");
}
if item.attachment_bytes.is_empty() {
return Err("share attachment must carry non-empty attachment bytes");
}
if item.attachment_bytes.len() > MAX_SHARE_ATTACHMENT_BYTES {
return Err("share attachment exceeds 64 MiB limit");
}
let queued_bytes: usize = self
.items
.iter()
.map(|existing| existing.attachment_bytes.len())
.sum();
if queued_bytes
.checked_add(item.attachment_bytes.len())
.is_none_or(|sum| sum > MAX_SHARE_ATTACHMENT_BYTES)
{
return Err("cumulative queued share attachments exceed 64 MiB limit");
}
}
AndroidShareKind::Text => {}
}
let blocked_by_live =
!allow_upgrade_from_live_delivery && self.live_delivered_ids.contains(&item.id);
if self.consumed_ids.contains(&item.id)
|| blocked_by_live
|| self.items.iter().any(|existing| existing.id == item.id)
{
return Err("duplicate share id");
}
self.items.push_back(item);
Ok(())
}
pub fn pending_count(&self) -> usize {
self.items.len()
}
/// Non-destructively clones pending items so failed or blocked ingestion attempts
/// never lose queued shares or mark `consumed_ids` prematurely.
pub fn peek_pending(&self) -> Vec<AndroidShareItem> {
self.items.iter().cloned().collect()
}
/// Commits a subset of pending share IDs as durably consumed after SQLite commit.
pub fn mark_consumed(&mut self, ids: &[String]) {
if ids.is_empty() {
return;
}
let done: BTreeSet<&str> = ids.iter().map(String::as_str).collect();
self.items.retain(|item| !done.contains(item.id.as_str()));
for id in ids {
self.live_delivered_ids.remove(id);
self.consumed_ids.insert(id.clone());
}
}
/// Marks share IDs delivered to the in-memory editor (without SQLite persistence yet).
pub fn mark_live_delivered(&mut self, ids: &[String]) {
if ids.is_empty() {
return;
}
let done: BTreeSet<&str> = ids.iter().map(String::as_str).collect();
self.items.retain(|item| !done.contains(item.id.as_str()));
for id in ids {
if !self.consumed_ids.contains(id) {
self.live_delivered_ids.insert(id.clone());
}
}
}
/// Returns `true` when `id` has been durably committed or delivered in this session.
pub fn is_consumed(&self, id: &str) -> bool {
self.consumed_ids.contains(id) || self.live_delivered_ids.contains(id)
}
pub fn drain_all(&mut self) -> Vec<AndroidShareItem> {
let drained: Vec<AndroidShareItem> = self.items.drain(..).collect();
for item in &drained {
self.consumed_ids.insert(item.id.clone());
}
drained
}
}
/// Combined narrow-bridge state for Android native islands.
#[derive(Debug, Default)]
pub struct AndroidNativeIslandsState {
pub share_queue: AndroidShareQueue,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn android_native_islands_share_intent_state_machine() {
let mut islands = AndroidNativeIslandsState::default();
assert!(
islands
.share_queue
.enqueue(AndroidShareItem {
id: "bad-url".into(),
kind: AndroidShareKind::Url,
title: "".into(),
content: "file:///etc/passwd".into(),
mime_type: "text/plain".into(),
attachment_bytes: Vec::new(),
})
.is_err()
);
// Image with file:// scheme or empty bytes must fail closed.
assert!(
islands
.share_queue
.enqueue(AndroidShareItem {
id: "bad-img-file".into(),
kind: AndroidShareKind::Image,
title: "".into(),
content: "file:///sdcard/secret.png".into(),
mime_type: "image/png".into(),
attachment_bytes: vec![0x89, b'P', b'N', b'G'],
})
.is_err()
);
assert!(
islands
.share_queue
.enqueue(AndroidShareItem {
id: "bad-img-empty".into(),
kind: AndroidShareKind::Image,
title: "".into(),
content: "content://media/external/images/media/1".into(),
mime_type: "image/png".into(),
attachment_bytes: Vec::new(),
})
.is_err()
);
islands
.share_queue
.enqueue(AndroidShareItem {
id: "intent-1".into(),
kind: AndroidShareKind::Url,
title: "AFFiNE".into(),
content: "https://affine.pro".into(),
mime_type: "text/plain".into(),
attachment_bytes: Vec::new(),
})
.expect("enqueue url");
islands
.share_queue
.enqueue(AndroidShareItem {
id: "intent-img-1".into(),
kind: AndroidShareKind::Image,
title: "Photo".into(),
content: "content://media/external/images/media/1".into(),
mime_type: "image/png".into(),
attachment_bytes: vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a],
})
.expect("enqueue content:// image with bytes");
assert_eq!(islands.share_queue.pending_count(), 2);
let peeked = islands.share_queue.peek_pending();
assert_eq!(peeked.len(), 2);
assert_eq!(islands.share_queue.pending_count(), 2);
islands.share_queue.mark_consumed(&["intent-1".into()]);
assert_eq!(islands.share_queue.pending_count(), 1);
// Re-enqueuing an already-consumed ID must fail idempotently.
assert!(
islands
.share_queue
.enqueue(AndroidShareItem {
id: "intent-1".into(),
kind: AndroidShareKind::Url,
title: "AFFiNE".into(),
content: "https://affine.pro".into(),
mime_type: "text/plain".into(),
attachment_bytes: Vec::new(),
})
.is_err()
);
}
}
@@ -278,6 +278,24 @@ impl AndroidSqliteBridge {
self.storages.contains_key(&key)
}
/// Returns `true` when `connection_key` is currently open in `storages`.
pub fn has_connection(&self, connection_key: &str) -> bool {
self.storages.contains_key(connection_key)
}
/// Returns `true` when at least one SQLite workspace connection is currently open.
pub fn has_any_connection(&self) -> bool {
!self.storages.is_empty()
}
/// Returns the first connected `workspace:local:<id>` connection key, if any.
pub fn first_connected_local_workspace_key(&self) -> Option<String> {
self.storages
.keys()
.find(|k| k.starts_with("workspace:local:"))
.cloned()
}
/// Closes and evicts any open `workspace:local:<id>` connections whose ID is
/// no longer in `catalog` (called when the local allowlist shrinks or updates).
pub fn evict_unlisted_local_workspaces(&mut self, catalog: &AndroidWorkspaceCatalog) -> usize {
@@ -395,6 +413,65 @@ impl AndroidSqliteBridge {
Ok(rec.map(|r| r.bin))
}
/// Reads a non-deleted blob's raw bytes from SQLite by content-addressed key.
pub fn get_blob(
&mut self,
connection_key: &str,
key: &str,
) -> Result<Option<Vec<u8>>, AndroidStorageError> {
let rt = Self::runtime_ref(&mut self.runtime)?;
let storage = self
.storages
.get(connection_key)
.ok_or_else(|| AndroidStorageError::NotConnected(connection_key.to_string()))?;
let rec = rt
.block_on(storage.get_blob(key))
.map_err(|e| AndroidStorageError::Store(e.to_string()))?;
Ok(rec.map(|r| r.data))
}
/// Atomically ingests a shared item into the connected SQLite workspace using the shared
/// `0.27.5`-compatible `affine_store::share_ingest::ingest_share_item_into_sqlite` transaction.
pub fn ingest_share_item(
&mut self,
connection_key: &str,
req: &affine_store::share_ingest::ShareIngestRequest,
blob_bytes: &[u8],
) -> Result<affine_store::share_ingest::ShareIngestOutcome, AndroidStorageError> {
let workspace_id = connection_key.rsplit(':').next().unwrap_or("").to_string();
let db_path = self
.storages
.get(connection_key)
.map(|s| PathBuf::from(s.path()))
.ok_or_else(|| AndroidStorageError::NotConnected(connection_key.to_string()))?;
let rt = Self::runtime_ref(&mut self.runtime)?;
rt.block_on(affine_store::share_ingest::ingest_share_item_into_sqlite(
&db_path,
&workspace_id,
req,
blob_bytes,
))
.map_err(|e| AndroidStorageError::Store(e.to_string()))
}
/// Returns `true` when `share_id` has a committed receipt in `share_ingest_receipts`.
pub fn is_share_durably_committed(
&mut self,
connection_key: &str,
share_id: &str,
) -> Result<bool, AndroidStorageError> {
let db_path = self
.storages
.get(connection_key)
.map(|s| PathBuf::from(s.path()))
.ok_or_else(|| AndroidStorageError::NotConnected(connection_key.to_string()))?;
let rt = Self::runtime_ref(&mut self.runtime)?;
rt.block_on(affine_store::share_ingest::is_share_durably_committed(
&db_path, share_id,
))
.map_err(|e| AndroidStorageError::Store(e.to_string()))
}
/// Computes the merged diff and state vector for sync round-trips.
pub fn get_doc_diff(
&mut self,
@@ -7,6 +7,54 @@
/// Default observable first-frame clear color (opaque `#FAFAFC` ARGB, matching iOS light canvas).
pub const DEFAULT_CLEAR_COLOR_ARGB: u32 = 0xFFFA_FAFC;
/// Logical-dp window insets forwarded across the Android JNI boundary.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct LogicalWindowInsets {
pub safe_top: f32,
pub safe_right: f32,
pub safe_bottom: f32,
pub safe_left: f32,
/// Absolute keyboard overlap height from the window bottom edge in logical `dp`.
/// Does not subtract `safe_bottom`; `ui::WindowInsets::effective()` takes the max.
pub ime_bottom: f32,
}
impl LogicalWindowInsets {
/// Returns keyboard height strictly above the bottom navigation bar in logical `dp`,
/// preventing double-deduction when combining `safe_bottom` and `ime_bottom`.
pub fn effective_ime_above_nav_bar(&self) -> f32 {
(self.ime_bottom - self.safe_bottom).max(0.0)
}
}
/// Converts Android `WindowInsets` physical pixel measurements into logical `dp`.
pub fn physical_insets_to_logical_dp(
safe_top_px: i32,
safe_right_px: i32,
safe_bottom_px: i32,
safe_left_px: i32,
ime_bottom_px: i32,
density: f32,
) -> LogicalWindowInsets {
let safe_density = if density.is_finite() && density > 0.0 {
density
} else {
1.0
};
let top = safe_top_px.max(0);
let right = safe_right_px.max(0);
let bottom = safe_bottom_px.max(0);
let left = safe_left_px.max(0);
let ime = ime_bottom_px.max(0);
LogicalWindowInsets {
safe_top: top as f32 / safe_density,
safe_right: right as f32 / safe_density,
safe_bottom: bottom as f32 / safe_density,
safe_left: left as f32 / safe_density,
ime_bottom: ime as f32 / safe_density,
}
}
/// Active Android presentation backend with deterministic fallback order.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(i32)]
@@ -1,9 +1,12 @@
import android.view.inputmethod.InputConnection
import app.affine.pro.host.AffineImeController
import app.affine.pro.host.AffineSurfaceView
import app.affine.pro.host.ShareDiskInbox
import app.affine.pro.host.ShareIntentBridge
import app.affine.pro.host.AndroidAutofillController
import app.affine.pro.host.AndroidBackDispatcher
import app.affine.pro.host.AndroidBootstrapCoordinator
import app.affine.pro.host.BootstrapOutcome
import app.affine.pro.host.AndroidCookieCleaner
import app.affine.pro.host.AndroidPdfPageRenderer
import app.affine.pro.host.AndroidSelectionCoordinator
@@ -2082,5 +2085,705 @@ fun main() {
NativeBridge.nativeDestroyHost(seq26Handle)
}
println("Kotlin JNI Android host parity check passed (26/26 sequences)")
// Sequence 27: Android native island (ShareIntentBridge) non-destructive block & SQLite ingestion:
// - Scheme allowlist (`http(s)://` for URLs, `content://`/`http(s)://` + non-empty bytes for images; rejects `file://`)
// - Preserves active word selection (`[6, 12)` = `"native"`) and focused paragraph text untouched (zero IME typing)
// - Read-only page leaves queued shares intact (`pendingCount > 0`) until unlocked
// - Appends real BlockSuite `affine:bookmark`, `affine:paragraph` (`quote`), and SHA-256 `affine:image` blocks
// - Commits atomically into mounted SQLite workspace (`blobs` + `updates` + `share_ingest_receipts`) and survives reopen
val seq27Handle = NativeBridge.nativeCreateHost()
val seq27Dir = java.nio.file.Files.createTempDirectory("affine-share-sqlite-").toFile()
try {
val png1x1 = byteArrayOf(
0x89.toByte(), 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A,
0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52,
)
checkEq(
NativeBridge.nativeShareEnqueue(seq27Handle, "bad-1", ShareIntentBridge.KIND_URL, "Bad", "javascript:alert(1)", "text/plain"),
false,
"seq27 rejects non-http(s) share URL",
)
checkEq(
NativeBridge.nativeShareEnqueueBytes(seq27Handle, "bad-file-img", ShareIntentBridge.KIND_IMAGE, "Secret", "file:///sdcard/secret.png", "image/png", png1x1),
false,
"seq27 rejects file:// image URI",
)
checkEq(
NativeBridge.nativeShareEnqueue(seq27Handle, "bad-empty-img", ShareIntentBridge.KIND_IMAGE, "Empty", "content://media/external/images/media/1", "image/png"),
false,
"seq27 rejects image without resolved bytes",
)
checkEq(
NativeBridge.nativeShareEnqueue(seq27Handle, "share-1", ShareIntentBridge.KIND_URL, "AFFiNE", "https://affine.pro", "text/plain"),
true,
"seq27 accepts https share URL",
)
checkEq(NativeBridge.nativeSharePendingCount(seq27Handle), 1, "seq27 pendingCount == 1")
val drained = NativeBridge.nativeShareDrainJson(seq27Handle) ?: ""
checkEq(drained.contains("https://affine.pro"), true, "seq27 drained JSON contains shared URL")
checkEq(NativeBridge.nativeSharePendingCount(seq27Handle), 0, "seq27 pendingCount == 0 after drain")
// Prepare active paragraph `"Hello native world"` with word `"native"` selected (`[6, 12)`).
NativeBridge.nativeResetEmptyDocument(seq27Handle)
val ime27 = AffineImeController { seq27Handle }
checkEq(ime27.commitText("Hello native world", 1), true, "seq27 seed paragraph text")
checkEq(ime27.setSelection(6, 12), true, "seq27 select word 'native' [6, 12)")
checkEq(ime27.selectionStart(), 6, "seq27 pre-share selectionStart == 6")
checkEq(ime27.selectionEnd(), 12, "seq27 pre-share selectionEnd == 12")
// Enqueue URL + Image (`ACTION_SEND`) and 2 Images + Text (`ACTION_SEND_MULTIPLE` + text).
val shareBridge = ShareIntentBridge(handleProvider = { seq27Handle })
val streamBytes = mapOf(
"content://media/external/images/media/42" to png1x1,
"content://media/1" to png1x1,
"content://media/2" to png1x1,
)
val enqueuedBoth = shareBridge.enqueueParsedPayloads(
action = "android.intent.action.SEND",
mimeType = "image/png",
subject = "Caption + Image",
text = "https://affine.pro/shared",
streamUris = listOf("content://media/external/images/media/42"),
streamBytes = streamBytes,
idPrefix = "main-send",
)
checkEq(enqueuedBoth, 2, "seq27 ACTION_SEND with EXTRA_TEXT + EXTRA_STREAM enqueues both")
val enqueuedText = shareBridge.enqueueParsedPayloads(
action = "android.intent.action.SEND",
mimeType = "text/plain",
subject = "",
text = "SHAREDTEXT",
streamUris = emptyList(),
idPrefix = "main-text",
)
checkEq(enqueuedText, 1, "seq27 plain text share enqueued")
val enqueuedMulti = shareBridge.enqueueParsedPayloads(
action = "android.intent.action.SEND_MULTIPLE",
mimeType = "image/*",
subject = "Gallery",
text = null,
streamUris = listOf("content://media/1", "content://media/2"),
streamBytes = streamBytes,
idPrefix = "main-multi",
)
checkEq(enqueuedMulti, 2, "seq27 ACTION_SEND_MULTIPLE enqueues all stream URIs")
checkEq(shareBridge.pendingCount(), 5, "seq27 ShareIntentBridge pendingCount == 5")
// 1) Standalone editor mode (no SQLite workspace connected yet):
// - Read-only page guard leaves shares queued and drainStagedQueue never re-enqueues an already staged intent;
// - Partial failure (0-byte invalid image) marks ONLY actually committed share IDs consumed.
NativeBridge.nativeSetPageReadonly(seq27Handle, true)
checkEq(
NativeBridge.nativeIngestSharedItems(seq27Handle, "", "", 1_795_900_000_000L),
0,
"seq27 read-only page leaves shares queued",
)
checkEq(shareBridge.pendingCount(), 5, "seq27 pendingCount remains 5 when blocked by read-only")
shareBridge.stageDescriptor(
ShareIntentBridge.PendingShareDescriptor(
action = "android.intent.action.SEND",
mimeType = "text/plain",
subject = "Readonly Retry Once",
text = "https://affine.pro/readonly-once",
streamUris = emptyList(),
rawUris = emptyList(),
idPrefix = null,
),
)
val drainReadonly = {
shareBridge.drainStagedQueue(
isReady = { true },
resolveStreamAsync = { _, cb -> cb(emptyMap()) },
ingestNative = { NativeBridge.nativeIngestSharedItems(seq27Handle, "", "", 1_795_900_000_100L) },
)
}
drainReadonly()
drainReadonly()
checkEq(shareBridge.pendingCount(), 6, "seq27 retry while read-only never duplicate-enqueues staged intent")
// Zero-byte attachment is rejected at the enqueue gate; valid PDF attachment is accepted and committed.
checkEq(
NativeBridge.nativeShareEnqueueBytes(
seq27Handle,
"main-empty-bad-img",
ShareIntentBridge.KIND_IMAGE,
"Empty",
"content://media/empty",
"image/png",
ByteArray(0),
),
false,
"seq27 zero-byte image rejected at enqueue gate",
)
val pdfSample = "%PDF-1.4\n1 0 obj\n<<>>\nendobj\ntrailer\n<<>>\n%%EOF\n".toByteArray(Charsets.UTF_8)
checkEq(
shareBridge.enqueueParsedPayloads(
action = "android.intent.action.SEND",
mimeType = "application/pdf",
subject = "Spec.pdf",
text = null,
streamUris = listOf("content://media/external/file/99"),
streamBytes = mapOf("content://media/external/file/99" to pdfSample),
idPrefix = "main-pdf",
),
1,
"seq27 PDF share enqueued as KIND_PDF",
)
checkEq(shareBridge.pendingCount(), 7, "seq27 pendingCount == 7 before standalone live ingest")
// Persistent ShareDiskInbox: stays on disk while read-only blocks ingest, removes ONLY after commit,
// and returns null when stream bytes fail to resolve (so ShareReceiverActivity surfaces failure Toast).
val diskInboxDir = java.io.File(seq27Dir, "share-inbox")
val diskInbox = ShareDiskInbox(diskInboxDir)
checkEq(
diskInbox.writeBatch(
action = "android.intent.action.SEND",
mimeType = "image/png",
subject = "Unreadable",
text = null,
streamUris = listOf("content://media/unreadable"),
streamBytes = emptyMap(),
batchId = "bad-batch",
),
null,
"seq27 unreadable attachment share returns null batch (triggers failure Toast)",
)
checkEq(
ShareIntentBridge.isHistoryLaunch(0x00100000),
true,
"seq27 FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY detected and suppressed",
)
val persistedBatch = diskInbox.writeBatch(
action = "android.intent.action.SEND",
mimeType = "application/pdf",
subject = "InboxDoc.pdf",
text = "https://affine.pro/from-disk-inbox",
streamUris = listOf("content://media/external/file/100"),
streamBytes = mapOf("content://media/external/file/100" to pdfSample),
batchId = "disk-batch-1",
createdAtMs = 1_795_900_000_150L,
)
checkEq(persistedBatch != null && persistedBatch.items.size == 2, true, "seq27 disk inbox persisted URL + PDF batch")
// Standalone inbox created first so read-only retention & standalone live delivery run on
// `standaloneInbox`, while `diskInbox` (`disk-batch-1`) stays strictly untouched across
// `PendingBootstrap` and transient probe/mount failure until `DurableWorkspace(wsKey27)` mounts!
val standaloneInboxDir = java.io.File(seq27Dir, "standalone-share-inbox")
val standaloneInbox = ShareDiskInbox(standaloneInboxDir)
val standaloneBatch = standaloneInbox.writeBatch(
action = "android.intent.action.SEND",
mimeType = "application/pdf",
subject = "StandaloneOnce.pdf",
text = "https://affine.pro/standalone-once",
streamUris = listOf("content://media/external/file/101"),
streamBytes = mapOf("content://media/external/file/101" to pdfSample),
batchId = "standalone-batch-1",
createdAtMs = 1_795_900_000_155L,
)
checkEq(standaloneBatch != null && standaloneBatch.items.size == 2, true, "seq27 standalone inbox persisted batch")
val trueStandaloneOutcome = BootstrapOutcome(
imported = true,
canCreateDefaultWorkspace = true,
connectedWorkspaceKeys = emptyList(),
failedWorkspaceIds = emptyList(),
preservedLocalWorkspaceRaw = null,
)
val blockedDiskCommitted = shareBridge.drainDiskInbox(
inbox = standaloneInbox,
drainTargetProvider = { ShareIntentBridge.resolveDrainTarget(true, trueStandaloneOutcome) },
isReady = { true },
ingestNative = { NativeBridge.nativeIngestSharedItems(seq27Handle, "", "", 1_795_900_000_160L) },
)
checkEq(blockedDiskCommitted, 0, "seq27 disk inbox drain while read-only commits 0")
checkEq(
standaloneInbox.listPendingBatches().size,
1,
"seq27 standalone inbox manifest retained on disk when page is read-only",
)
NativeBridge.nativeSetPageReadonly(seq27Handle, false)
// Pre-bootstrap, failed probe (`imported=false`), and failed workspace mount (`failedWorkspaceIds`
// non-empty) ALL map via `ShareIntentBridge.resolveDrainTarget` to `PendingBootstrap` so `diskInbox`
// (`disk-batch-1` + PDF attachment) is NEVER prematurely deleted or consumed into the demo doc!
val failedProbeOutcome = BootstrapOutcome(
imported = false,
canCreateDefaultWorkspace = false,
connectedWorkspaceKeys = emptyList(),
failedWorkspaceIds = emptyList(),
preservedLocalWorkspaceRaw = null,
)
val failedMountOutcome = BootstrapOutcome(
imported = true,
canCreateDefaultWorkspace = false,
connectedWorkspaceKeys = emptyList(),
failedWorkspaceIds = listOf("ws-share-27"),
preservedLocalWorkspaceRaw = "[\"ws-share-27\"]",
)
val corruptLegacyOutcome = BootstrapOutcome(
imported = true,
canCreateDefaultWorkspace = false,
connectedWorkspaceKeys = emptyList(),
failedWorkspaceIds = emptyList(),
preservedLocalWorkspaceRaw = "corrupt-json",
)
for ((label, target) in listOf(
"pre-bootstrap" to ShareIntentBridge.resolveDrainTarget(false, null),
"probe-failed" to ShareIntentBridge.resolveDrainTarget(true, failedProbeOutcome),
"mount-failed" to ShareIntentBridge.resolveDrainTarget(true, failedMountOutcome),
"corrupt-legacy" to ShareIntentBridge.resolveDrainTarget(true, corruptLegacyOutcome),
)) {
checkEq(
target,
ShareIntentBridge.ShareDrainTarget.PendingBootstrap,
"seq27 resolveDrainTarget($label) == PendingBootstrap",
)
val drained = shareBridge.drainDiskInbox(
inbox = diskInbox,
drainTargetProvider = { target },
isReady = { true },
ingestNative = { NativeBridge.nativeIngestSharedItems(seq27Handle, "", "", 1_795_900_000_180L) },
)
checkEq(drained, 0, "seq27 $label drains 0 items from diskInbox")
}
val persistedAttachmentNames = persistedBatch!!.items.mapNotNull { it.attachmentFileName }
checkEq(
diskInbox.listPendingBatches().size == 1 &&
persistedAttachmentNames.isNotEmpty() &&
persistedAttachmentNames.all { java.io.File(diskInboxDir, it).isFile } &&
persistedBatch.items.none { NativeBridge.nativeShareIsConsumed(seq27Handle, it.id) },
true,
"seq27 disk-batch-1 manifest & PDF attachment preserved untouched across pre-bootstrap and mount failure",
)
// Healthy standalone (`resolveDrainTarget(true, trueStandaloneOutcome)` == `EphemeralStandalone`):
// delivers into the live in-memory document AND deletes `standaloneInbox` immediately!
val standaloneCommitted = shareBridge.drainDiskInbox(
inbox = standaloneInbox,
drainTargetProvider = { ShareIntentBridge.resolveDrainTarget(true, trueStandaloneOutcome) },
isReady = { true },
ingestNative = { NativeBridge.nativeIngestSharedItems(seq27Handle, "", "", 1_795_900_000_200L) },
)
checkEq(standaloneCommitted, 9, "seq27 standalone live ingest commits all 9 valid items (7 staged + 2 standalone inbox)")
checkEq(shareBridge.pendingCount(), 0, "seq27 queue clean after standalone live ingest")
checkEq(
NativeBridge.nativeShareIsDurablyCommitted(seq27Handle, "", "standalone-batch-1-0"),
false,
"seq27 unmounted workspace reports nativeShareIsDurablyCommitted == false",
)
checkEq(
standaloneInbox.listPendingBatches().isEmpty() &&
(standaloneInboxDir.listFiles()?.none { it.isFile } ?: true),
true,
"seq27 EphemeralStandalone deletes disk batch immediately after live in-memory delivery",
)
checkEq(
NativeBridge.nativeShareIsConsumed(seq27Handle, "standalone-batch-1-0") &&
NativeBridge.nativeShareIsConsumed(seq27Handle, "standalone-batch-1-pdf-0"),
true,
"seq27 nativeShareIsConsumed confirms both standalone-inbox item IDs delivered in session",
)
checkEq(
!NativeBridge.nativeShareIsConsumed(seq27Handle, "disk-batch-1-0") &&
diskInbox.listPendingBatches().size == 1,
true,
"seq27 disk-batch-1 still untouched on disk waiting for DurableWorkspace mount recovery",
)
// Simulate 3 consecutive force-stop + cold restarts on the standalone APK (brand-new native
// host + brand-new ShareIntentBridge against the same standaloneInboxDir): zero replay!
repeat(3) { restartIdx ->
val coldHandle = NativeBridge.nativeCreateHost()
try {
val coldBridge = ShareIntentBridge { coldHandle }
val replayed = coldBridge.drainDiskInbox(
inbox = standaloneInbox,
drainTargetProvider = { ShareIntentBridge.resolveDrainTarget(true, trueStandaloneOutcome) },
isReady = { true },
ingestNative = { NativeBridge.nativeIngestSharedItems(coldHandle, "", "", 1_795_900_000_300L + restartIdx) },
)
checkEq(replayed, 0, "seq27 standalone cold restart #${restartIdx + 1} replays 0 items")
val coldSnap = NativeBridge.nativeGetActivePageSnapshotJson(coldHandle) ?: ""
checkEq(
coldSnap.contains("standalone-once"),
false,
"seq27 standalone cold restart #${restartIdx + 1} snapshot has zero duplicate shared bookmark",
)
} finally {
NativeBridge.nativeDestroyHost(coldHandle)
}
}
// Selection `[6, 12)` (`"native"`) and focused paragraph `"Hello native world"` MUST remain 100% untouched!
checkEq(
NativeBridge.nativeGetUtf16Text(seq27Handle),
"Hello native world",
"seq27 focused paragraph text untouched (zero IME typing at caret)",
)
checkEq(ime27.selectionStart(), 6, "seq27 selectionStart [6, 12) preserved across standalone share")
checkEq(ime27.selectionEnd(), 12, "seq27 selectionEnd [6, 12) preserved across standalone share")
val sha256Digest = java.security.MessageDigest.getInstance("SHA-256").digest(png1x1)
val expectedBlobKey = java.util.Base64.getEncoder().encodeToString(sha256Digest)
.replace('+', '-')
.replace('/', '_')
val liveSnapJson = NativeBridge.nativeGetActivePageSnapshotJson(seq27Handle) ?: ""
checkEq(liveSnapJson.contains("affine:bookmark"), true, "seq27 standalone snapshot has real affine:bookmark block")
checkEq(liveSnapJson.contains("https://affine.pro/shared"), true, "seq27 standalone snapshot has shared URL")
checkEq(liveSnapJson.contains("SHAREDTEXT"), true, "seq27 standalone snapshot has shared quote text")
checkEq(liveSnapJson.contains("affine:image"), true, "seq27 standalone snapshot has real affine:image block")
checkEq(liveSnapJson.contains(expectedBlobKey), true, "seq27 standalone snapshot references 44-char SHA-256 blob key")
checkEq(liveSnapJson.contains("content://media"), false, "seq27 standalone snapshot never inserts raw content:// URI text")
// 2) Production SQLite workspace mode (`ws-share-27`):
// - Must commit strictly to SQLite target doc (`share-doc-...` or explicit `doc-target-b`) WITHOUT
// modifying open writable document A (`snapOpenDocABefore`) or being blocked by an unrelated read-only page.
val boot27 = AndroidBootstrapCoordinator(
handleProvider = { seq27Handle },
filesDirProvider = { seq27Dir.absolutePath },
)
val out27 = boot27.completeWithProbePayload(
"""{"origin":"https://localhost","length":1,"keys":["affine-local-workspace"],"entries":{"affine-local-workspace":"[\"ws-share-27\"]"}}""",
)
val wsKey27 = out27.connectedWorkspaceKeys.single()
val snapOpenDocABefore = NativeBridge.nativeGetActivePageSnapshotJson(seq27Handle) ?: ""
// Now that SQLite workspace `wsKey27` is mounted (`out27.isComplete == true`), `resolveDrainTarget`
// maps to `DurableWorkspace(wsKey27)`, committing `disk-batch-1` into SQLite `share_ingest_receipts`
// and ONLY THEN removing the disk files!
checkEq(
ShareIntentBridge.resolveDrainTarget(true, out27),
ShareIntentBridge.ShareDrainTarget.DurableWorkspace(wsKey27),
"seq27 resolveDrainTarget(out27) == DurableWorkspace(wsKey27)",
)
val diskMountedCommitted = shareBridge.drainDiskInbox(
inbox = diskInbox,
drainTargetProvider = { ShareIntentBridge.resolveDrainTarget(true, out27) },
isReady = { true },
ingestNative = { NativeBridge.nativeIngestSharedItems(seq27Handle, wsKey27, "", 1_795_900_000_500L) },
)
checkEq(diskMountedCommitted, 2, "seq27 mounted SQLite workspace commits retained disk-batch-1 (URL + PDF)")
checkEq(
NativeBridge.nativeShareIsDurablyCommitted(seq27Handle, wsKey27, "disk-batch-1-0") &&
NativeBridge.nativeShareIsDurablyCommitted(seq27Handle, wsKey27, "disk-batch-1-pdf-0"),
true,
"seq27 nativeShareIsDurablyCommitted confirms SQLite share_ingest_receipts rows",
)
checkEq(
diskInbox.listPendingBatches().isEmpty(),
true,
"seq27 disk inbox manifest & attachments deleted ONLY after durable SQLite receipt",
)
// Partial failure stats for ACTION_SEND_MULTIPLE (1 valid image + 1 unreadable URI).
val partialRes = diskInbox.writeBatchWithStats(
action = "android.intent.action.SEND_MULTIPLE",
mimeType = "image/png",
subject = "Partial Batch",
text = null,
streamUris = listOf("content://media/1", "content://media/unreadable"),
streamBytes = mapOf("content://media/1" to png1x1),
batchId = "partial-batch",
createdAtMs = 1_795_900_000_600L,
)
checkEq(
partialRes.batch != null && partialRes.batch.items.size == 1 && partialRes.skippedCount == 1,
true,
"seq27 ACTION_SEND_MULTIPLE partial failure reports 1 persisted + 1 skipped (for Toast)",
)
diskInbox.removeCommittedBatch(partialRes.batch!!)
// Writer cap at MAX_BATCH_ITEMS (256): 260 valid images -> 256 persisted + 4 skipped, readable back cleanly.
val capUris = (0 until 260).map { "content://media/cap/$it.png" }
val capBytes = capUris.associateWith { png1x1 }
val capRes = diskInbox.writeBatchWithStats(
action = "android.intent.action.SEND_MULTIPLE",
mimeType = "image/png",
subject = "Cap 256 Batch",
text = null,
streamUris = capUris,
streamBytes = capBytes,
batchId = "cap-256-batch",
createdAtMs = 1_795_900_000_650L,
)
checkEq(
capRes.batch != null && capRes.batch.items.size == 256 && capRes.skippedCount == 4,
true,
"seq27 writer enforces MAX_BATCH_ITEMS=256 and reports 4 skipped items",
)
val decodedCap = diskInbox.listPendingBatches()
checkEq(
decodedCap.size == 1 && decodedCap.single().items.size == 256,
true,
"seq27 reader decodes full 256-item capped batch without rejection",
)
diskInbox.removeCommittedBatch(decodedCap.single())
// Corrupt or >256 .manifest handling must quarantine BOTH `.manifest` and matching `<batchId>-att-*.bin` into invalid/ (never silently deleting attachments).
val orphanManifest = java.io.File(diskInboxDir, "corrupt-orphan.manifest")
val orphanAtt = java.io.File(diskInboxDir, "corrupt-orphan-att-0.bin")
orphanManifest.writeBytes(byteArrayOf(0x00, 0x01, 0x02))
orphanAtt.writeBytes(png1x1)
val overcapManifest = java.io.File(diskInboxDir, "overcap-257.manifest")
val overcapAtt = java.io.File(diskInboxDir, "overcap-257-att-0.bin")
java.io.DataOutputStream(java.io.FileOutputStream(overcapManifest)).use { out ->
out.writeInt(0x41465348) // "AFSH"
out.writeInt(1)
out.writeUTF("overcap-257")
out.writeLong(1_795_900_000_680L)
out.writeInt(257)
}
overcapAtt.writeBytes(png1x1)
checkEq(diskInbox.listPendingBatches().isEmpty(), true, "seq27 corrupt and >256 manifests excluded from pending list")
checkEq(
!orphanManifest.exists() && !orphanAtt.exists() &&
java.io.File(diskInbox.invalidDir, "corrupt-orphan.manifest").isFile &&
java.io.File(diskInbox.invalidDir, "corrupt-orphan-att-0.bin").isFile &&
java.io.File(diskInbox.invalidDir, "overcap-257.manifest").isFile &&
java.io.File(diskInbox.invalidDir, "overcap-257-att-0.bin").isFile,
true,
"seq27 corrupt and >256 manifests + attachments quarantined into share-inbox/invalid/",
)
// Missing attachment file referenced by a valid manifest must be quarantined into invalid/ (never treated as committed).
val missingAttBatch = diskInbox.writeBatch(
action = "android.intent.action.SEND",
mimeType = "image/png",
subject = "Missing Att",
text = null,
streamUris = listOf("content://media/1"),
streamBytes = mapOf("content://media/1" to png1x1),
batchId = "missing-att-batch",
createdAtMs = 1_795_900_000_700L,
)!!
java.io.File(diskInboxDir, missingAttBatch.items.single().attachmentFileName!!).delete()
val quarantinedIds = mutableListOf<String>()
shareBridge.drainDiskInbox(
inbox = diskInbox,
drainTargetProvider = { ShareIntentBridge.ShareDrainTarget.DurableWorkspace(wsKey27) },
isReady = { true },
ingestNative = { NativeBridge.nativeIngestSharedItems(seq27Handle, wsKey27, "", 1_795_900_000_750L) },
onBatchQuarantined = { quarantinedIds.add(it) },
)
checkEq(quarantinedIds, listOf("missing-att-batch"), "seq27 missing attachment triggers quarantine callback")
checkEq(
java.io.File(diskInbox.invalidDir, "missing-att-batch.manifest").isFile &&
diskInbox.listPendingBatches().isEmpty(),
true,
"seq27 missing attachment batch moved into share-inbox/invalid/",
)
// Repeated failed ingest attempts (>= 3) quarantine the batch into invalid/ instead of looping infinitely.
val retryFailBatch = diskInbox.writeBatch(
action = "android.intent.action.SEND",
mimeType = "text/plain",
subject = "Failing Ingest",
text = "https://affine.pro/will-fail-3x",
streamUris = emptyList(),
streamBytes = emptyMap(),
batchId = "retry-fail-batch",
createdAtMs = 1_795_900_000_800L,
)!!
quarantinedIds.clear()
repeat(ShareDiskInbox.MAX_INGEST_ATTEMPTS) {
shareBridge.drainDiskInbox(
inbox = diskInbox,
drainTargetProvider = { ShareIntentBridge.ShareDrainTarget.DurableWorkspace(wsKey27) },
isReady = { true },
ingestNative = { 0 }, // Simulate failed ingest with no SQLite commit
onBatchQuarantined = { quarantinedIds.add(it) },
)
}
checkEq(quarantinedIds, listOf(retryFailBatch.batchId), "seq27 3 failed attempts quarantine batch into invalid/")
checkEq(
java.io.File(diskInbox.invalidDir, "${retryFailBatch.batchId}.manifest").isFile &&
diskInbox.listPendingBatches().isEmpty(),
true,
"seq27 quarantined retry-fail batch resides in invalid/ with clean inbox",
)
// Clear any unconsumed item from simulated 0-return ingest so subsequent checks start clean.
NativeBridge.nativeShareDrainJson(seq27Handle)
checkEq(
shareBridge.enqueueParsedPayloads(
action = "android.intent.action.SEND",
mimeType = "image/png",
subject = "SQLite Share",
text = "https://affine.pro/sqlite-only",
streamUris = listOf("content://media/external/images/media/42"),
streamBytes = streamBytes,
idPrefix = "sql-send",
),
2,
"seq27 enqueue SQLite default-route share",
)
val sqlDefaultIngested = NativeBridge.nativeIngestSharedItems(seq27Handle, wsKey27, "", 1_795_900_001_000L)
checkEq(sqlDefaultIngested, 2, "seq27 SQLite default-route commits both items")
checkEq(
NativeBridge.nativeGetActivePageSnapshotJson(seq27Handle),
snapOpenDocABefore,
"seq27 default SQLite route NEVER double-writes into open writable document A",
)
checkEq(
shareBridge.enqueueParsedPayloads(
action = "android.intent.action.SEND",
mimeType = "text/plain",
subject = "Target B",
text = "https://affine.pro/only-in-doc-b",
streamUris = emptyList(),
idPrefix = "sql-doc-b",
),
1,
"seq27 enqueue explicit target doc B share",
)
checkEq(
NativeBridge.nativeIngestSharedItems(seq27Handle, wsKey27, "doc-target-b", 1_795_900_002_000L),
1,
"seq27 explicit target doc B committed",
)
checkEq(
NativeBridge.nativeGetActivePageSnapshotJson(seq27Handle),
snapOpenDocABefore,
"seq27 explicit target doc B leaves open writable document A 100% unchanged",
)
checkEq(ime27.selectionStart(), 6, "seq27 open document A selectionStart [6, 12) untouched")
checkEq(ime27.selectionEnd(), 12, "seq27 open document A selectionEnd [6, 12) untouched")
// 3) Interleaved consecutive ACTION_SEND image intents (`interleave-a` in flight when `interleave-b` arrives):
// Both must resolve, commit, and survive workspace reopen with exact count == 1 each.
var capturedResolveA: ((Map<String, ByteArray>) -> Unit)? = null
var capturedResolveB: ((Map<String, ByteArray>) -> Unit)? = null
val runInterleavedDrain = {
shareBridge.drainStagedQueue(
isReady = { true },
resolveStreamAsync = { desc, onResolved ->
if (desc.idPrefix == "interleave-a") {
capturedResolveA = onResolved
} else {
capturedResolveB = onResolved
}
},
ingestNative = {
NativeBridge.nativeIngestSharedItems(seq27Handle, wsKey27, "", 1_795_900_005_000L)
},
)
}
shareBridge.stageDescriptor(
ShareIntentBridge.PendingShareDescriptor(
action = "android.intent.action.SEND",
mimeType = "image/png",
subject = "Interleave A",
text = null,
streamUris = listOf("content://media/1"),
rawUris = emptyList(),
idPrefix = "interleave-a",
),
)
runInterleavedDrain()
checkEq(shareBridge.isResolveInFlight(), true, "seq27 interleave-a stream read is in flight")
checkEq(capturedResolveA != null, true, "seq27 interleave-a resolver captured")
// Arrive via onNewIntent while interleave-a is still reading bytes on background thread!
shareBridge.stageDescriptor(
ShareIntentBridge.PendingShareDescriptor(
action = "android.intent.action.SEND",
mimeType = "image/png",
subject = "Interleave B",
text = null,
streamUris = listOf("content://media/2"),
rawUris = emptyList(),
idPrefix = "interleave-b",
),
)
runInterleavedDrain()
checkEq(shareBridge.stagedIntentCount(), 1, "seq27 interleave-b queued without overwriting interleave-a")
checkEq(capturedResolveB == null, true, "seq27 interleave-b waits until interleave-a finishes")
capturedResolveA!!.invoke(streamBytes)
checkEq(capturedResolveB != null, true, "seq27 completing interleave-a automatically launches interleave-b")
capturedResolveB!!.invoke(streamBytes)
checkEq(shareBridge.isResolveInFlight(), false, "seq27 interleaved queue fully idle after both complete")
checkEq(shareBridge.stagedIntentCount(), 0, "seq27 zero staged intents left")
checkEq(shareBridge.pendingCount(), 0, "seq27 zero native share_queue items left")
// Close and reopen SQLite workspace: verify all SQLite docs (`sql-send`, `doc-target-b`, `interleave-a`, `interleave-b`) & SHA-256 blob!
checkEq(NativeBridge.nativeStorageClose(seq27Handle, wsKey27), true, "seq27 close SQLite workspace")
val reopenedKey27 = NativeBridge.nativeConnectWorkspace(seq27Handle, seq27Dir.absolutePath, "local", "ws-share-27")
checkEq(reopenedKey27, wsKey27, "seq27 reopen SQLite workspace")
checkEq(
!NativeBridge.nativeStorageGetDocB64(seq27Handle, wsKey27, "share-doc-sql-send-0").isNullOrEmpty(),
true,
"seq27 SQLite persisted share-doc-sql-send-0 across reopen",
)
checkEq(
!NativeBridge.nativeStorageGetDocB64(seq27Handle, wsKey27, "doc-target-b").isNullOrEmpty(),
true,
"seq27 SQLite persisted explicit doc-target-b across reopen",
)
checkEq(
!NativeBridge.nativeStorageGetDocB64(seq27Handle, wsKey27, "share-doc-interleave-a-img-0").isNullOrEmpty(),
true,
"seq27 SQLite persisted interleaved intent A across reopen",
)
checkEq(
!NativeBridge.nativeStorageGetDocB64(seq27Handle, wsKey27, "share-doc-interleave-b-img-0").isNullOrEmpty(),
true,
"seq27 SQLite persisted interleaved intent B across reopen",
)
val persistedBlobB64 = NativeBridge.nativeStorageGetBlobB64(seq27Handle, wsKey27, expectedBlobKey)
checkEq(
persistedBlobB64,
java.util.Base64.getEncoder().encodeToString(png1x1),
"seq27 SQLite persisted exact SHA-256 image bytes in blobs table across reopen",
)
val dupEnqueued = shareBridge.enqueueParsedPayloads(
action = "android.intent.action.SEND",
mimeType = "image/png",
subject = "SQLite Share",
text = "https://affine.pro/sqlite-only",
streamUris = listOf("content://media/external/images/media/42"),
streamBytes = streamBytes,
idPrefix = "sql-send",
)
checkEq(dupEnqueued, 0, "seq27 duplicate share IDs rejected idempotently after ingest")
} finally {
NativeBridge.nativeDestroyHost(seq27Handle)
seq27Dir.deleteRecursively()
}
// Sequence 28: 0.27.5 https://localhost same-signature upgrade + rollback writeback drill.
val seq28Handle = NativeBridge.nativeCreateHost()
val seq28Dir = java.nio.file.Files.createTempDirectory("affine-0275-drill-").toFile()
try {
val probePayload = """
{
"origin": "https://localhost",
"length": 4,
"keys": ["affine-local-workspace", "theme", "last_workspace_id", "capacitor_noise"],
"entries": {
"affine-local-workspace": "[\"ws-0275-a\"]",
"theme": "dark",
"last_workspace_id": "ws-0275-a"
}
}
""".trimIndent()
val coordinator28 = AndroidBootstrapCoordinator(
handleProvider = { seq28Handle },
filesDirProvider = { seq28Dir.absolutePath },
)
val outcome = coordinator28.completeWithProbePayload(probePayload)
checkEq(outcome.imported, true, "seq28 0.27.5 probe imported")
checkEq(outcome.connectedWorkspaceKeys.size, 1, "seq28 allowlisted ws-0275-a mounted in place")
val writebackJson = NativeBridge.nativePlanLegacyLocalStorageWriteBack(seq28Handle) ?: ""
checkEq(writebackJson.contains("ws-0275-a"), true, "seq28 rollback writeback preserves ws-0275-a")
checkEq(writebackJson.contains("capacitor_noise"), false, "seq28 rollback writeback never deletes noise key")
} finally {
NativeBridge.nativeDestroyHost(seq28Handle)
seq28Dir.deleteRecursively()
}
println("Kotlin JNI Android host parity check passed (28/28 sequences)")
}
+1 -1
View File
@@ -1,7 +1,7 @@
# Working in `packages/frontend/hosts/ios/` (for agents)
This directory holds the zero-CocoaPods iOS thin host for AFFiNE.
It bridges `UIKit`, `CAMetalLayer`, ProMotion `CADisplayLink`, `UITextInput`, system `UITextInteraction` (`.editable` / `.nonEditable`) + `UIEditMenuInteraction`, per-frame keyboard avoidance (`KeyboardAvoidanceCoordinator`), system `PDFKit` page rasterization (`PdfRendererBridge`), and UIKit haptics (`HapticsBridge`) to the Rust client workspace through a C ABI.
It bridges `UIKit`, `CAMetalLayer`, ProMotion `CADisplayLink`, `UITextInput`, system `UITextInteraction` (`.editable` / `.nonEditable`) + `UIEditMenuInteraction`, per-frame keyboard avoidance (`KeyboardAvoidanceCoordinator`), system `PDFKit` page rasterization (`PdfRendererBridge`), UIKit haptics (`HapticsBridge`), and three zero-CocoaPods native-island bridges (`ShareExtensionBridge`, `AffinePaywallBridge`, `OnboardingSignInBridge`) to the Rust client workspace through a C ABI.
## Hard boundaries
+13
View File
@@ -18,6 +18,19 @@
<string>0.27.5</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLName</key>
<string>app.affine.pro</string>
<key>CFBundleURLSchemes</key>
<array>
<string>affine</string>
</array>
</dict>
</array>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UIApplicationSupportsIndirectInputEvents</key>
@@ -0,0 +1,280 @@
import Foundation
/// Authoritative verified StoreKit 2 entitlement snapshot persisted atomically on disk.
struct PaywallEntitlementSnapshot: Codable, Equatable, Sendable {
let transactionId: String
let productId: String
let jwsRepresentation: String
let expirationDate: Date?
let revocationDate: Date?
}
/// Zero-CocoaPods StoreKit 2 paywall narrow bridge (`AffinePaywall`).
///
/// Architectural safety contract:
/// - Never starts a `Transaction.updates` listener on the app launch path, never invokes
/// `product.purchase()`, and never calls `transaction.finish()`.
/// - Filters all entitlement snapshots through the 3-product `0.27.5` allowlist + compact
/// 3-segment JWS check before persisting to disk or selecting the primary Rust entitlement.
/// - Reconciles persisted snapshots atomically between disk and Rust state, rolling back both
/// if persistence or FFI synchronization fails.
@MainActor
final class AffinePaywallBridge {
/// Exact `0.27.5` App Store Connect product identifiers (`PricingConfiguration.swift`).
nonisolated static let defaultProductIds: [String] = [
"app.affine.pro.Monthly",
"app.affine.pro.Annual",
"app.affine.pro.ai.Annual",
]
private var hostHandle: OpaquePointer?
private let entitlementFileUrl: URL
private(set) var activeEntitlements: [String: PaywallEntitlementSnapshot] = [:]
private static func makeEncoder() -> JSONEncoder {
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
return encoder
}
private static func makeDecoder() -> JSONDecoder {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
return decoder
}
/// Validates that `productId` is in the `0.27.5` 3-product allowlist.
nonisolated static func isAllowlistedProduct(_ productId: String) -> Bool {
defaultProductIds.contains(productId)
}
/// Validates a compact 3-segment base64url JWS string (`header.payload.signature`).
nonisolated static func isValidJwsEnvelope(_ jws: String) -> Bool {
let parts = jws.split(separator: ".", omittingEmptySubsequences: false)
guard parts.count == 3 else {
return false
}
return parts.allSatisfy { seg in
!seg.isEmpty && seg.utf8.allSatisfy { b in
(b >= 0x30 && b <= 0x39)
|| (b >= 0x41 && b <= 0x5A)
|| (b >= 0x61 && b <= 0x7A)
|| b == 0x2D
|| b == 0x5F
}
}
}
/// Single authoritative entitlement active predicate: not revoked and not expired.
nonisolated static func isActiveEntitlement(
revocationDate: Date?,
expirationDate: Date?,
now: Date = Date()
) -> Bool {
guard revocationDate == nil else {
return false
}
if let expirationDate {
return expirationDate > now
}
return true
}
nonisolated static func isEligibleSnapshot(
_ snapshot: PaywallEntitlementSnapshot,
now: Date = Date()
) -> Bool {
guard
!snapshot.transactionId.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
isAllowlistedProduct(snapshot.productId),
isValidJwsEnvelope(snapshot.jwsRepresentation)
else {
return false
}
return isActiveEntitlement(
revocationDate: snapshot.revocationDate,
expirationDate: snapshot.expirationDate,
now: now
)
}
init(entitlementFileUrl: URL? = nil) {
if let entitlementFileUrl {
self.entitlementFileUrl = entitlementFileUrl
} else if let appSupport = FileManager.default.urls(
for: .applicationSupportDirectory,
in: .userDomainMask
).first {
self.entitlementFileUrl = appSupport
.appendingPathComponent("affine-paywall", isDirectory: true)
.appendingPathComponent("verified-entitlements.json")
} else {
self.entitlementFileUrl = FileManager.default.temporaryDirectory
.appendingPathComponent("affine-paywall-entitlements.json")
}
}
func attach(host: OpaquePointer, now: Date = Date()) {
hostHandle = host
_ = restorePersistedEntitlements(into: host, now: now)
}
func detach() {
hostHandle = nil
}
private func writeEntitlementsToDisk(_ map: [String: PaywallEntitlementSnapshot]) -> Bool {
let fm = FileManager.default
if map.isEmpty {
if fm.fileExists(atPath: entitlementFileUrl.path) {
do {
try fm.removeItem(at: entitlementFileUrl)
} catch {
return false
}
}
return true
}
let sorted = map.values.sorted { $0.transactionId < $1.transactionId }
do {
try fm.createDirectory(
at: entitlementFileUrl.deletingLastPathComponent(),
withIntermediateDirectories: true
)
let data = try Self.makeEncoder().encode(sorted)
try data.write(to: entitlementFileUrl, options: .atomic)
return true
} catch {
return false
}
}
private func syncRustEntitlementState(
from map: [String: PaywallEntitlementSnapshot],
host: OpaquePointer
) -> Bool {
guard let primary = map.values.sorted(by: { $0.transactionId < $1.transactionId }).first else {
return affine_ios_island_paywall_clear_entitlements(host)
}
return primary.productId.withCString { cPid in
primary.transactionId.withCString { cTx in
primary.jwsRepresentation.withCString { cJws in
affine_ios_island_paywall_complete_jws(host, cPid, cTx, cJws)
}
}
}
}
private func commitEntitlementMapAtomically(
_ nextMap: [String: PaywallEntitlementSnapshot],
host: OpaquePointer
) -> Bool {
let previous = activeEntitlements
guard writeEntitlementsToDisk(nextMap) else {
activeEntitlements = previous
return false
}
guard syncRustEntitlementState(from: nextMap, host: host) else {
_ = writeEntitlementsToDisk(previous)
_ = syncRustEntitlementState(from: previous, host: host)
activeEntitlements = previous
return false
}
activeEntitlements = nextMap
return true
}
@discardableResult
func restorePersistedEntitlements(into host: OpaquePointer, now: Date = Date()) -> Bool {
guard
let data = try? Data(contentsOf: entitlementFileUrl),
let records = try? Self.makeDecoder().decode([PaywallEntitlementSnapshot].self, from: data)
else {
activeEntitlements = [:]
_ = affine_ios_island_paywall_clear_entitlements(host)
return false
}
return reconcileCurrentEntitlements(records, host: host, now: now)
}
@discardableResult
func reconcileCurrentEntitlements(
_ snapshots: [PaywallEntitlementSnapshot],
host: OpaquePointer? = nil,
now: Date = Date()
) -> Bool {
guard let activeHost = host ?? hostHandle else {
return false
}
var nextActive: [String: PaywallEntitlementSnapshot] = [:]
for snap in snapshots where Self.isEligibleSnapshot(snap, now: now) {
nextActive[snap.transactionId] = snap
}
return commitEntitlementMapAtomically(nextActive, host: activeHost)
}
@discardableResult
func applyVerifiedTransactionUpdate(
_ snapshot: PaywallEntitlementSnapshot,
host: OpaquePointer? = nil,
now: Date = Date()
) -> Bool {
guard let activeHost = host ?? hostHandle else {
return false
}
var nextMap = activeEntitlements.filter { _, existing in
Self.isEligibleSnapshot(existing, now: now)
}
let trimmedTxId = snapshot.transactionId.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmedTxId.isEmpty else {
"empty transaction id".withCString {
_ = affine_ios_island_paywall_finish_non_verified(activeHost, 2, $0)
}
return false
}
if !Self.isAllowlistedProduct(snapshot.productId) || !Self.isValidJwsEnvelope(snapshot.jwsRepresentation) {
if nextMap.isEmpty {
"invalid StoreKit product or JWS envelope".withCString {
_ = affine_ios_island_paywall_finish_non_verified(activeHost, 2, $0)
}
}
return false
}
if Self.isActiveEntitlement(
revocationDate: snapshot.revocationDate,
expirationDate: snapshot.expirationDate,
now: now
) {
nextMap[trimmedTxId] = snapshot
return commitEntitlementMapAtomically(nextMap, host: activeHost)
} else {
nextMap.removeValue(forKey: trimmedTxId)
return commitEntitlementMapAtomically(nextMap, host: activeHost)
}
}
func syncProductsPayload(host: OpaquePointer, payload: [[String: String]]) -> Bool {
guard
let data = try? JSONSerialization.data(withJSONObject: payload),
let json = String(data: data, encoding: .utf8)
else {
return false
}
return json.withCString { affine_ios_island_paywall_set_products_json(host, $0) }
}
func beginPurchase(host: OpaquePointer, productId: String) -> Bool {
productId.withCString { affine_ios_island_paywall_begin_purchase(host, $0) }
}
func stateJson(host: OpaquePointer) -> String {
guard let ptr = affine_ios_island_paywall_state_json(host) else {
return "{}"
}
defer { affine_ios_string_free(ptr) }
return String(cString: ptr)
}
}
@@ -36,8 +36,21 @@ final class SceneDelegate: UIResponder, UIWindowSceneDelegate {
return
}
let window = UIWindow(windowScene: windowScene)
window.rootViewController = MetalHostViewController()
let rootVC = MetalHostViewController()
window.rootViewController = rootVC
window.makeKeyAndVisible()
self.window = window
for context in connectionOptions.urlContexts {
_ = rootVC.handleIncomingUrl(context.url)
}
}
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
guard let rootVC = window?.rootViewController as? MetalHostViewController else {
return
}
for context in URLContexts {
_ = rootVC.handleIncomingUrl(context.url)
}
}
}
@@ -26,16 +26,24 @@ enum HostBootstrapError: Error, Equatable {
/// rollback write-back planning -> background `PASSIVE` WAL checkpoints.
@MainActor
final class HostBootstrapCoordinator {
private let probe = LegacyLocalStorageProbe()
private let probe: LegacyLocalStorageProbe
private let documentsDirectory: URL?
private(set) var imported: Bool = false
private(set) var allowlistedLocalIds: [String] = []
private(set) var lastFailedMountIds: [String] = []
private(set) var lastSnapshot: LegacyLocalStorageSnapshot?
private(set) var importedStateJson: String?
private var activeWorkspaces: [String: WorkspaceStorageBridge] = [:]
init(documentsDirectory: URL? = nil) {
/// True only after legacy storage bootstrap completed cleanly with zero local workspaces.
/// Remains false when `LegacyLocalStorageProbe` fails or times out (fail-closed).
var canCreateDefaultWorkspace: Bool {
imported && lastFailedMountIds.isEmpty && allowlistedLocalIds.isEmpty
}
init(documentsDirectory: URL? = nil, probe: LegacyLocalStorageProbe? = nil) {
self.documentsDirectory = documentsDirectory
self.probe = probe ?? LegacyLocalStorageProbe()
}
/// Run the one-shot legacy `capacitor://localhost` probe and mount allowlisted local workspaces.
@@ -74,6 +82,7 @@ final class HostBootstrapCoordinator {
lastSnapshot = snapshot
importedStateJson = stateJson
try reconcileActiveWorkspaces(disposition.state.localWorkspaceIds)
imported = true
return disposition
}
@@ -120,6 +129,10 @@ final class HostBootstrapCoordinator {
activeWorkspaces[id]
}
func mountedWorkspacesSnapshot() -> [String: WorkspaceStorageBridge] {
activeWorkspaces
}
/// Non-blocking `PRAGMA wal_checkpoint(PASSIVE)` across all active workspaces on background entry.
@discardableResult
func checkpointAllPassive() -> Bool {
@@ -1,4 +1,5 @@
import Foundation
import UIKit
import WebKit
/// Unified `WebViewStorageSentinel` payload captured from the legacy Capacitor origin.
@@ -50,9 +51,48 @@ private final class LegacyCapacitorSchemeHandler: NSObject, WKURLSchemeHandler {
/// origin with a hard runtime trap forbidding any IndexedDB access (`idbAccessCount == 0`).
@MainActor
final class LegacyLocalStorageProbe: NSObject, WKNavigationDelegate {
typealias TimeoutScheduler =
@MainActor (_ delaySeconds: TimeInterval, _ onTimeout: @escaping @MainActor () -> Void) -> () -> Void
static let legacyOrigin = "capacitor://localhost"
static let probeURLString = "capacitor://localhost/__affine_probe__"
static let localWorkspaceKey = "affine-local-workspace"
nonisolated static let defaultNavigationTimeoutSeconds: TimeInterval = 15.0
nonisolated static let defaultEvaluationTimeoutSeconds: TimeInterval = 10.0
/// Shared warm WebContent process pool reused across probe calls to avoid cold XPC churn.
private static let sharedProcessPool = WKProcessPool()
private static func defaultTimeoutScheduler(
delaySeconds: TimeInterval,
onTimeout: @escaping @MainActor () -> Void
) -> () -> Void {
let clamped = max(0.1, delaySeconds)
let task = Task { @MainActor in
try? await Task.sleep(nanoseconds: UInt64(clamped * 1_000_000_000))
guard !Task.isCancelled else {
return
}
onTimeout()
}
return { task.cancel() }
}
private static func activeForegroundWindow() -> UIWindow? {
let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }
let foregroundScenes = scenes.filter {
$0.activationState == .foregroundActive || $0.activationState == .foregroundInactive
}
for scene in foregroundScenes + scenes {
if let key = scene.windows.first(where: { $0.isKeyWindow && !$0.isHidden }) {
return key
}
if let visible = scene.windows.first(where: { !$0.isHidden }) {
return visible
}
}
return nil
}
/// Delegate allowlist membership directly to `affine-legacy-import` via Rust C-ABI.
static func isWhitelistedKey(_ key: String) -> Bool {
@@ -103,20 +143,38 @@ final class LegacyLocalStorageProbe: NSObject, WKNavigationDelegate {
case writeBack(set: [String: String], remove: [String])
}
private let timeoutScheduler: TimeoutScheduler
private let hostWindowProvider: () -> UIWindow?
private var webView: WKWebView?
private var mode: Mode = .capture(allowedKeys: [])
private var continuation: CheckedContinuation<LegacyLocalStorageSnapshot, Error>?
private var timeoutTask: Task<Void, Never>?
private var cancelTimeout: (() -> Void)?
private var activeRunId: UInt64 = 0
private var activeEvaluationTimeoutSeconds: TimeInterval = LegacyLocalStorageProbe.defaultEvaluationTimeoutSeconds
init(
timeoutScheduler: TimeoutScheduler? = nil,
hostWindowProvider: (() -> UIWindow?)? = nil
) {
self.timeoutScheduler = timeoutScheduler ?? Self.defaultTimeoutScheduler
self.hostWindowProvider = hostWindowProvider ?? Self.activeForegroundWindow
super.init()
}
/// Capture the unified `WebViewStorageSentinel` from `capacitor://localhost`:
/// `keys` holds all sorted `localStorage` keys (`keys.count == length`), while `entries`
/// contains strictly whitelisted key-value pairs.
func capture(
allowedKeys: [String] = [],
timeoutSeconds: TimeInterval = 5.0
timeoutSeconds: TimeInterval = LegacyLocalStorageProbe.defaultEvaluationTimeoutSeconds,
navigationTimeoutSeconds: TimeInterval = LegacyLocalStorageProbe.defaultNavigationTimeoutSeconds
) async throws -> LegacyLocalStorageSnapshot {
try await run(mode: .capture(allowedKeys: allowedKeys), timeoutSeconds: timeoutSeconds)
try await run(
mode: .capture(allowedKeys: allowedKeys),
navigationTimeoutSeconds: navigationTimeoutSeconds,
evaluationTimeoutSeconds: timeoutSeconds
)
}
/// Write whitelisted mutated state back to `capacitor://localhost` `localStorage` and
@@ -124,12 +182,14 @@ final class LegacyLocalStorageProbe: NSObject, WKNavigationDelegate {
func writeBackLegacyLocalStorage(
set: [String: String],
remove: [String],
timeoutSeconds: TimeInterval = 5.0
timeoutSeconds: TimeInterval = LegacyLocalStorageProbe.defaultEvaluationTimeoutSeconds,
navigationTimeoutSeconds: TimeInterval = LegacyLocalStorageProbe.defaultNavigationTimeoutSeconds
) async throws -> LegacyLocalStorageSnapshot {
try Self.validateWriteBackKeys(set: set, remove: remove)
let snapshot = try await run(
mode: .writeBack(set: set, remove: remove),
timeoutSeconds: timeoutSeconds
navigationTimeoutSeconds: navigationTimeoutSeconds,
evaluationTimeoutSeconds: timeoutSeconds
)
for (key, expected) in set {
guard snapshot.entries[key] == expected else {
@@ -144,9 +204,17 @@ final class LegacyLocalStorageProbe: NSObject, WKNavigationDelegate {
return snapshot
}
private func armTimeout(seconds: TimeInterval, runId: UInt64) {
cancelTimeout?()
cancelTimeout = timeoutScheduler(seconds) { [weak self] in
self?.finish(runId: runId, result: .failure(LegacyLocalStorageProbeError.timedOut))
}
}
private func run(
mode: Mode,
timeoutSeconds: TimeInterval
navigationTimeoutSeconds: TimeInterval,
evaluationTimeoutSeconds: TimeInterval
) async throws -> LegacyLocalStorageSnapshot {
guard continuation == nil else {
throw LegacyLocalStorageProbeError.alreadyInProgress
@@ -154,6 +222,7 @@ final class LegacyLocalStorageProbe: NSObject, WKNavigationDelegate {
activeRunId &+= 1
let currentRunId = activeRunId
self.mode = mode
self.activeEvaluationTimeoutSeconds = evaluationTimeoutSeconds
let userContent = WKUserContentController()
let idbGuard = WKUserScript(
@@ -164,20 +233,26 @@ final class LegacyLocalStorageProbe: NSObject, WKNavigationDelegate {
userContent.addUserScript(idbGuard)
let configuration = WKWebViewConfiguration()
configuration.processPool = Self.sharedProcessPool
configuration.userContentController = userContent
configuration.websiteDataStore = .default()
configuration.setURLSchemeHandler(LegacyCapacitorSchemeHandler(), forURLScheme: "capacitor")
let webView = WKWebView(frame: .zero, configuration: configuration)
let webView = WKWebView(frame: CGRect(x: 0, y: 0, width: 1, height: 1), configuration: configuration)
webView.alpha = 0.0
webView.isUserInteractionEnabled = false
webView.accessibilityElementsHidden = true
webView.navigationDelegate = self
if let hostWindow = hostWindowProvider() {
hostWindow.addSubview(webView)
}
self.webView = webView
return try await withCheckedThrowingContinuation { continuation in
self.continuation = continuation
let clampedTimeout = max(0.1, timeoutSeconds)
self.timeoutTask = Task { @MainActor [weak self] in
try? await Task.sleep(nanoseconds: UInt64(clampedTimeout * 1_000_000_000))
self?.finish(runId: currentRunId, result: .failure(LegacyLocalStorageProbeError.timedOut))
self.armTimeout(seconds: navigationTimeoutSeconds, runId: currentRunId)
guard self.continuation != nil else {
return
}
guard let probeURL = URL(string: Self.probeURLString) else {
self.finish(
@@ -192,6 +267,15 @@ final class LegacyLocalStorageProbe: NSObject, WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
let runId = activeRunId
guard continuation != nil else {
return
}
// Start the JS evaluation safety ceiling after navigation finishes (WebContent is warm).
armTimeout(seconds: activeEvaluationTimeoutSeconds, runId: runId)
guard continuation != nil else {
return
}
let script: String
switch mode {
case .capture(let allowedKeys):
@@ -367,11 +451,12 @@ final class LegacyLocalStorageProbe: NSObject, WKNavigationDelegate {
return
}
continuation = nil
timeoutTask?.cancel()
timeoutTask = nil
cancelTimeout?()
cancelTimeout = nil
webView?.stopLoading()
webView?.configuration.userContentController.removeAllUserScripts()
webView?.navigationDelegate = nil
webView?.removeFromSuperview()
webView = nil
activeContinuation.resume(with: result)
}
@@ -489,6 +489,8 @@ final class MetalHostView: UIView, UITextInput {
set {}
}
var keyboardAppearance: UIKeyboardAppearance = .default
func syncCodeInputTraitsIfNeeded() {
let next = wantsCodeInput
if next != lastWantsCodeInput {
@@ -1643,7 +1645,6 @@ final class MetalHostView: UIView, UITextInput {
_ = resignFirstResponder()
}
}
override func didMoveToWindow() {
super.didMoveToWindow()
onDidMoveToWindow?()
@@ -1816,6 +1817,9 @@ final class MetalHostViewController:
private let textRenderingBridge = TextRenderingBridge()
private let hapticsBridge = HapticsBridge()
private let bootstrapCoordinator = HostBootstrapCoordinator()
private let shareExtensionBridge = ShareExtensionBridge()
private let paywallBridge = AffinePaywallBridge()
private let onboardingSignInBridge = OnboardingSignInBridge()
private var editorMetalLayer: CAMetalLayer?
private var textInteraction: UITextInteraction?
private var textInteractionIsReadonly = false
@@ -1857,6 +1861,7 @@ final class MetalHostViewController:
)
private(set) var lastBootstrapError: Error?
private var bootstrapCompleted = false
private var bootstrapTask: Task<Void, Never>?
private var hostHandle: OpaquePointer?
private var displayLink: CADisplayLink?
private var displayLinkProxy: DisplayLinkProxy?
@@ -1867,6 +1872,60 @@ final class MetalHostViewController:
var haptics: HapticsBridge { hapticsBridge }
var textRenderer: TextRenderingBridge { textRenderingBridge }
var hostPointer: OpaquePointer? { hostHandle }
var shareExtension: ShareExtensionBridge { shareExtensionBridge }
var paywall: AffinePaywallBridge { paywallBridge }
var onboardingSignIn: OnboardingSignInBridge { onboardingSignInBridge }
/// Routes incoming `affine://auth/callback?...` and `affine://share-inbox` URLs from `SceneDelegate`
/// without exposing any raw host pointers outside the view controller.
@discardableResult
func handleIncomingUrl(_ url: URL) -> Bool {
guard let handle = hostHandle else {
return false
}
guard url.scheme?.lowercased() == "affine" else {
return false
}
let hostComponent = url.host?.lowercased() ?? ""
if hostComponent == "share-inbox" {
drainPendingShareInboxInBackground()
affine_ios_host_request_frame(handle)
wakeDisplayLink()
return true
}
guard hostComponent == "auth" else {
return false
}
let handled = onboardingSignInBridge.handleOAuthCallbackUrl(url, host: handle)
if handled {
affine_ios_host_request_frame(handle)
wakeDisplayLink()
}
return handled
}
private func drainPendingShareInboxInBackground() {
guard bootstrapCompleted else {
return
}
let preferredWorkspaceId = bootstrapCoordinator.lastSnapshot?.entries["last_workspace_id"]
let activeWorkspace = preferredWorkspaceId.flatMap { bootstrapCoordinator.workspace(id: $0) }
?? bootstrapCoordinator.allowlistedLocalIds
.compactMap { bootstrapCoordinator.workspace(id: $0) }
.first
let mountedMap = bootstrapCoordinator.mountedWorkspacesSnapshot()
shareExtensionBridge.drainInBackground(
workspace: activeWorkspace,
mountedWorkspaces: mountedMap,
onMainThreadCompletion: { [weak self] (ingested: Int) in
guard let self, ingested > 0, let handle = self.hostHandle else {
return
}
affine_ios_host_request_frame(handle)
self.wakeDisplayLink()
}
)
}
override func loadView() {
let root = UIView()
@@ -1921,6 +1980,7 @@ final class MetalHostViewController:
hostView.layer.insertSublayer(metalLayer, at: 0)
editorMetalLayer = metalLayer
}
paywallBridge.attach(host: handle)
}
applyClearColor(TextRenderingBridge.defaultClearColorRgba)
@@ -1931,6 +1991,9 @@ final class MetalHostViewController:
hostView.onDidMoveToWindow = { [weak self] in
self?.attachSystemGestureObservers()
if let self, self.view.window != nil {
self.retryBootstrapIfNeeded()
}
}
hostView.onQuerySystemGestureActive = { [weak self] in
self?.isSystemSelectionGestureActive ?? false
@@ -1970,7 +2033,9 @@ final class MetalHostViewController:
}
observeNotifications()
startDisplayLink()
retryBootstrapIfNeeded()
if view.window != nil {
retryBootstrapIfNeeded()
}
}
private func installTextInteraction(readonly: Bool) {
@@ -1998,17 +2063,20 @@ final class MetalHostViewController:
@MainActor
func retryBootstrapIfNeeded() {
guard !bootstrapCompleted else {
guard !bootstrapCompleted, bootstrapTask == nil else {
return
}
Task { @MainActor [weak self] in
bootstrapTask = Task { @MainActor [weak self] in
guard let self else {
return
}
defer { self.bootstrapTask = nil }
do {
_ = try await self.bootstrapCoordinator.bootstrapFromLegacyStorage()
guard !Task.isCancelled else { return }
self.lastBootstrapError = nil
self.bootstrapCompleted = true
self.drainPendingShareInboxInBackground()
} catch {
self.lastBootstrapError = error
}
@@ -2081,6 +2149,8 @@ final class MetalHostViewController:
}
deinit {
bootstrapTask?.cancel()
bootstrapTask = nil
timerWakeWorkItem?.cancel()
timerWakeWorkItem = nil
displayLink?.invalidate()
@@ -2097,6 +2167,9 @@ final class MetalHostViewController:
handle,
AffineClipboardProvider(write_json: nil, read_json: nil, user_data: nil)
)
MainActor.assumeIsolated {
paywallBridge.detach()
}
textRenderingBridge.detach()
pdfRendererBridge.detach(from: handle)
hapticsBridge.detach(from: handle)
@@ -2122,12 +2195,36 @@ final class MetalHostViewController:
view.window?.backgroundColor = bg
}
let expectedStyle: UIUserInterfaceStyle = textRenderingBridge.isDarkCanvas ? .dark : .light
if overrideUserInterfaceStyle != expectedStyle || textRenderingBridge.isDarkCanvas != wasDark {
let targetKeyboard: UIKeyboardAppearance = textRenderingBridge.isDarkCanvas ? .dark : .light
if overrideUserInterfaceStyle != expectedStyle
|| textRenderingBridge.isDarkCanvas != wasDark
|| hostView.keyboardAppearance != targetKeyboard
{
overrideUserInterfaceStyle = expectedStyle
view.overrideUserInterfaceStyle = expectedStyle
hostView.overrideUserInterfaceStyle = expectedStyle
view.window?.overrideUserInterfaceStyle = expectedStyle
if hostView.keyboardAppearance != targetKeyboard {
hostView.keyboardAppearance = targetKeyboard
if hostView.isFirstResponder {
hostView.reloadInputViews()
}
}
setNeedsStatusBarAppearanceUpdate()
}
}
/// Renders one dirty frame immediately and syncs background/dark-chrome appearance.
@discardableResult
func renderFrameNow(timestamp: Double = CACurrentMediaTime()) -> UInt32 {
guard let handle = hostHandle else { return 0 }
let clearRgba = affine_ios_host_render_frame(handle, timestamp)
if clearRgba != 0 {
applyClearColor(clearRgba)
}
return clearRgba
}
private var isSystemSelectionGestureActive: Bool {
let gestures = textInteraction?.gesturesForFailureRequirements ?? []
return gestures.contains { $0.state == .began || $0.state == .changed }
@@ -2493,6 +2590,8 @@ final class MetalHostViewController:
}
@objc private func handleWillEnterForeground() {
shareExtensionBridge.resetFailedBackoff()
drainPendingShareInboxInBackground()
if let handle = hostHandle {
affine_ios_host_request_frame(handle)
}
@@ -0,0 +1,65 @@
import Foundation
/// Zero-CocoaPods Onboarding + Native Sign-In narrow bridge.
///
/// Enforces the two-stage sign-in state machine in Rust without issuing network requests directly:
/// 1. Stage 1 (`pending_exchange`): validates CSRF `state` (OAuth deep-link callback) or compact
/// 3-segment JWS (Sign in with Apple) in Rust without prematurely marking sign-in completed.
/// 2. Stage 2 (`completed` / `sign_in_choice`): records the verified session subject via
/// `confirmSessionExchange` or resets on error via `failSessionExchange`.
@MainActor
final class OnboardingSignInBridge {
/// Begins OAuth flow with CSRF state registered in Rust (`authenticating`).
func beginOAuth(host: OpaquePointer, csrfState: String) -> Bool {
csrfState.withCString { affine_ios_island_onboarding_begin_oauth(host, $0) }
}
/// Stage 1: handles `affine://auth/callback?code=...&state=...` deep link, verifies CSRF state in
/// Rust, and transitions into `pending_exchange` without marking sign-in completed prematurely.
func handleOAuthCallbackUrl(_ url: URL, host: OpaquePointer) -> Bool {
guard
let components = URLComponents(url: url, resolvingAgainstBaseURL: false),
let items = components.queryItems,
let code = items.first(where: { $0.name == "code" })?.value,
let state = items.first(where: { $0.name == "state" })?.value
else {
return false
}
return code.withCString { cCode in
state.withCString { cState in
affine_ios_island_onboarding_complete_oauth(host, cCode, cState)
}
}
}
/// Records a verified Apple Sign-In credential into `pending_exchange` awaiting session confirmation.
func completeAppleCredential(
host: OpaquePointer,
userIdentifier: String,
identityTokenJws: String
) -> Bool {
userIdentifier.withCString { cUid in
identityTokenJws.withCString { cJws in
affine_ios_island_onboarding_complete_apple(host, cUid, cJws)
}
}
}
/// Finalizes session exchange with the verified user `subject` (`completed`).
func confirmSessionExchange(host: OpaquePointer, subject: String) -> Bool {
subject.withCString { affine_ios_island_onboarding_confirm_session(host, $0) }
}
/// Marks session exchange as failed (`sign_in_choice`) so the user can retry.
func failSessionExchange(host: OpaquePointer, reason: String) -> Bool {
reason.withCString { affine_ios_island_onboarding_fail_session(host, $0) }
}
func stateJson(host: OpaquePointer) -> String {
guard let ptr = affine_ios_island_onboarding_state_json(host) else {
return "{}"
}
defer { affine_ios_string_free(ptr) }
return String(cString: ptr)
}
}
@@ -0,0 +1,613 @@
import CryptoKit
import Foundation
/// 1:1 mirror of `packages/frontend/apps/ios/App/Shared/ShareInbox/ShareInboxModels.swift`
/// so the thin iOS host consumes the exact files written by the shipping ShareExtension
/// under `<AppGroup:group.app.affine.pro>/ShareInbox/<id>.json` and
/// `ShareInbox/Attachments/<id>/<fileName>`.
struct ShareInboxAttachment: Codable, Equatable {
var fileName: String
var mimeType: String
/// Relative to `ShareInbox/Attachments/` (i.e. `"<item.id>/<fileName>"`).
var relativePath: String
}
enum ShareInboxContentKind: String, Codable {
case url
case text
case image
case pdf
}
struct ShareInboxContent: Codable, Equatable {
var kind: ShareInboxContentKind
var url: String?
var text: String?
}
struct ShareInboxTarget: Codable, Equatable {
var workspaceId: String
var workspaceFlavour: String
var tagIds: [String]
var collectionId: String?
}
struct ShareInboxResult: Codable, Equatable {
var docId: String
var committedAt: Date
}
struct ShareInboxItem: Codable, Equatable {
static let currentSchemaVersion = 2
var schemaVersion: Int
var importAttemptId: String
var id: String
var documentId: String
var createdAt: Date
var title: String
var content: ShareInboxContent
var target: ShareInboxTarget?
var previewRoute: String?
var previewText: String?
var attachments: [ShareInboxAttachment]
var result: ShareInboxResult?
var lastError: String?
enum CodingKeys: String, CodingKey {
case schemaVersion
case importAttemptId
case id
case documentId
case createdAt
case title
case content
case target
case previewRoute
case previewText
case attachments
case result
case lastError
}
init(
id: String = UUID().uuidString,
documentId: String = UUID().uuidString,
importAttemptId: String = UUID().uuidString,
createdAt: Date = Date(),
title: String,
content: ShareInboxContent,
target: ShareInboxTarget? = nil,
previewRoute: String? = "deferred",
previewText: String? = nil,
attachments: [ShareInboxAttachment] = [],
result: ShareInboxResult? = nil,
lastError: String? = nil
) {
self.schemaVersion = Self.currentSchemaVersion
self.importAttemptId = importAttemptId
self.id = id
self.documentId = documentId
self.createdAt = createdAt
self.title = title
self.content = content
self.target = target
self.previewRoute = previewRoute
self.previewText = previewText
self.attachments = attachments
self.result = result
self.lastError = lastError
}
/// Matches `ShareInboxModels.swift:123-152`: supports schemaVersion 1 (defaults missing
/// `importAttemptId` & optional fields) and schemaVersion 2 (requires non-empty `importAttemptId`).
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let schemaVersion = try container.decodeIfPresent(Int.self, forKey: .schemaVersion) ?? 1
self.schemaVersion = schemaVersion
if schemaVersion == 1 {
importAttemptId = UUID().uuidString
} else {
let importAttemptId = try container.decode(String.self, forKey: .importAttemptId)
guard !importAttemptId.isEmpty else {
throw DecodingError.dataCorruptedError(
forKey: .importAttemptId,
in: container,
debugDescription: "importAttemptId must not be empty"
)
}
self.importAttemptId = importAttemptId
}
id = try container.decode(String.self, forKey: .id)
documentId = try container.decode(String.self, forKey: .documentId)
createdAt = try container.decode(Date.self, forKey: .createdAt)
title = try container.decode(String.self, forKey: .title)
content = try container.decode(ShareInboxContent.self, forKey: .content)
target = try container.decodeIfPresent(ShareInboxTarget.self, forKey: .target)
previewRoute = (try? container.decodeIfPresent(String.self, forKey: .previewRoute)) ?? "deferred"
previewText = try container.decodeIfPresent(String.self, forKey: .previewText)
attachments =
try container.decodeIfPresent([ShareInboxAttachment].self, forKey: .attachments) ?? []
result = try container.decodeIfPresent(ShareInboxResult.self, forKey: .result)
lastError = try container.decodeIfPresent(String.self, forKey: .lastError)
}
}
private struct ShareIngestAttachmentSpecPayload: Encodable {
let blob_key: String
let file_name: String
let mime_type: String
let byte_offset: Int
let byte_len: Int
}
private struct ShareIngestRequestPayload: Encodable {
let share_id: String
let import_attempt_id: String
let doc_id: String
let kind: String
let title: String
let text_or_url: String
let secondary_text: String
let tag_ids: [String]
let collection_id: String?
let attachments: [ShareIngestAttachmentSpecPayload]
let client_id: UInt64
let now_ms: Int64
}
private struct ShareIngestOutcomePayload: Decodable {
let already_committed: Bool
let doc_id: String
let inserted_text: String
let blob_keys: [String]
}
/// Zero-CocoaPods App Group ShareExtension inbox coordinator.
/// Consumes `<AppGroup:group.app.affine.pro>/ShareInbox/<id>.json` and
/// `ShareInbox/Attachments/<id>/<fileName>` through a single atomic Rust SQLite transaction
/// (`blobs` + `updates` + `clocks` + `db$docProperties` + `share_ingest_receipts`).
final class ShareExtensionBridge: @unchecked Sendable {
static let appGroupIdentifier = "group.app.affine.pro"
static let inboxDirectoryName = "ShareInbox"
static let attachmentsDirectoryName = "Attachments"
static let invalidDirectoryName = "Invalid"
static let maxShareAttachmentBytes = 64 * 1024 * 1024
/// Cooldown before retrying an unchanged failing manifest within the same foreground stay;
/// `resetFailedBackoff()` clears it immediately on foreground entry or workspace mount change.
static let failureRetryCooldownSec: TimeInterval = 5.0
private let inboxDirectory: URL
private let lock = NSLock()
private var drainInFlight = false
/// Tracks `(manifestPath -> (modDate, failedAt))` so large failing attachments are not tight-looped
/// within the same 5 s window while still recovering automatically after cooldown or foreground re-entry.
private var failedManifestBackoff: [String: (modDate: Date, failedAt: Date)] = [:]
/// Optional test hook overriding the post-commit passive WAL checkpoint step.
var checkpointHook: ((WorkspaceStorageBridge) -> Bool)?
private static func makeEncoder() -> JSONEncoder {
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
return encoder
}
private static func makeDecoder() -> JSONDecoder {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
return decoder
}
/// Computes 44-char padded base64url SHA-256 matching `0.27.5` `blobSync.set` (`import.ts:212`).
static func sha256Base64Url(_ data: Data) -> String {
let digest = SHA256.hash(data: data)
return Data(digest)
.base64EncodedString()
.replacingOccurrences(of: "+", with: "-")
.replacingOccurrences(of: "/", with: "_")
}
init(inboxDirectory: URL? = nil) {
if let inboxDirectory {
self.inboxDirectory = inboxDirectory
} else if let groupUrl = FileManager.default.containerURL(
forSecurityApplicationGroupIdentifier: Self.appGroupIdentifier
) {
self.inboxDirectory = groupUrl.appendingPathComponent(
Self.inboxDirectoryName,
isDirectory: true
)
} else {
self.inboxDirectory = FileManager.default.temporaryDirectory
.appendingPathComponent(Self.inboxDirectoryName, isDirectory: true)
}
}
var attachmentsDirectory: URL {
inboxDirectory.appendingPathComponent(Self.attachmentsDirectoryName, isDirectory: true)
}
var invalidDirectory: URL {
inboxDirectory.appendingPathComponent(Self.invalidDirectoryName, isDirectory: true)
}
/// Clears in-memory failed-manifest backoff (used on foreground entry, workspace mounts, or retry tests).
func resetFailedBackoff() {
lock.lock()
failedManifestBackoff.removeAll()
lock.unlock()
}
/// Resolves an attachment `relativePath` (relative to `ShareInbox/Attachments/`,
/// e.g. `"<item.id>/<fileName>"`) and enforces strict symlink-resolved containment.
func safeAttachmentURL(relativePath: String) -> URL? {
let cleaned = relativePath.trimmingCharacters(in: .whitespacesAndNewlines)
guard
!cleaned.isEmpty,
!cleaned.hasPrefix("/"),
!cleaned.split(separator: "/").contains("..")
else {
return nil
}
let base = attachmentsDirectory.standardizedFileURL
let candidate = base.appendingPathComponent(cleaned).standardizedFileURL
let resolvedBase = base.resolvingSymlinksInPath().standardizedFileURL
let resolvedCandidate = candidate.resolvingSymlinksInPath().standardizedFileURL
guard
candidate.path.hasPrefix(base.path + "/"),
resolvedCandidate.path.hasPrefix(resolvedBase.path + "/")
else {
return nil
}
return candidate
}
private func itemAttachmentsDirectory(itemId: String) -> URL? {
let cleaned = itemId.trimmingCharacters(in: .whitespacesAndNewlines)
guard
!cleaned.isEmpty,
!cleaned.contains("/"),
cleaned != ".",
cleaned != ".."
else {
return nil
}
return attachmentsDirectory.appendingPathComponent(cleaned, isDirectory: true)
}
/// Atomically writes one canonical `ShareInbox/<id>.json` item and optional attachments
/// under `ShareInbox/Attachments/<relativePath>` (`"<item.id>/<fileName>"`).
func stageItem(_ item: ShareInboxItem, attachmentBlobs: [String: Data] = [:]) throws -> URL {
let fm = FileManager.default
try fm.createDirectory(at: inboxDirectory, withIntermediateDirectories: true)
if !attachmentBlobs.isEmpty {
try fm.createDirectory(at: attachmentsDirectory, withIntermediateDirectories: true)
for (relativePath, blob) in attachmentBlobs {
guard let dest = safeAttachmentURL(relativePath: relativePath) else {
continue
}
try fm.createDirectory(
at: dest.deletingLastPathComponent(),
withIntermediateDirectories: true
)
try blob.write(to: dest, options: .atomic)
}
}
let sanitizedId = item.id.replacingOccurrences(of: "/", with: "_")
let target = inboxDirectory.appendingPathComponent("\(sanitizedId).json")
let data = try Self.makeEncoder().encode(item)
try data.write(to: target, options: .atomic)
lock.lock()
failedManifestBackoff.removeValue(forKey: target.path)
lock.unlock()
return target
}
private static func peekSchemaVersion(from data: Data) -> Int? {
guard
let obj = try? JSONSerialization.jsonObject(with: data, options: []),
let dict = obj as? [String: Any]
else {
return nil
}
if let version = dict["schemaVersion"] as? Int {
return version
}
if dict["schemaVersion"] == nil {
return 1
}
return nil
}
private func quarantineManifest(at url: URL) {
let fm = FileManager.default
try? fm.createDirectory(at: invalidDirectory, withIntermediateDirectories: true)
let dest = invalidDirectory.appendingPathComponent(url.lastPathComponent)
try? fm.removeItem(at: dest)
do {
try fm.moveItem(at: url, to: dest)
} catch {
try? fm.removeItem(at: url)
}
}
private func cleanupConsumedItem(manifestUrl: URL, item: ShareInboxItem) {
let fm = FileManager.default
lock.lock()
failedManifestBackoff.removeValue(forKey: manifestUrl.path)
lock.unlock()
try? fm.removeItem(at: manifestUrl)
if let itemAttDir = itemAttachmentsDirectory(itemId: item.id),
fm.fileExists(atPath: itemAttDir.path)
{
try? fm.removeItem(at: itemAttDir)
} else {
for att in item.attachments {
if let attUrl = safeAttachmentURL(relativePath: att.relativePath) {
try? fm.removeItem(at: attUrl)
}
}
}
}
/// Drains pending `ShareInbox` items on a background utility queue so file I/O (up to 64 MiB)
/// and SQLite `BEGIN IMMEDIATE ... COMMIT` + WAL checkpoint never block the UI main thread.
func drainInBackground(
workspace: WorkspaceStorageBridge?,
mountedWorkspaces: [String: WorkspaceStorageBridge] = [:],
onMainThreadCompletion: @escaping @MainActor @Sendable (Int) -> Void
) {
guard workspace != nil || !mountedWorkspaces.isEmpty else {
Task { @MainActor in onMainThreadCompletion(0) }
return
}
let bridge = self
Task.detached(priority: .utility) {
let count = bridge.drainAndIngestIntoHost(
nil,
workspace: workspace,
resolveWorkspace: mountedWorkspaces.isEmpty ? nil : { wsId in mountedWorkspaces[wsId] }
)
await onMainThreadCompletion(count)
}
}
/// Atomically ingests pending `ShareInbox/<id>.json` items into their target local `workspace`
/// SQLite (`blobs` + `updates` + `clocks` + `db$docProperties` + `share_ingest_receipts`).
@discardableResult
func drainAndIngestIntoHost(
_ host: OpaquePointer?,
workspace: WorkspaceStorageBridge?,
resolveWorkspace: ((String) -> WorkspaceStorageBridge?)? = nil,
docId overrideDocId: String? = nil
) -> Int {
guard workspace != nil || resolveWorkspace != nil else {
return 0
}
lock.lock()
if drainInFlight {
lock.unlock()
return 0
}
drainInFlight = true
lock.unlock()
defer {
lock.lock()
drainInFlight = false
lock.unlock()
}
let fm = FileManager.default
let decoder = Self.makeDecoder()
guard let urls = try? fm.contentsOfDirectory(
at: inboxDirectory,
includingPropertiesForKeys: [.contentModificationDateKey],
options: [.skipsHiddenFiles]
) else {
return 0
}
let manifestUrls = urls
.filter { $0.pathExtension.lowercased() == "json" }
.sorted { $0.lastPathComponent < $1.lastPathComponent }
var decodedEntries: [(url: URL, modDate: Date?, item: ShareInboxItem)] = []
for url in manifestUrls {
let modDate = (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?
.contentModificationDate
let now = Date()
lock.lock()
let skipUnchangedFailure: Bool
if let modDate, let record = failedManifestBackoff[url.path], record.modDate == modDate {
skipUnchangedFailure = now.timeIntervalSince(record.failedAt) < Self.failureRetryCooldownSec
} else {
skipUnchangedFailure = false
}
lock.unlock()
if skipUnchangedFailure {
continue
}
guard let data = try? Data(contentsOf: url) else {
continue
}
guard let schemaVersion = Self.peekSchemaVersion(from: data) else {
quarantineManifest(at: url)
continue
}
if schemaVersion > ShareInboxItem.currentSchemaVersion {
continue
}
guard let item = try? decoder.decode(ShareInboxItem.self, from: data) else {
quarantineManifest(at: url)
continue
}
decodedEntries.append((url, modDate, item))
}
decodedEntries.sort { $0.item.createdAt < $1.item.createdAt }
var newlyIngested = 0
for entry in decodedEntries {
let item = entry.item
if item.result != nil {
cleanupConsumedItem(manifestUrl: entry.url, item: item)
continue
}
let targetWorkspace: WorkspaceStorageBridge?
if let target = item.target {
let flavour = target.workspaceFlavour.trimmingCharacters(in: .whitespacesAndNewlines)
if !flavour.isEmpty && flavour != "local" {
continue
}
let requestedId = target.workspaceId.trimmingCharacters(in: .whitespacesAndNewlines)
if requestedId.isEmpty {
targetWorkspace = workspace
} else if let resolved = resolveWorkspace?(requestedId) {
targetWorkspace = resolved
} else if let workspace, workspace.spaceId == requestedId {
targetWorkspace = workspace
} else {
continue
}
} else {
targetWorkspace = workspace
}
guard let targetWorkspace else {
continue
}
let targetDocId = (overrideDocId?.trimmingCharacters(in: .whitespacesAndNewlines)).flatMap {
$0.isEmpty ? nil : $0
} ?? item.documentId
var blobBuffer = Data()
var attachmentSpecs: [ShareIngestAttachmentSpecPayload] = []
var attachmentsValid = true
for att in item.attachments {
guard
!att.fileName.isEmpty,
att.fileName == (att.fileName as NSString).lastPathComponent,
att.fileName != ".",
att.fileName != "..",
att.relativePath == "\(item.id)/\(att.fileName)",
let attUrl = safeAttachmentURL(relativePath: att.relativePath),
let values = try? attUrl.resourceValues(
forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey]
),
values.isSymbolicLink != true,
values.isRegularFile == true,
let fileSize = values.fileSize,
fileSize > 0,
fileSize <= Self.maxShareAttachmentBytes,
blobBuffer.count + fileSize <= Self.maxShareAttachmentBytes,
let bytes = try? Data(contentsOf: attUrl),
!bytes.isEmpty,
bytes.count <= Self.maxShareAttachmentBytes,
blobBuffer.count + bytes.count <= Self.maxShareAttachmentBytes
else {
attachmentsValid = false
break
}
let offset = blobBuffer.count
blobBuffer.append(bytes)
let blobKey = Self.sha256Base64Url(bytes)
attachmentSpecs.append(
ShareIngestAttachmentSpecPayload(
blob_key: blobKey,
file_name: att.fileName,
mime_type: att.mimeType,
byte_offset: offset,
byte_len: bytes.count
)
)
}
if !attachmentsValid {
quarantineManifest(at: entry.url)
continue
}
let textOrUrl: String
let secondaryText: String
switch item.content.kind {
case .url:
let rawUrl = (item.content.url ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
guard rawUrl.hasPrefix("https://") || rawUrl.hasPrefix("http://") else {
quarantineManifest(at: entry.url)
continue
}
textOrUrl = rawUrl
secondaryText = (item.content.text ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
case .text:
let rawText = (item.content.text ?? item.previewText ?? "").trimmingCharacters(
in: .whitespacesAndNewlines
)
guard !rawText.isEmpty else {
quarantineManifest(at: entry.url)
continue
}
textOrUrl = rawText
secondaryText = (item.content.url ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
case .image, .pdf:
guard !attachmentSpecs.isEmpty else {
quarantineManifest(at: entry.url)
continue
}
textOrUrl = (item.content.url ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
secondaryText = (item.content.text ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
}
let request = ShareIngestRequestPayload(
share_id: item.id,
import_attempt_id: item.importAttemptId,
doc_id: targetDocId,
kind: item.content.kind.rawValue,
title: item.title,
text_or_url: textOrUrl,
secondary_text: secondaryText,
tag_ids: item.target?.tagIds ?? [],
collection_id: item.target?.collectionId,
attachments: attachmentSpecs,
client_id: UInt64(UInt32.random(in: 1...UInt32.max)),
now_ms: Int64(Date().timeIntervalSince1970 * 1000.0)
)
guard
let reqData = try? JSONEncoder().encode(request),
let reqJson = String(data: reqData, encoding: .utf8),
let outcomeJson = targetWorkspace.ingestShareItem(
requestJson: reqJson,
blobBytes: blobBuffer
),
let outcomeData = outcomeJson.data(using: .utf8),
let outcome = try? JSONDecoder().decode(ShareIngestOutcomePayload.self, from: outcomeData)
else {
if let modDate = entry.modDate {
lock.lock()
failedManifestBackoff[entry.url.path] = (modDate: modDate, failedAt: Date())
lock.unlock()
}
continue
}
if !outcome.already_committed {
newlyIngested += 1
}
let checkpointOk = checkpointHook?(targetWorkspace) ?? targetWorkspace.checkpointPassive()
guard checkpointOk else {
continue
}
cleanupConsumedItem(manifestUrl: entry.url, item: item)
}
if let host, newlyIngested > 0 {
affine_ios_host_request_frame(host)
}
return newlyIngested
}
}
@@ -8,7 +8,12 @@ enum WorkspaceStorageBridgeError: Error, Equatable {
}
/// Thin Swift wrapper over the in-place 0.27.5 SQLite WAL C ABI in `affine_mobile_host.h`.
final class WorkspaceStorageBridge {
/// Thread-safe: all access to `handle` (including `close()`) is serialized under `lock`.
final class WorkspaceStorageBridge: @unchecked Sendable {
let spaceType: String
let peer: String
let spaceId: String
private let lock = NSLock()
private var handle: OpaquePointer?
init(
@@ -62,6 +67,9 @@ final class WorkspaceStorageBridge {
guard let opened else {
throw WorkspaceStorageBridgeError.openFailed
}
self.spaceType = spaceType
self.peer = peer
self.spaceId = spaceId
self.handle = opened
}
@@ -70,19 +78,25 @@ final class WorkspaceStorageBridge {
}
func close() {
if let handle {
affine_ios_workspace_close(handle)
lock.lock()
defer { lock.unlock() }
if let current = handle {
self.handle = nil
affine_ios_workspace_close(current)
}
}
func readDoc(docId: String) -> Data? {
lock.lock()
defer { lock.unlock() }
guard let handle else { return nil }
let buffer = docId.withCString { affine_ios_workspace_read_doc(handle, $0) }
return takeBytes(buffer)
}
func readPageSnapshotJson(docId: String, clientId: UInt64) -> String? {
lock.lock()
defer { lock.unlock() }
guard let handle else { return nil }
let ptr = docId.withCString { affine_ios_workspace_read_page_snapshot_json(handle, $0, clientId) }
guard let ptr else { return nil }
@@ -99,6 +113,8 @@ final class WorkspaceStorageBridge {
clientId: UInt64,
nowMs: Int64
) -> Data? {
lock.lock()
defer { lock.unlock() }
guard let handle else { return nil }
let buffer = docId.withCString { cDoc in
blockId.withCString { cBlock in
@@ -120,6 +136,8 @@ final class WorkspaceStorageBridge {
}
func exportPendingDiff(docId: String, remoteStateVector: Data? = nil) -> Data? {
lock.lock()
defer { lock.unlock() }
guard let handle else { return nil }
let buffer: AffineIosByteBuffer = docId.withCString { cDoc in
if let remoteStateVector, !remoteStateVector.isEmpty {
@@ -140,6 +158,8 @@ final class WorkspaceStorageBridge {
remoteClockMs: Int64,
localNowMs: Int64
) -> Data? {
lock.lock()
defer { lock.unlock() }
guard let handle else { return nil }
let buffer: AffineIosByteBuffer = docId.withCString { cDoc in
peer.withCString { cPeer in
@@ -161,15 +181,45 @@ final class WorkspaceStorageBridge {
}
func checkpointPassive() -> Bool {
lock.lock()
defer { lock.unlock() }
guard let handle else { return false }
return affine_ios_workspace_checkpoint_passive(handle)
}
func checkpoint() -> Bool {
lock.lock()
defer { lock.unlock() }
guard let handle else { return false }
return affine_ios_workspace_checkpoint(handle)
}
func readBlob(key: String) -> Data? {
lock.lock()
defer { lock.unlock() }
guard let handle else { return nil }
let buffer = key.withCString { affine_ios_workspace_read_blob(handle, $0) }
return takeBytes(buffer)
}
func ingestShareItem(requestJson: String, blobBytes: Data) -> String? {
lock.lock()
defer { lock.unlock() }
guard let handle else { return nil }
let ptr: UnsafeMutablePointer<CChar>? = requestJson.withCString { cReq in
if blobBytes.isEmpty {
return affine_ios_workspace_ingest_share_item(handle, cReq, nil, 0)
}
return blobBytes.withUnsafeBytes { raw in
let base = raw.bindMemory(to: UInt8.self).baseAddress
return affine_ios_workspace_ingest_share_item(handle, cReq, base, blobBytes.count)
}
}
guard let ptr else { return nil }
defer { affine_ios_string_free(ptr) }
return String(cString: ptr)
}
private func takeBytes(_ buffer: AffineIosByteBuffer) -> Data? {
defer { affine_ios_bytes_free(buffer) }
guard let ptr = buffer.ptr, buffer.len > 0 else {
@@ -284,6 +284,10 @@ bool affine_ios_host_wants_code_input(const AffineIosHost *host);
typedef void (*AffineTextInputChangedCallback)(uint8_t change_kind, void *user_data);
bool affine_ios_host_is_dark_theme(const AffineIosHost *host);
void affine_ios_host_set_dark_theme(AffineIosHost *host, bool dark);
void *affine_ios_host_metal_layer(const AffineIosHost *host);
size_t affine_ios_host_utf16_len(const AffineIosHost *host);
@@ -803,6 +807,64 @@ char *affine_ios_host_doc_text_between_tokens(
uint64_t start_endpoint_token,
uint64_t end_endpoint_token);
/* Zero-CocoaPods iOS Native Islands (Atomic SQLite ShareExtension, AffinePaywall, Onboarding/SignIn). */
char *affine_ios_workspace_ingest_share_item(
const AffineIosWorkspace *ws,
const char *request_json,
const uint8_t *blob_bytes_ptr,
size_t blob_bytes_len);
AffineIosByteBuffer affine_ios_workspace_read_blob(
const AffineIosWorkspace *ws,
const char *blob_key);
bool affine_ios_island_paywall_set_products_json(
AffineIosHost *host,
const char *products_json);
bool affine_ios_island_paywall_begin_purchase(
AffineIosHost *host,
const char *product_id);
bool affine_ios_island_paywall_complete_jws(
AffineIosHost *host,
const char *product_id,
const char *transaction_id,
const char *jws_representation);
bool affine_ios_island_paywall_finish_non_verified(
AffineIosHost *host,
uint8_t outcome_kind,
const char *reason);
bool affine_ios_island_paywall_clear_entitlements(AffineIosHost *host);
char *affine_ios_island_paywall_state_json(const AffineIosHost *host);
bool affine_ios_island_onboarding_begin_oauth(
AffineIosHost *host,
const char *csrf_state);
bool affine_ios_island_onboarding_complete_apple(
AffineIosHost *host,
const char *user_identifier,
const char *identity_token_jws);
bool affine_ios_island_onboarding_complete_oauth(
AffineIosHost *host,
const char *code,
const char *state);
bool affine_ios_island_onboarding_confirm_session(
AffineIosHost *host,
const char *subject);
bool affine_ios_island_onboarding_fail_session(
AffineIosHost *host,
const char *reason);
char *affine_ios_island_onboarding_state_json(const AffineIosHost *host);
#ifdef __cplusplus
}
#endif
@@ -57,6 +57,8 @@ swiftc -emit-executable \
-framework CoreFoundation \
-framework Foundation \
-framework UniformTypeIdentifiers \
-framework StoreKit \
-framework AuthenticationServices \
-o "$APP_DIR/AffineIosHost" \
"$IOS_HOST_DIR"/Sources/*.swift
@@ -233,6 +233,53 @@ impl IosEditorRuntime {
self.dispatcher.drain_ready()
}
pub(crate) fn is_dark_theme(&self) -> bool {
self.app
.update(|cx| {
self.view.read_with(cx, |view, _| {
view.theme() == playground::PlaygroundTheme::Dark
})
})
.unwrap_or(false)
}
pub(crate) fn set_dark_theme(&mut self, dark: bool) {
let target = if dark {
playground::PlaygroundTheme::Dark
} else {
playground::PlaygroundTheme::Light
};
let _ = self.app.update(|cx| {
let _ = self.view.update(cx, |view, _window, cx| {
if view.theme() != target {
view.set_theme(target, cx);
}
});
});
self.request_frame();
}
pub(crate) fn clear_color_rgba(&self) -> u32 {
let bg = self
.app
.update(|cx| {
self.view
.read_with(cx, |view, _| view.theme().palette().background)
})
.ok();
match bg {
Some(hsla) => {
let rgba: ui::Rgba = hsla.into();
let r = (rgba.r.clamp(0.0, 1.0) * 255.0).round() as u32;
let g = (rgba.g.clamp(0.0, 1.0) * 255.0).round() as u32;
let b = (rgba.b.clamp(0.0, 1.0) * 255.0).round() as u32;
let a = (rgba.a.clamp(0.0, 1.0) * 255.0).round() as u32;
(r << 24) | (g << 16) | (b << 8) | a
}
None => IosHostState::DEFAULT_CLEAR_COLOR_RGBA,
}
}
pub(crate) fn render_frame(&mut self, timestamp_sec: f64) -> u32 {
#[cfg(not(target_os = "ios"))]
let _ = self.dispatcher.drain_ready();
@@ -244,18 +291,7 @@ impl IosEditorRuntime {
if timestamp_sec.is_finite() {
self.last_frame_timestamp_sec = timestamp_sec;
}
let is_dark = self
.app
.update(|cx| {
self.view
.read_with(cx, |v, _| v.theme() == playground::PlaygroundTheme::Dark)
})
.unwrap_or(false);
if is_dark {
0x1414_14FF
} else {
IosHostState::DEFAULT_CLEAR_COLOR_RGBA
}
self.clear_color_rgba()
}
pub(crate) fn set_form_factor(&mut self, form_factor: FormFactor) {
+3 -1
View File
@@ -27,11 +27,12 @@ pub struct AffineIosHost {
pub(crate) haptics_user_data: *mut c_void,
pub(crate) pdf_provider: Option<super::ffi_s3::AffinePdfProvider>,
pub(crate) text_provider: Option<super::ffi_text::AffineTextProvider>,
pub(crate) islands: super::native_islands::IosNativeIslandsState,
}
/// Opaque C-ABI handle matching `typedef struct AffineIosWorkspace AffineIosWorkspace`.
pub struct AffineIosWorkspace {
handle: IosWorkspaceHandle,
pub(crate) handle: IosWorkspaceHandle,
}
/// Owned byte buffer returned across the C ABI. Free with `affine_ios_bytes_free`.
@@ -120,6 +121,7 @@ pub extern "C" fn affine_ios_host_create(
haptics_user_data: core::ptr::null_mut(),
pdf_provider: None,
text_provider: None,
islands: super::native_islands::IosNativeIslandsState::default(),
});
Box::into_raw(host)
}
@@ -35,6 +35,37 @@ unsafe fn c_str_opt<'a>(ptr: *const c_char) -> Option<&'a str> {
unsafe { CStr::from_ptr(ptr) }.to_str().ok()
}
/// Returns whether the live `PlaygroundView` is currently rendering in dark theme.
///
/// # Safety
/// `host` must be null or a live pointer returned by `affine_ios_host_create`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn affine_ios_host_is_dark_theme(host: *const AffineIosHost) -> bool {
let Some(host) = (unsafe { host.as_ref() }) else {
return false;
};
host.editor
.borrow()
.as_ref()
.is_some_and(IosEditorRuntime::is_dark_theme)
}
/// Switches the live `PlaygroundView` between light (`false`) and dark (`true`) themes.
///
/// # Safety
/// `host` must be null or a live pointer returned by `affine_ios_host_create`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn affine_ios_host_set_dark_theme(host: *mut AffineIosHost, dark: bool) {
let Some(host) = (unsafe { host.as_mut() }) else {
return;
};
if let Some(editor) = host.editor.borrow_mut().as_mut() {
editor.set_dark_theme(dark);
} else {
host.state.request_frame();
}
}
/// Returns the `CAMetalLayer *` owned by `MetalRenderer` on iOS, or null on non-iOS hosts.
///
/// # Safety
@@ -0,0 +1,322 @@
#![allow(unsafe_code)]
//! C-ABI narrow-bridge exports for iOS native islands
//! (Atomic SQLite `ShareExtension`, `AffinePaywall`, `Onboarding + NativeSignIn`).
use std::ffi::{CStr, CString, c_char};
use super::{
ffi::{AffineIosByteBuffer, AffineIosHost, AffineIosWorkspace},
native_islands::PaywallProduct,
share_ingest::ShareIngestRequest,
};
unsafe fn c_str_opt<'a>(ptr: *const c_char) -> Option<&'a str> {
if ptr.is_null() {
return None;
}
unsafe { CStr::from_ptr(ptr) }.to_str().ok()
}
fn into_c_string(value: String) -> *mut c_char {
CString::new(value)
.map(CString::into_raw)
.unwrap_or(core::ptr::null_mut())
}
/// Atomically ingest one ShareExtension item (`blobs` + `updates` + `clocks` +
/// `share_ingest_receipts`) inside a single SQLite `BEGIN IMMEDIATE ... COMMIT` transaction.
///
/// Returns a JSON-encoded `ShareIngestOutcome` (caller frees via `affine_ios_string_free`),
/// or NULL on validation/database failure.
///
/// # Safety
/// `ws` must be a live workspace handle; `request_json` must be a valid NUL-terminated UTF-8 string;
/// `blob_bytes_ptr` must be valid for `blob_bytes_len` reads when `blob_bytes_len > 0`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn affine_ios_workspace_ingest_share_item(
ws: *const AffineIosWorkspace,
request_json: *const c_char,
blob_bytes_ptr: *const u8,
blob_bytes_len: usize,
) -> *mut c_char {
let (Some(ws), Some(raw_json)) = (unsafe { ws.as_ref() }, unsafe { c_str_opt(request_json) })
else {
return core::ptr::null_mut();
};
let Ok(req) = serde_json::from_str::<ShareIngestRequest>(raw_json) else {
return core::ptr::null_mut();
};
let blob_bytes: &[u8] = if blob_bytes_ptr.is_null() || blob_bytes_len == 0 {
&[]
} else {
// SAFETY: Caller guarantees `blob_bytes_ptr` points to `blob_bytes_len` readable bytes.
unsafe { core::slice::from_raw_parts(blob_bytes_ptr, blob_bytes_len) }
};
match ws.handle.ingest_share_item(&req, blob_bytes) {
Ok(outcome) => serde_json::to_string(&outcome)
.map(into_c_string)
.unwrap_or(core::ptr::null_mut()),
Err(_) => core::ptr::null_mut(),
}
}
/// Read a non-deleted blob from the workspace SQLite `blobs` table.
///
/// # Safety
/// `ws` must be a live workspace handle; `blob_key` must be a valid NUL-terminated UTF-8 string.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn affine_ios_workspace_read_blob(
ws: *const AffineIosWorkspace,
blob_key: *const c_char,
) -> AffineIosByteBuffer {
let (Some(ws), Some(key)) = (unsafe { ws.as_ref() }, unsafe { c_str_opt(blob_key) }) else {
return AffineIosByteBuffer::empty();
};
ws.handle
.read_blob(key)
.ok()
.flatten()
.map(AffineIosByteBuffer::from_vec)
.unwrap_or_else(AffineIosByteBuffer::empty)
}
/// Register StoreKit 2 products JSON array (`[{product_id, display_name, display_price}]`).
///
/// # Safety
/// `host` must be null or a live pointer; `products_json` must be null or a valid C string.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn affine_ios_island_paywall_set_products_json(
host: *mut AffineIosHost,
products_json: *const c_char,
) -> bool {
let Some(host) = (unsafe { host.as_mut() }) else {
return false;
};
let Some(raw) = (unsafe { c_str_opt(products_json) }) else {
return false;
};
let Ok(products) = serde_json::from_str::<Vec<PaywallProduct>>(raw) else {
return false;
};
host.islands.paywall.begin_load_products();
host.islands.paywall.set_products(products).is_ok()
}
/// Transition StoreKit 2 paywall into `Purchasing` for an allowlisted `product_id`.
///
/// # Safety
/// `host` must be null or a live pointer; `product_id` must be null or a valid C string.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn affine_ios_island_paywall_begin_purchase(
host: *mut AffineIosHost,
product_id: *const c_char,
) -> bool {
let Some(host) = (unsafe { host.as_mut() }) else {
return false;
};
let Some(pid) = (unsafe { c_str_opt(product_id) }) else {
return false;
};
host.islands.paywall.begin_purchase(pid).is_ok()
}
/// Complete a verified StoreKit 2 purchase with its `product_id`, `transaction_id`, and compact JWS string.
///
/// # Safety
/// `host` and string pointers must be null or valid C strings.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn affine_ios_island_paywall_complete_jws(
host: *mut AffineIosHost,
product_id: *const c_char,
transaction_id: *const c_char,
jws_representation: *const c_char,
) -> bool {
let Some(host) = (unsafe { host.as_mut() }) else {
return false;
};
let (Some(pid), Some(tx_id), Some(jws)) = (
unsafe { c_str_opt(product_id) },
unsafe { c_str_opt(transaction_id) },
unsafe { c_str_opt(jws_representation) },
) else {
return false;
};
host.islands
.paywall
.complete_verified_transaction(pid, tx_id, jws)
.is_ok()
}
/// Update non-verified StoreKit 2 purchase outcome (`0 = pending`, `1 = cancelled`, `2 = failed`).
///
/// # Safety
/// `host` must be null or a live pointer; `reason` must be null or a valid C string.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn affine_ios_island_paywall_finish_non_verified(
host: *mut AffineIosHost,
outcome_kind: u8,
reason: *const c_char,
) -> bool {
let Some(host) = (unsafe { host.as_mut() }) else {
return false;
};
match outcome_kind {
0 => host.islands.paywall.mark_pending(),
1 => host.islands.paywall.mark_cancelled(),
_ => {
let msg = unsafe { c_str_opt(reason) }.unwrap_or("StoreKit purchase failed");
host.islands.paywall.mark_failed(msg);
}
}
true
}
/// Clear all active StoreKit 2 entitlements (on expiration, refund, or revocation).
///
/// # Safety
/// `host` must be null or a live pointer returned by `affine_ios_host_create`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn affine_ios_island_paywall_clear_entitlements(
host: *mut AffineIosHost,
) -> bool {
let Some(host) = (unsafe { host.as_mut() }) else {
return false;
};
host.islands.paywall.clear_entitlement();
true
}
/// Serialize current `PaywallStateMachine` as JSON (caller frees via `affine_ios_string_free`).
///
/// # Safety
/// `host` must be null or a live pointer returned by `affine_ios_host_create`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn affine_ios_island_paywall_state_json(
host: *const AffineIosHost,
) -> *mut c_char {
let Some(host) = (unsafe { host.as_ref() }) else {
return core::ptr::null_mut();
};
let json = serde_json::to_string(&host.islands.paywall).unwrap_or_else(|_| "{}".to_string());
into_c_string(json)
}
/// Begin OAuth sign-in during onboarding with an expected CSRF `state` token.
///
/// # Safety
/// `host` must be null or a live pointer; `csrf_state` must be null or a valid C string.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn affine_ios_island_onboarding_begin_oauth(
host: *mut AffineIosHost,
csrf_state: *const c_char,
) -> bool {
let Some(host) = (unsafe { host.as_mut() }) else {
return false;
};
let Some(state) = (unsafe { c_str_opt(csrf_state) }) else {
return false;
};
host.islands.onboarding.advance_to_sign_in();
host.islands.onboarding.begin_oauth(state).is_ok()
}
/// Complete Sign in with Apple (`ASAuthorizationAppleIDCredential`) with user ID + identity token JWS.
///
/// # Safety
/// `host` and string pointers must be null or valid C strings.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn affine_ios_island_onboarding_complete_apple(
host: *mut AffineIosHost,
user_identifier: *const c_char,
identity_token_jws: *const c_char,
) -> bool {
let Some(host) = (unsafe { host.as_mut() }) else {
return false;
};
let (Some(uid), Some(jws)) = (unsafe { c_str_opt(user_identifier) }, unsafe {
c_str_opt(identity_token_jws)
}) else {
return false;
};
host.islands
.onboarding
.receive_apple_credential(uid, jws)
.is_ok()
}
/// Record OAuth callback (`affine://auth/callback?code=...&state=...`) with CSRF check (`PendingExchange`).
///
/// # Safety
/// `host` and string pointers must be null or valid C strings.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn affine_ios_island_onboarding_complete_oauth(
host: *mut AffineIosHost,
code: *const c_char,
state: *const c_char,
) -> bool {
let Some(host) = (unsafe { host.as_mut() }) else {
return false;
};
let (Some(code), Some(state)) = (unsafe { c_str_opt(code) }, unsafe { c_str_opt(state) })
else {
return false;
};
host.islands
.onboarding
.receive_oauth_callback(code, state)
.is_ok()
}
/// Confirm server session exchange with the verified user `subject` (`PendingExchange -> Completed`).
///
/// # Safety
/// `host` and `subject` must be null or valid C strings.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn affine_ios_island_onboarding_confirm_session(
host: *mut AffineIosHost,
subject: *const c_char,
) -> bool {
let Some(host) = (unsafe { host.as_mut() }) else {
return false;
};
let Some(subject) = (unsafe { c_str_opt(subject) }) else {
return false;
};
host.islands
.onboarding
.confirm_session_exchange(subject)
.is_ok()
}
/// Mark a pending server session exchange as failed so the user returns to `SignInChoice`.
///
/// # Safety
/// `host` and `reason` must be null or valid C strings.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn affine_ios_island_onboarding_fail_session(
host: *mut AffineIosHost,
reason: *const c_char,
) -> bool {
let Some(host) = (unsafe { host.as_mut() }) else {
return false;
};
let msg = unsafe { c_str_opt(reason) }.unwrap_or("session exchange failed");
host.islands.onboarding.fail_session_exchange(msg);
true
}
/// Serialize current `OnboardingSignInState` as JSON (caller frees via `affine_ios_string_free`).
///
/// # Safety
/// `host` must be null or a live pointer returned by `affine_ios_host_create`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn affine_ios_island_onboarding_state_json(
host: *const AffineIosHost,
) -> *mut c_char {
let Some(host) = (unsafe { host.as_ref() }) else {
return core::ptr::null_mut();
};
let json = serde_json::to_string(&host.islands.onboarding).unwrap_or_else(|_| "{}".to_string());
into_c_string(json)
}
+3
View File
@@ -18,14 +18,17 @@ pub(crate) mod editor_runtime;
pub mod ffi;
pub mod ffi_doc_positions;
pub mod ffi_editor;
pub mod ffi_islands;
pub mod ffi_s3;
pub mod ffi_selection;
pub mod ffi_text;
pub mod haptics;
pub mod keyboard_insets;
pub mod legacy_storage;
pub mod native_islands;
pub mod pdf;
pub mod selection;
pub mod share_ingest;
pub mod text_layout;
pub mod workspace_store;
@@ -0,0 +1,437 @@
//! Zero-CocoaPods iOS native-island narrow state machines:
//! 1. `AffinePaywall`: StoreKit 2 product catalog, purchase state machine, and JWS envelope check.
//! 2. `OnboardingSignIn`: First-launch onboarding + Sign in with Apple / OAuth CSRF narrow bridge,
//! explicitly separating callback/credential receipt (`PendingExchange`) from server-verified
//! session establishment (`Completed`).
//! (ShareExtension ingest runs atomically against SQLite in `crate::share_ingest`.)
use serde::{Deserialize, Serialize};
pub use crate::share_ingest::IOS_APP_GROUP_ID;
/// StoreKit 2 paywall narrow bridge state.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PaywallPhase {
Idle,
LoadingProducts,
Ready,
Purchasing,
Verified,
Pending,
Cancelled,
Failed,
}
/// StoreKit 2 product descriptor bridged from Swift `Product`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PaywallProduct {
pub product_id: String,
pub display_name: String,
pub display_price: String,
}
/// StoreKit 2 paywall state machine + JWS transaction verifier.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaywallStateMachine {
pub phase: PaywallPhase,
pub products: Vec<PaywallProduct>,
pub active_product_id: Option<String>,
pub verified_transaction_id: Option<String>,
pub last_error: Option<String>,
}
impl Default for PaywallStateMachine {
fn default() -> Self {
Self {
phase: PaywallPhase::Idle,
products: Vec::new(),
active_product_id: None,
verified_transaction_id: None,
last_error: None,
}
}
}
impl PaywallStateMachine {
/// Exact `0.27.5` App Store Connect product allowlist (`PricingConfiguration.swift`).
pub fn is_known_product_id(product_id: &str) -> bool {
matches!(
product_id,
"app.affine.pro.Monthly" | "app.affine.pro.Annual" | "app.affine.pro.ai.Annual"
)
}
/// Validates a compact 3-part JWS string (`header.payload.signature`) with non-empty segments.
pub fn is_valid_jws_envelope(jws: &str) -> bool {
let mut parts = jws.split('.');
let (Some(h), Some(p), Some(s), None) =
(parts.next(), parts.next(), parts.next(), parts.next())
else {
return false;
};
let valid_seg = |seg: &str| {
!seg.is_empty()
&& seg
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
};
valid_seg(h) && valid_seg(p) && valid_seg(s)
}
pub fn begin_load_products(&mut self) {
self.phase = PaywallPhase::LoadingProducts;
self.last_error = None;
}
pub fn set_products(&mut self, products: Vec<PaywallProduct>) -> Result<(), &'static str> {
let filtered: Vec<PaywallProduct> = products
.into_iter()
.filter(|p| Self::is_known_product_id(&p.product_id))
.collect();
if filtered.is_empty() {
self.phase = PaywallPhase::Failed;
self.active_product_id = None;
self.verified_transaction_id = None;
self.last_error = Some("no allowlisted StoreKit products".to_string());
return Err("no allowlisted StoreKit products");
}
self.products = filtered;
if self.phase != PaywallPhase::Verified {
self.phase = PaywallPhase::Ready;
}
self.last_error = None;
Ok(())
}
pub fn begin_purchase(&mut self, product_id: &str) -> Result<(), &'static str> {
if !Self::is_known_product_id(product_id) {
return Err("unknown StoreKit product id");
}
self.active_product_id = Some(product_id.to_string());
self.phase = PaywallPhase::Purchasing;
self.last_error = None;
Ok(())
}
pub fn complete_verified_transaction(
&mut self,
product_id: &str,
transaction_id: &str,
jws_representation: &str,
) -> Result<(), &'static str> {
if !Self::is_known_product_id(product_id) {
self.mark_failed("unknown StoreKit product id");
return Err("unknown StoreKit product id");
}
if transaction_id.trim().is_empty() {
self.mark_failed("empty transaction id");
return Err("empty transaction id");
}
if !Self::is_valid_jws_envelope(jws_representation) {
self.mark_failed("invalid JWS receipt envelope");
return Err("invalid JWS receipt envelope");
}
self.active_product_id = Some(product_id.to_string());
self.verified_transaction_id = Some(transaction_id.to_string());
self.phase = PaywallPhase::Verified;
self.last_error = None;
Ok(())
}
pub fn mark_pending(&mut self) {
self.verified_transaction_id = None;
self.phase = PaywallPhase::Pending;
}
pub fn mark_cancelled(&mut self) {
self.verified_transaction_id = None;
self.active_product_id = None;
self.phase = PaywallPhase::Cancelled;
}
pub fn mark_failed(&mut self, reason: &str) {
self.verified_transaction_id = None;
self.active_product_id = None;
self.phase = PaywallPhase::Failed;
self.last_error = Some(reason.to_string());
}
/// Clear all active entitlements (used when StoreKit 2 `currentEntitlements` is empty,
/// when cache decode fails, or when a verified transaction update reports revocation/expiration).
pub fn clear_entitlement(&mut self) {
self.verified_transaction_id = None;
self.active_product_id = None;
self.last_error = None;
self.phase = if self.products.is_empty() {
PaywallPhase::Idle
} else {
PaywallPhase::Ready
};
}
}
/// Onboarding + Native Sign-In (`ASAuthorizationController` / OAuth) state machine.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OnboardingStage {
Welcome,
SignInChoice,
Authenticating,
PendingExchange,
Completed,
Skipped,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OnboardingSignInState {
pub stage: OnboardingStage,
pub expected_oauth_state: Option<String>,
pub authenticated_provider: Option<String>,
/// One-time OAuth authorization code or Apple credential awaiting server session exchange.
pub pending_credential: Option<String>,
/// Server-confirmed user subject, populated ONLY after `confirm_session_exchange` succeeds.
pub authenticated_subject: Option<String>,
pub last_error: Option<String>,
}
impl Default for OnboardingSignInState {
fn default() -> Self {
Self {
stage: OnboardingStage::Welcome,
expected_oauth_state: None,
authenticated_provider: None,
pending_credential: None,
authenticated_subject: None,
last_error: None,
}
}
}
impl OnboardingSignInState {
pub fn advance_to_sign_in(&mut self) {
self.stage = OnboardingStage::SignInChoice;
self.pending_credential = None;
self.last_error = None;
}
pub fn skip_sign_in(&mut self) {
self.stage = OnboardingStage::Skipped;
self.expected_oauth_state = None;
self.pending_credential = None;
self.authenticated_subject = None;
self.last_error = None;
}
pub fn begin_oauth(&mut self, csrf_state: &str) -> Result<(), &'static str> {
if csrf_state.trim().len() < 8 {
return Err("oauth state token too short");
}
self.expected_oauth_state = Some(csrf_state.to_string());
self.pending_credential = None;
self.authenticated_subject = None;
self.stage = OnboardingStage::Authenticating;
self.last_error = None;
Ok(())
}
/// Record a verified local Apple Sign-In credential and enter `PendingExchange` until the
/// AFFiNE server confirms the session subject.
pub fn receive_apple_credential(
&mut self,
user_identifier: &str,
identity_token_jws: &str,
) -> Result<(), &'static str> {
if user_identifier.trim().is_empty() {
self.last_error = Some("empty apple user identifier".to_string());
return Err("empty apple user identifier");
}
if !PaywallStateMachine::is_valid_jws_envelope(identity_token_jws) {
self.last_error = Some("invalid apple identity token JWS".to_string());
return Err("invalid apple identity token JWS");
}
self.authenticated_provider = Some("apple".to_string());
self.pending_credential = Some(user_identifier.to_string());
self.authenticated_subject = None;
self.expected_oauth_state = None;
self.stage = OnboardingStage::PendingExchange;
self.last_error = None;
Ok(())
}
/// Validate CSRF `state` + non-empty authorization `code` and enter `PendingExchange`
/// without storing the one-time authorization code as `authenticated_subject`.
pub fn receive_oauth_callback(&mut self, code: &str, state: &str) -> Result<(), &'static str> {
let Some(expected) = self.expected_oauth_state.as_deref() else {
return Err("no pending oauth state");
};
if state != expected {
self.last_error = Some("oauth state mismatch".to_string());
return Err("oauth state mismatch");
}
if code.trim().is_empty() {
self.last_error = Some("empty oauth authorization code".to_string());
return Err("empty oauth authorization code");
}
self.authenticated_provider = Some("oauth".to_string());
self.pending_credential = Some(code.to_string());
self.authenticated_subject = None;
self.expected_oauth_state = None;
self.stage = OnboardingStage::PendingExchange;
self.last_error = None;
Ok(())
}
/// Finalize server code/token exchange with the confirmed user `subject`.
pub fn confirm_session_exchange(&mut self, subject: &str) -> Result<(), &'static str> {
if self.stage != OnboardingStage::PendingExchange || self.pending_credential.is_none() {
return Err("no pending credential exchange");
}
let trimmed = subject.trim();
if trimmed.is_empty() {
self.last_error = Some("empty confirmed subject".to_string());
return Err("empty confirmed subject");
}
self.pending_credential = None;
self.authenticated_subject = Some(trimmed.to_string());
self.stage = OnboardingStage::Completed;
self.last_error = None;
Ok(())
}
/// Record a server code/token exchange failure and return to `SignInChoice` so the user can retry.
pub fn fail_session_exchange(&mut self, reason: &str) {
self.pending_credential = None;
self.authenticated_subject = None;
self.expected_oauth_state = None;
self.stage = OnboardingStage::SignInChoice;
self.last_error = Some(if reason.trim().is_empty() {
"session exchange failed".to_string()
} else {
reason.to_string()
});
}
}
/// Combined narrow-bridge state for the iOS native islands.
#[derive(Debug, Default)]
pub struct IosNativeIslandsState {
pub paywall: PaywallStateMachine,
pub onboarding: OnboardingSignInState,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ios_native_islands_cover_paywall_invariants_and_two_step_onboarding_exchange() {
let mut islands = IosNativeIslandsState::default();
// 1. AffinePaywall 3-product allowlist, JWS validation, and clean failure state clearing.
assert!(!PaywallStateMachine::is_known_product_id(
"app.affine.pro.ai.Monthly"
));
islands.paywall.begin_load_products();
islands
.paywall
.set_products(vec![PaywallProduct {
product_id: "app.affine.pro.Monthly".into(),
display_name: "AFFiNE Pro Monthly".into(),
display_price: "$9.99".into(),
}])
.expect("products");
islands
.paywall
.begin_purchase("app.affine.pro.Monthly")
.expect("begin purchase");
assert!(
islands
.paywall
.complete_verified_transaction("app.affine.pro.Monthly", "tx-1", "not-a-jws")
.is_err()
);
assert_eq!(islands.paywall.phase, PaywallPhase::Failed);
assert!(islands.paywall.verified_transaction_id.is_none());
assert!(islands.paywall.active_product_id.is_none());
islands
.paywall
.complete_verified_transaction(
"app.affine.pro.Monthly",
"tx-1",
"eyJhbGciOiJFUzI1NiJ9.eyJzdWIiOiIxIn0.c2ln",
)
.expect("verified jws");
assert_eq!(islands.paywall.phase, PaywallPhase::Verified);
// Rejecting a subsequent unknown product must clear stale `verified_transaction_id`.
assert!(
islands
.paywall
.complete_verified_transaction(
"com.unknown.Item",
"tx-2",
"eyJhbGciOiJFUzI1NiJ9.eyJzdWIiOiIxIn0.c2ln",
)
.is_err()
);
assert_eq!(islands.paywall.phase, PaywallPhase::Failed);
assert!(islands.paywall.verified_transaction_id.is_none());
assert!(islands.paywall.active_product_id.is_none());
islands.paywall.clear_entitlement();
assert_eq!(islands.paywall.phase, PaywallPhase::Ready);
// 2. Two-phase OAuth / Apple credential exchange: callback enters `PendingExchange`
// without populating `authenticated_subject`, covers exchange failure + retry + success.
islands.onboarding.advance_to_sign_in();
islands
.onboarding
.begin_oauth("csrf-state-123456")
.expect("oauth begin");
assert!(
islands
.onboarding
.receive_oauth_callback("auth-code-once", "wrong-state")
.is_err()
);
islands
.onboarding
.receive_oauth_callback("auth-code-once", "csrf-state-123456")
.expect("oauth callback received");
assert_eq!(islands.onboarding.stage, OnboardingStage::PendingExchange);
assert!(islands.onboarding.authenticated_subject.is_none());
assert_eq!(
islands.onboarding.pending_credential.as_deref(),
Some("auth-code-once")
);
// Simulate server exchange failure -> returns to `SignInChoice` so retry works cleanly.
islands.onboarding.fail_session_exchange("invalid_grant");
assert_eq!(islands.onboarding.stage, OnboardingStage::SignInChoice);
assert!(islands.onboarding.pending_credential.is_none());
assert!(islands.onboarding.authenticated_subject.is_none());
// Retry via Apple Sign-In -> `PendingExchange` -> `confirm_session_exchange` -> `Completed`.
islands
.onboarding
.receive_apple_credential(
"001234.abcdef",
"eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ1MSJ9.c2ln",
)
.expect("apple credential");
assert_eq!(islands.onboarding.stage, OnboardingStage::PendingExchange);
assert!(islands.onboarding.authenticated_subject.is_none());
islands
.onboarding
.confirm_session_exchange("usr_confirmed_42")
.expect("confirm session");
assert_eq!(islands.onboarding.stage, OnboardingStage::Completed);
assert_eq!(
islands.onboarding.authenticated_subject.as_deref(),
Some("usr_confirmed_42")
);
assert!(islands.onboarding.pending_credential.is_none());
}
}
@@ -0,0 +1,435 @@
//! Thin iOS adapter over [`affine_store::share_ingest`] for `ShareExtensionBridge`.
//!
//! Delegates all validation, SHA-256 content-addressed blob persistence, `0.27.5`
//! `affine:share-import-receipt-v1` & `hasValidSharePlan` idempotency, and `tagIds` /
//! `collectionId` root metadata updates to the single canonical store-domain implementation.
pub use affine_store::share_ingest::{
IOS_APP_GROUP_ID, MAX_SHARE_ATTACHMENT_BYTES, SHARE_IMPORT_RECEIPT_PROPERTY_ID,
ShareIngestAttachmentSpec, ShareIngestOutcome, ShareIngestRequest, SharePayloadKind,
ingest_share_item_into_sqlite, sha256_base64url,
};
use crate::workspace_store::{IosWorkspaceHandle, WorkspaceStoreError};
impl IosWorkspaceHandle {
/// Read a non-deleted attachment blob by key from the workspace SQLite `blobs` table.
pub fn read_blob(&self, key: &str) -> Result<Option<Vec<u8>>, WorkspaceStoreError> {
let record = self.runtime.block_on(self.storage.get_blob(key))?;
Ok(record.map(|r| r.data))
}
/// Atomically ingest one ShareExtension item into SQLite (`blobs` + `updates` + `clocks` +
/// `db$docProperties` + `share_ingest_receipts`) inside a single `BEGIN IMMEDIATE ... COMMIT`
/// transaction via [`affine_store::share_ingest::ingest_share_item_into_sqlite`].
pub fn ingest_share_item(
&self,
req: &ShareIngestRequest,
blob_bytes: &[u8],
) -> Result<ShareIngestOutcome, WorkspaceStoreError> {
if self.storage.is_closed() {
return Err(WorkspaceStoreError::Database(
"workspace storage is closed".into(),
));
}
let db_path = self.db_path.clone();
let workspace_id = self.space_id.clone();
self.runtime
.block_on(ingest_share_item_into_sqlite(
&db_path,
&workspace_id,
req,
blob_bytes,
))
.map_err(WorkspaceStoreError::from)
}
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use affine_store::workspace_db::{WorkspaceDb, WorkspaceDbTableName, WorkspaceRootDoc};
use blocksuite_playground_doc::{
read::BlockContent, schema::BlockSpec, session::PageDocSession,
};
use super::*;
fn unique_temp_dir(label: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!(
"affine-ios-share-ingest-{label}-{}-{}",
std::process::id(),
uuid::Uuid::new_v4()
));
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn share_ingest_matches_0275_sha256_empty_title_pdf_style_image_size_tags_and_collections() {
let docs = unique_temp_dir("parity-0275");
let allowlist = vec!["ws-share".to_string()];
let ws =
IosWorkspaceHandle::open(&docs, "workspace", "local", "ws-share", Some(&allowlist))
.unwrap();
// Seed workspace root with tag "tag-rust" and collection "col-inbox" as 0.27.5 would.
{
let mut root = WorkspaceRootDoc::new("ws-share", 11);
if let Some(u) = root.initialize_meta().unwrap() {
ws.runtime
.block_on(ws.storage.push_update("ws-share", u, 1_795_880_000_000))
.unwrap();
}
if let Some(u) = root
.define_tag("tag-rust", "Rust", "blue", 1_795_880_000_000)
.unwrap()
{
ws.runtime
.block_on(ws.storage.push_update("ws-share", u, 1_795_880_000_001))
.unwrap();
}
if let Some(u) = root.define_collection("col-inbox", "Inbox").unwrap() {
ws.runtime
.block_on(ws.storage.push_update("ws-share", u, 1_795_880_000_002))
.unwrap();
}
}
// 1) PDF with tagIds + collectionId + SHA-256 content-addressed blob + style == "pdf".
let pdf_bytes = b"%PDF-1.4\n";
let expected_pdf_key = sha256_base64url(pdf_bytes);
let pdf_req = ShareIngestRequest {
share_id: "item-pdf-1".into(),
import_attempt_id: "attempt-pdf-1".into(),
doc_id: "doc-pdf-1".into(),
kind: SharePayloadKind::Pdf,
title: "Spec PDF".into(),
text_or_url: String::new(),
secondary_text: String::new(),
tag_ids: vec!["tag-rust".into()],
collection_id: Some("col-inbox".into()),
attachments: vec![ShareIngestAttachmentSpec {
blob_key: String::new(),
file_name: "x.pdf".into(),
mime_type: "application/pdf".into(),
byte_offset: 0,
byte_len: pdf_bytes.len(),
}],
client_id: 0,
now_ms: 1_795_880_000_010,
};
let pdf_out = ws.ingest_share_item(&pdf_req, pdf_bytes).unwrap();
assert!(!pdf_out.already_committed);
assert_eq!(pdf_out.blob_keys, vec![expected_pdf_key.clone()]);
// 2) Untitled URL share: empty title MUST remain `""` (never `doc-untitled-2`).
let url_req = ShareIngestRequest {
share_id: "item-url-2".into(),
import_attempt_id: "attempt-url-2".into(),
doc_id: "doc-untitled-2".into(),
kind: SharePayloadKind::Url,
title: String::new(),
text_or_url: "https://affine.pro".into(),
secondary_text: String::new(),
tag_ids: Vec::new(),
collection_id: None,
attachments: Vec::new(),
client_id: 0,
now_ms: 1_795_880_000_020,
};
ws.ingest_share_item(&url_req, &[]).unwrap();
// 3) Image share: prop:size MUST equal exact byte count (12), not -1.
let img_bytes = b"\x89PNG\r\n\x1a\n1234";
let expected_img_key = sha256_base64url(img_bytes);
let img_req = ShareIngestRequest {
share_id: "item-img-3".into(),
import_attempt_id: "attempt-img-3".into(),
doc_id: "doc-img-3".into(),
kind: SharePayloadKind::Image,
title: "Photo".into(),
text_or_url: String::new(),
secondary_text: String::new(),
tag_ids: Vec::new(),
collection_id: None,
attachments: vec![ShareIngestAttachmentSpec {
blob_key: String::new(),
file_name: "p.png".into(),
mime_type: "image/png".into(),
byte_offset: 0,
byte_len: img_bytes.len(),
}],
client_id: 0,
now_ms: 1_795_880_000_030,
};
ws.ingest_share_item(&img_req, img_bytes).unwrap();
// Retry of item-pdf-1 hits share_ingest_receipts idempotently.
assert!(
ws.ingest_share_item(&pdf_req, pdf_bytes)
.unwrap()
.already_committed
);
ws.checkpoint().unwrap();
ws.close();
// Reopen from disk and verify every invariant.
let reopened =
IosWorkspaceHandle::open(&docs, "workspace", "local", "ws-share", Some(&allowlist))
.unwrap();
assert_eq!(
reopened.read_blob(&expected_pdf_key).unwrap().as_deref(),
Some(pdf_bytes.as_slice())
);
assert_eq!(
reopened.read_blob(&expected_img_key).unwrap().as_deref(),
Some(img_bytes.as_slice())
);
let pdf_bin = reopened.read_doc_binary("doc-pdf-1").unwrap().unwrap();
let pdf_json = {
let mut s = PageDocSession::new("doc-pdf-1", 42).unwrap();
s.apply_remote_update_v1(&pdf_bin).unwrap();
s.export_doc_json().unwrap()
};
assert_eq!(
pdf_json["blocks"]["share-attempt-pdf-1-attachment"]["prop:style"],
"pdf"
);
assert_eq!(
pdf_json["blocks"]["share-attempt-pdf-1-attachment"]["prop:embed"],
true
);
let img_bin = reopened.read_doc_binary("doc-img-3").unwrap().unwrap();
let img_json = {
let mut s = PageDocSession::new("doc-img-3", 42).unwrap();
s.apply_remote_update_v1(&img_bin).unwrap();
s.export_doc_json().unwrap()
};
assert_eq!(
img_json["blocks"]["share-attempt-img-3-image"]["prop:size"],
12
);
let untitled_bin = reopened.read_doc_binary("doc-untitled-2").unwrap().unwrap();
let mut untitled_sess = PageDocSession::new("doc-untitled-2", 42).unwrap();
untitled_sess.apply_remote_update_v1(&untitled_bin).unwrap();
assert_eq!(untitled_sess.read_page_snapshot().unwrap().title(), "");
let root_bin = reopened.read_doc_binary("ws-share").unwrap().unwrap();
let root = WorkspaceRootDoc::from_update_v1("ws-share", 99, &root_bin).unwrap();
let pdf_meta = root.get_page("doc-pdf-1").unwrap().unwrap();
assert_eq!(pdf_meta.tags, vec!["tag-rust".to_string()]);
assert_eq!(
root.collection_allow_list("col-inbox").unwrap(),
Some(vec!["doc-pdf-1".to_string()])
);
let untitled_meta = root.get_page("doc-untitled-2").unwrap().unwrap();
assert_eq!(untitled_meta.title, "");
reopened.close();
let _ = std::fs::remove_dir_all(&docs);
}
#[test]
fn interrupted_0275_partial_blocks_are_reused_without_overwriting_or_duplicating_children() {
let docs = unique_temp_dir("interrupted-0275");
let allowlist = vec!["ws-share".to_string()];
let ws =
IosWorkspaceHandle::open(&docs, "workspace", "local", "ws-share", Some(&allowlist))
.unwrap();
// Simulate 0.27.5 having written `preparing` receipt + partial/full share blocks,
// plus a user/preview edit on the bookmark title, before crashing prior to `committed`.
{
let mut s = PageDocSession::new("doc-resume", 55).unwrap();
s.add_block(
"share-att-resume-page",
BlockSpec::Page {
title: "Original".into(),
},
None,
None,
1,
)
.unwrap();
s.add_block(
"share-att-resume-surface",
BlockSpec::Surface,
Some("share-att-resume-page"),
None,
2,
)
.unwrap();
s.add_block(
"share-att-resume-note",
BlockSpec::Note {
xywh: Some("[0,0,800,600]".into()),
},
Some("share-att-resume-page"),
None,
3,
)
.unwrap();
s.add_block(
"share-att-resume-bookmark",
BlockSpec::Bookmark {
url: "https://example.com/page".into(),
title: Some("Preview Fetched By 0.27.5".into()),
description: None,
},
Some("share-att-resume-note"),
None,
4,
)
.unwrap();
let bin = s.encode_update_v1().unwrap();
ws.runtime
.block_on(ws.storage.push_update("doc-resume", bin, 1_795_880_000_000))
.unwrap();
let mut db = WorkspaceDb::new("ws-share", "local", 55);
let mut row = serde_json::Map::new();
row.insert("id".into(), "doc-resume".into());
row.insert(
SHARE_IMPORT_RECEIPT_PROPERTY_ID.into(),
serde_json::json!({
"version": 1,
"attemptId": "att-resume",
"state": "preparing"
})
.to_string()
.into(),
);
let dp_bin = db
.upsert_db_row(WorkspaceDbTableName::DocProperties, &row)
.unwrap();
ws.runtime
.block_on(ws.storage.push_update(
&WorkspaceDbTableName::DocProperties.local_doc_id(),
dp_bin,
1_795_880_000_001,
))
.unwrap();
}
let req = ShareIngestRequest {
share_id: "share-resume-1".into(),
import_attempt_id: "att-resume".into(),
doc_id: "doc-resume".into(),
kind: SharePayloadKind::Url,
title: "Fallback Title".into(),
text_or_url: "https://example.com/page".into(),
secondary_text: "Missing quote leaf".into(),
tag_ids: Vec::new(),
collection_id: None,
attachments: Vec::new(),
client_id: 77,
now_ms: 1_795_880_000_100,
};
let out = ws.ingest_share_item(&req, &[]).unwrap();
assert!(!out.already_committed);
let doc_bin = ws.read_doc_binary("doc-resume").unwrap().unwrap();
let mut verify = PageDocSession::new("doc-resume", 88).unwrap();
verify.apply_remote_update_v1(&doc_bin).unwrap();
let snap = verify.read_page_snapshot().unwrap();
let note = snap
.root
.as_ref()
.unwrap()
.children
.iter()
.find(|n| n.id == "share-att-resume-note")
.unwrap();
let child_ids: Vec<&str> = note.children.iter().map(|c| c.id.as_str()).collect();
assert_eq!(
child_ids,
vec![
"share-att-resume-bookmark",
"share-att-resume-selected-text"
],
"existing bookmark must not be duplicated in sys:children"
);
match &note.children[0].content {
BlockContent::Bookmark { title, .. } => {
assert_eq!(
title.as_deref(),
Some("Preview Fetched By 0.27.5"),
"existing bookmark block must not be overwritten"
);
}
other => panic!("expected Bookmark, got {other:?}"),
}
// A different share item claiming a DIFFERENT attemptId on `doc-resume` must fail with conflict.
let conflict_req = ShareIngestRequest {
share_id: "share-conflict-2".into(),
import_attempt_id: "att-other".into(),
doc_id: "doc-resume".into(),
..req
};
assert!(ws.ingest_share_item(&conflict_req, &[]).is_err());
ws.close();
let _ = std::fs::remove_dir_all(&docs);
}
#[test]
fn corrupted_workspace_root_and_missing_destinations_abort_atomically() {
let docs = unique_temp_dir("corrupt-root");
let allowlist = vec!["ws-share".to_string()];
let ws =
IosWorkspaceHandle::open(&docs, "workspace", "local", "ws-share", Some(&allowlist))
.unwrap();
// Missing destination tag must fail before creating blob or doc.
let pdf_bytes = b"%PDF-1.4\n";
let missing_tag_req = ShareIngestRequest {
share_id: "item-missing-tag".into(),
import_attempt_id: "att-missing-tag".into(),
doc_id: "doc-missing-tag".into(),
kind: SharePayloadKind::Pdf,
title: "Tagged".into(),
text_or_url: String::new(),
secondary_text: String::new(),
tag_ids: vec!["nonexistent-tag".into()],
collection_id: None,
attachments: vec![ShareIngestAttachmentSpec {
blob_key: String::new(),
file_name: "c.pdf".into(),
mime_type: "application/pdf".into(),
byte_offset: 0,
byte_len: pdf_bytes.len(),
}],
client_id: 7,
now_ms: 1_795_880_000_000,
};
assert!(ws.ingest_share_item(&missing_tag_req, pdf_bytes).is_err());
assert!(
ws.read_blob(&sha256_base64url(pdf_bytes))
.unwrap()
.is_none()
);
assert!(ws.read_doc_binary("doc-missing-tag").unwrap().is_none());
// Corrupted workspace root must also roll back atomically.
ws.runtime
.block_on(
ws.storage
.push_update("ws-share", [0xff_u8, 0xff, 0xff], 1_795_880_000_000),
)
.unwrap();
let mut plain_req = missing_tag_req;
plain_req.tag_ids.clear();
assert!(ws.ingest_share_item(&plain_req, pdf_bytes).is_err());
assert!(ws.read_doc_binary("doc-missing-tag").unwrap().is_none());
ws.close();
let _ = std::fs::remove_dir_all(&docs);
}
}
@@ -35,6 +35,10 @@ struct BlockSummaryDto<'a> {
id: &'a str,
flavour: &'a str,
text: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
source_id: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
url: Option<&'a str>,
child_ids: Vec<&'a str>,
}
@@ -48,6 +52,24 @@ fn block_plain_text(node: &BlockNode) -> Option<&str> {
}
}
fn block_source_id(node: &BlockNode) -> Option<&str> {
match &node.content {
BlockContent::Image { source_id, .. } | BlockContent::Attachment { source_id, .. } => {
Some(source_id.as_str())
}
_ => None,
}
}
fn block_url(node: &BlockNode) -> Option<&str> {
match &node.content {
BlockContent::Bookmark { url, .. } | BlockContent::ExternalEmbed { url, .. } => {
Some(url.as_str())
}
_ => None,
}
}
fn serialize_page_snapshot(snapshot: &PageSnapshot) -> Result<String, serde_json::Error> {
let blocks: Vec<BlockSummaryDto<'_>> = snapshot
.root
@@ -58,6 +80,8 @@ fn serialize_page_snapshot(snapshot: &PageSnapshot) -> Result<String, serde_json
id: node.id.as_str(),
flavour: node.flavour.as_str(),
text: block_plain_text(node),
source_id: block_source_id(node),
url: block_url(node),
child_ids: node.children.iter().map(|c| c.id.as_str()).collect(),
})
.collect();
@@ -82,6 +106,10 @@ pub enum WorkspaceStoreError {
Json(#[from] serde_json::Error),
#[error("local workspace {0:?} requires an explicit affine-local-workspace allowlist entry")]
WorkspaceNotAllowlisted(String),
#[error("invalid share ingest payload: {0}")]
InvalidSharePayload(String),
#[error("database error: {0}")]
Database(String),
}
/// Persisted result of an offline paragraph edit on an in-place SQLite WAL database.
@@ -136,10 +164,10 @@ pub fn resolve_allowlisted_local_workspaces(
/// Handle to an opened 0.27.5-compatible in-place SQLite WAL workspace or userspace database.
pub struct IosWorkspaceHandle {
storage: SqliteDocStorage,
runtime: Runtime,
space_id: String,
db_path: PathBuf,
pub(crate) storage: SqliteDocStorage,
pub(crate) runtime: Runtime,
pub(crate) space_id: String,
pub(crate) db_path: PathBuf,
}
impl IosWorkspaceHandle {
@@ -229,13 +257,16 @@ impl IosWorkspaceHandle {
client_id: u64,
now_ms: i64,
) -> Result<OfflineEditResult, WorkspaceStoreError> {
let Some(existing) = self.read_doc_binary(doc_id)? else {
return Err(WorkspaceStoreError::Store(
affine_store::StoreError::DocNotFound(doc_id.to_string()),
));
};
let mut session = PageDocSession::new(doc_id, client_id)?;
if let Some(existing) = self.read_doc_binary(doc_id)? {
session.apply_remote_update_v1(&existing)?;
}
let now_u64 = now_ms.max(0) as u64;
session.apply_remote_update_v1(&existing)?;
let sv_before = session.encode_state_vector_v1()?;
let now_u64 = now_ms.max(0) as u64;
if delete_len > 0 {
session.remove_text(block_id, "prop:text", utf16_index, delete_len, now_u64)?;
}
@@ -1,7 +1,9 @@
import CoreGraphics
import Foundation
import PDFKit
import SQLite3
import UIKit
import WebKit
func requireS3(_ condition: Bool, _ message: String) {
if !condition {
@@ -82,15 +84,16 @@ func assertColor(_ px: (UInt8, UInt8, UInt8, UInt8), r: Bool, g: Bool, b: Bool,
@main
struct IosHostS3SmokeTest {
@MainActor
static func main() {
static func main() async {
do {
try testPdfKitFourPageGeometryAndGuards()
testTouchOwnershipPartitionAndReadonlyDocPositions()
testKeyboardAvoidancePerFrameSlideOverAndBackgroundResume()
testHapticsBridgeDispatchAndBoundedHistory()
testMetalHostViewControllerEndToEndTextSelectionDragCopyAndMenu()
testS6NativeEditorMountImeAndStageOneReadonly()
print("ALL 6 SWIFT+RUST S3/S6-IOS SMOKE TESTS PASSED")
try await testS6NativeEditorMountImeAndStageOneReadonly()
try await test0275SameSignatureWebViewAndSqliteUpgradeRollbackDrill()
print("ALL 7 SWIFT+RUST IOS HOST SMOKE TESTS PASSED")
} catch {
fputs("UNHANDLED ERROR: \(error)\n", stderr)
exit(1)
@@ -720,7 +723,7 @@ struct IosHostS3SmokeTest {
/// H-S1 zero backingText copy (Markdown `# ` + `[[` -> `@`), H-S2 inputDelegate notifications,
/// newline block split & block-start deleteBackward merge, and T1 Stage-1 touch readonly.
@MainActor
static func testS6NativeEditorMountImeAndStageOneReadonly() {
static func testS6NativeEditorMountImeAndStageOneReadonly() async throws {
let vc = MetalHostViewController()
vc.view.frame = CGRect(x: 0, y: 0, width: 390, height: 844)
vc.loadViewIfNeeded()
@@ -894,7 +897,6 @@ struct IosHostS3SmokeTest {
"External editor mutation must notify UITextInputDelegate"
)
vcSafe.textHostView.inputDelegate = nil
// Code input mode disables autocorrection, autocapitalization, smart quotes, and smart dashes.
affine_ios_host_reset_empty_doc(safeHandle)
requireS3(
@@ -950,12 +952,27 @@ struct IosHostS3SmokeTest {
}
}
// Reload showcase document and trigger a real GPU Metal frame render.
affine_ios_host_load_showcase_doc(handle)
let renderedColor = affine_ios_host_render_frame(handle, 1.0)
requireS3(renderedColor != 0, "GPU editor frame render must succeed on showcase doc")
// Verify all 3 zero-CocoaPods iOS Native Islands (Atomic SQLite ShareExtension, Paywall, Onboarding/SignIn).
requireS3(
ShareExtensionBridge.appGroupIdentifier == "group.app.affine.pro"
&& ShareExtensionBridge.inboxDirectoryName == "ShareInbox"
&& ShareExtensionBridge.attachmentsDirectoryName == "Attachments"
&& ShareExtensionBridge.invalidDirectoryName == "Invalid",
"ShareExtension must align 1:1 with group.app.affine.pro/ShareInbox/{Attachments,Invalid}"
)
let tempInbox = FileManager.default.temporaryDirectory
.appendingPathComponent("affine-ios-s6-share-\(UUID().uuidString)", isDirectory: true)
.appendingPathComponent("ShareInbox", isDirectory: true)
let tempShareDocs = FileManager.default.temporaryDirectory
.appendingPathComponent("affine-ios-s6-share-docs-\(UUID().uuidString)", isDirectory: true)
defer {
try? FileManager.default.removeItem(at: tempInbox.deletingLastPathComponent())
try? FileManager.default.removeItem(at: tempShareDocs)
}
try! FileManager.default.createDirectory(at: tempShareDocs, withIntermediateDirectories: true)
let shareBridge = ShareExtensionBridge(inboxDirectory: tempInbox)
// Wave 3 cold-start regression guards:
// Cold-start regression guards:
// (a) Single-tap on prose at cold start (`wants_software_keyboard == false`): UIKit calls
// `becomeFirstResponder()` (which initially queries `inputView` -> `emptyInputView`),
// immediately followed by `setSelectedTextRange:` placing a collapsed caret on prose ->
@@ -1033,6 +1050,726 @@ struct IosHostS3SmokeTest {
_ = vcColdRo.textHostView.resignFirstResponder()
}
print("PASS [6/6]: S6 iOS native GPU editor mount, safe-area alignment, H-S1/H-S2 IME, block split/merge, UITextInteraction selection, empty-tail tap keyboard raise, and T1 readonly passed")
// 1) Real ShareInboxStore layout: ShareInbox/<id>.json + ShareInbox/Attachments/<id>/x.pdf (9 bytes)
// + schemaVersion 1 legacy envelope (no importAttemptId) + schemaVersion 99 future envelope (preserved).
let pdf9Bytes = Data("%PDF-1.4\n".utf8)
requireS3(pdf9Bytes.count == 9, "test PDF fixture must be 9 bytes")
let shareItem = ShareInboxItem(
id: "ios-share-1",
documentId: "share-doc-url",
title: "AFFiNE",
content: ShareInboxContent(kind: .url, url: "https://affine.pro", text: nil),
target: ShareInboxTarget(
workspaceId: "ws-share-1",
workspaceFlavour: "local",
tagIds: [],
collectionId: nil
)
)
let pdfShareItem = ShareInboxItem(
id: "ios-share-pdf-1",
documentId: "share-doc-pdf",
title: "Spec",
content: ShareInboxContent(kind: .pdf, url: nil, text: nil),
attachments: [
ShareInboxAttachment(
fileName: "x.pdf",
mimeType: "application/pdf",
relativePath: "ios-share-pdf-1/x.pdf"
),
]
)
let staged = try! shareBridge.stageItem(shareItem)
let stagedPdf = try! shareBridge.stageItem(
pdfShareItem,
attachmentBlobs: ["ios-share-pdf-1/x.pdf": pdf9Bytes]
)
let pdfAttDir = tempInbox.appendingPathComponent("Attachments/ios-share-pdf-1", isDirectory: true)
let pdfAttPath = pdfAttDir.appendingPathComponent("x.pdf")
// Legacy v1 manifest (omits schemaVersion & importAttemptId).
let v1ManifestUrl = tempInbox.appendingPathComponent("ios-share-v1.json")
let v1Json = """
{
"id": "ios-share-v1",
"documentId": "share-doc-v1",
"createdAt": "2026-11-28T10:00:00Z",
"title": "Legacy v1",
"content": { "kind": "text", "text": "Legacy v1 shared note" }
}
"""
try! Data(v1Json.utf8).write(to: v1ManifestUrl, options: .atomic)
// Future schemaVersion 99 manifest: MUST be skipped and preserved untouched.
let v99ManifestUrl = tempInbox.appendingPathComponent("ios-share-v99.json")
let v99Json = """
{
"schemaVersion": 99,
"importAttemptId": "future-attempt",
"id": "ios-share-v99",
"documentId": "share-doc",
"createdAt": "2026-11-28T11:00:00Z",
"title": "Future",
"content": { "kind": "text", "text": "Future format" }
}
"""
try! Data(v99Json.utf8).write(to: v99ManifestUrl, options: .atomic)
requireS3(
FileManager.default.fileExists(atPath: staged.path)
&& FileManager.default.fileExists(atPath: stagedPdf.path)
&& FileManager.default.fileExists(atPath: pdfAttPath.path)
&& FileManager.default.fileExists(atPath: v1ManifestUrl.path)
&& FileManager.default.fileExists(atPath: v99ManifestUrl.path),
"ShareExtension fixtures must exist under ShareInbox/<id>.json and ShareInbox/Attachments/<id>/x.pdf"
)
// Precondition gate: unmounted workspace (workspace == nil) MUST consume 0 and leave every file untouched.
let unmountedCount = shareBridge.drainAndIngestIntoHost(handle, workspace: nil)
requireS3(
unmountedCount == 0
&& FileManager.default.fileExists(atPath: staged.path)
&& FileManager.default.fileExists(atPath: stagedPdf.path)
&& FileManager.default.fileExists(atPath: pdfAttPath.path)
&& FileManager.default.fileExists(atPath: v1ManifestUrl.path)
&& FileManager.default.fileExists(atPath: v99ManifestUrl.path),
"Unmounted workspace must consume 0 items and never touch ShareInbox files"
)
// Mount workspace and consume atomically into SQLite (blobs + updates + share_ingest_receipts).
let shareCoord1 = HostBootstrapCoordinator(documentsDirectory: tempShareDocs)
try! shareCoord1.applyLocalWorkspaceAllowlist(["ws-share-1"])
let shareWs1 = shareCoord1.workspace(id: "ws-share-1")!
affine_ios_host_reset_empty_doc(handle)
let ingestedCount = shareBridge.drainAndIngestIntoHost(handle, workspace: shareWs1)
requireS3(
ingestedCount == 3,
"ShareExtension must atomically ingest 3 items (URL + 9-byte PDF + v1 text), got \(ingestedCount)"
)
requireS3(
!FileManager.default.fileExists(atPath: staged.path)
&& !FileManager.default.fileExists(atPath: stagedPdf.path)
&& !FileManager.default.fileExists(atPath: pdfAttDir.path)
&& !FileManager.default.fileExists(atPath: v1ManifestUrl.path)
&& FileManager.default.fileExists(atPath: v99ManifestUrl.path),
"ShareExtension cleanup must remove consumed JSON + Attachments/<id>/ dir while preserving schemaVersion 99"
)
shareCoord1.closeAll()
// Reopen SQLite workspace: verify exact 9-byte SHA-256 content-addressed blob in `blobs` table AND all 3 blocks in `share-doc`.
let shareCoord2 = HostBootstrapCoordinator(documentsDirectory: tempShareDocs)
try! shareCoord2.applyLocalWorkspaceAllowlist(["ws-share-1"])
let shareWs2 = shareCoord2.workspace(id: "ws-share-1")!
let expectedPdfBlobKey = ShareExtensionBridge.sha256Base64Url(pdf9Bytes)
requireS3(
expectedPdfBlobKey.count == 44,
"0.27.5 blob key must be 44-char unpadded base64url SHA-256, got \(expectedPdfBlobKey)"
)
let readBackBlob = shareWs2.readBlob(key: expectedPdfBlobKey)
requireS3(
readBackBlob == pdf9Bytes,
"Reopened SQLite blobs table must contain exact 9-byte PDF attachment under SHA-256 key, got \(String(describing: readBackBlob?.count))"
)
let persistedUrlSnap = shareWs2.readPageSnapshotJson(docId: "share-doc-url", clientId: 1) ?? ""
let persistedPdfSnap = shareWs2.readPageSnapshotJson(docId: "share-doc-pdf", clientId: 1) ?? ""
let persistedV1Snap = shareWs2.readPageSnapshotJson(docId: "share-doc-v1", clientId: 1) ?? ""
requireS3(
persistedUrlSnap.contains("https://affine.pro")
&& persistedUrlSnap.contains("affine:bookmark")
&& persistedPdfSnap.contains(expectedPdfBlobKey)
&& persistedPdfSnap.contains("affine:attachment")
&& persistedV1Snap.contains("Legacy v1 shared note"),
"Reopened SQLite docs must contain Bookmark URL, SHA-256 Attachment blob reference, and v1 text"
)
// Active PlaygroundView text must NOT be polluted by unrelated background ShareInbox ingests.
let activeEditorRange = vc.textHostView.textRange(
from: vc.textHostView.beginningOfDocument,
to: vc.textHostView.endOfDocument
)
let activeEditorText = activeEditorRange.flatMap { vc.textHostView.text(in: $0) } ?? ""
requireS3(
!activeEditorText.contains("Legacy v1 shared note"),
"ShareInbox SQLite ingest must never dual-write into an unrelated open PlaygroundView buffer"
)
// Cloud-targeted or other-workspace share manifests must stay untouched when only ws-share-1 is mounted.
let cloudTargetedUrl = try! shareBridge.stageItem(ShareInboxItem(
id: "ios-share-cloud-1",
documentId: "cloud-doc-1",
title: "Cloud Target",
content: ShareInboxContent(kind: .text, url: nil, text: "Keep for cloud sync"),
target: ShareInboxTarget(
workspaceId: "ws-cloud-9",
workspaceFlavour: "affine-cloud",
tagIds: [],
collectionId: nil
)
))
let skippedCloud = shareBridge.drainAndIngestIntoHost(handle, workspace: shareWs2)
requireS3(
skippedCloud == 0 && FileManager.default.fileExists(atPath: cloudTargetedUrl.path),
"Cloud-targeted ShareInbox manifest must remain untouched when draining local workspace"
)
try? FileManager.default.removeItem(at: cloudTargetedUrl)
// Corrupt JSON and invalid URL scheme must be moved into ShareInbox/Invalid/ (zero rescan loop).
let corruptUrl = tempInbox.appendingPathComponent("999-corrupt.json")
try! "{not-valid-json".data(using: .utf8)!.write(to: corruptUrl)
let rejectedUrl = try! shareBridge.stageItem(ShareInboxItem(
id: "ios-share-bad",
documentId: "share-doc-bad",
title: "Bad",
content: ShareInboxContent(kind: .url, url: "javascript:alert(1)", text: nil)
))
_ = shareBridge.drainAndIngestIntoHost(handle, workspace: shareWs2)
requireS3(!FileManager.default.fileExists(atPath: corruptUrl.path), "Corrupt JSON must be moved out of ShareInbox/")
requireS3(!FileManager.default.fileExists(atPath: rejectedUrl.path), "Invalid scheme manifest must be moved out of ShareInbox/")
requireS3(
FileManager.default.fileExists(atPath: shareBridge.invalidDirectory.appendingPathComponent("999-corrupt.json").path),
"Corrupt JSON must reside in ShareInbox/Invalid/"
)
// 2) SQLite COMMIT succeeded + first checkpoint_passive failed + retry -> idempotent receipt hit,
// target doc contains text EXACTLY ONCE (zero duplicate paragraphs).
let idempItem = ShareInboxItem(
id: "ios-share-idemp-1",
documentId: "share-doc-idemp",
title: "Idempotent",
content: ShareInboxContent(kind: .text, url: nil, text: "UNIQUE_IDEMPOTENT_MARKER_42")
)
let idempFile = try! shareBridge.stageItem(idempItem)
var checkpointCalls = 0
shareBridge.checkpointHook = { ws in
checkpointCalls += 1
if checkpointCalls == 1 {
return false // Inject first checkpoint_passive failure AFTER SQLite COMMIT succeeded.
}
return ws.checkpointPassive()
}
let firstAttempt = shareBridge.drainAndIngestIntoHost(handle, workspace: shareWs2)
requireS3(firstAttempt == 1, "First attempt commits SQLite tx before checkpoint failure (got \(firstAttempt))")
requireS3(
FileManager.default.fileExists(atPath: idempFile.path),
"Failed checkpoint_passive must leave manifest intact for idempotent retry"
)
let retryAttempt = shareBridge.drainAndIngestIntoHost(handle, workspace: shareWs2)
shareBridge.checkpointHook = nil
requireS3(retryAttempt == 0, "Retry must hit share_ingest_receipts idempotently (0 newly inserted), got \(retryAttempt)")
requireS3(!FileManager.default.fileExists(atPath: idempFile.path), "Successful retry checkpoint must clean up manifest")
let snapAfterRetry = shareWs2.readPageSnapshotJson(docId: "share-doc-idemp", clientId: 1) ?? ""
let markerOccurrences = snapAfterRetry.components(separatedBy: "UNIQUE_IDEMPOTENT_MARKER_42").count - 1
requireS3(
markerOccurrences == 1,
"Idempotent retry after checkpoint failure must insert text EXACTLY once, got \(markerOccurrences) in \(snapAfterRetry)"
)
shareCoord2.closeAll()
// 3) StoreKit 2 expiration & revocation reconciliation (`0.27.5` `PricingConfiguration` IDs):
// purchase -> persisted Verified -> restart -> currentEntitlements=[] clears disk & Rust ->
// re-purchase -> revocationDate != nil revokes immediately & deletes disk cache.
let tempEntitlementFile = FileManager.default.temporaryDirectory
.appendingPathComponent("affine-ios-s6-paywall-\(UUID().uuidString).json")
defer { try? FileManager.default.removeItem(at: tempEntitlementFile) }
let fixedNow = Date(timeIntervalSince1970: 1_800_000_000)
let futureExp = Date(timeIntervalSince1970: 1_800_086_400)
let paywall1 = AffinePaywallBridge(entitlementFileUrl: tempEntitlementFile)
paywall1.attach(host: handle, now: fixedNow)
requireS3(
paywall1.syncProductsPayload(host: handle, payload: [[
"product_id": "app.affine.pro.Monthly",
"display_name": "AFFiNE Pro",
"display_price": "$9.99",
]]),
"AffinePaywall must accept allowlisted 0.27.5 StoreKit 2 product"
)
requireS3(paywall1.beginPurchase(host: handle, productId: "app.affine.pro.Monthly"), "beginPurchase")
let activeSnap = PaywallEntitlementSnapshot(
transactionId: "tx-ios-1",
productId: "app.affine.pro.Monthly",
jwsRepresentation: "eyJhbGciOiJFUzI1NiJ9.eyJzdWIiOiIxIn0.c2ln",
expirationDate: futureExp,
revocationDate: nil
)
requireS3(
paywall1.applyVerifiedTransactionUpdate(activeSnap, host: handle, now: fixedNow),
"AffinePaywall must verify active JWS entitlement and persist to disk"
)
requireS3(paywall1.stateJson(host: handle).contains("verified"), "Paywall state must be verified")
requireS3(FileManager.default.fileExists(atPath: tempEntitlementFile.path), "Entitlement cache must exist on disk")
// Restart fresh host: restore persisted entitlement, then reconcile against empty currentEntitlements = [].
let vcFreshPaywall = MetalHostViewController()
vcFreshPaywall.view.frame = CGRect(x: 0, y: 0, width: 390, height: 844)
vcFreshPaywall.loadViewIfNeeded()
let paywall2 = AffinePaywallBridge(entitlementFileUrl: tempEntitlementFile)
paywall2.attach(host: vcFreshPaywall.hostPointer!, now: fixedNow)
let restoredPaywallJson = paywall2.stateJson(host: vcFreshPaywall.hostPointer!)
requireS3(
restoredPaywallJson.contains("verified")
&& restoredPaywallJson.contains("tx-ios-1")
&& restoredPaywallJson.contains("app.affine.pro.Monthly"),
"Restarted host must restore active persisted StoreKit 2 entitlement + product_id (got \(restoredPaywallJson))"
)
requireS3(
paywall2.reconcileCurrentEntitlements([], host: vcFreshPaywall.hostPointer!, now: fixedNow),
"Reconciling empty currentEntitlements must succeed"
)
let clearedPaywallJson = paywall2.stateJson(host: vcFreshPaywall.hostPointer!)
requireS3(
!clearedPaywallJson.contains("\"phase\":\"verified\"")
&& clearedPaywallJson.contains("\"verified_transaction_id\":null")
&& !FileManager.default.fileExists(atPath: tempEntitlementFile.path),
"Empty currentEntitlements must revoke Rust state and delete stale disk cache (got \(clearedPaywallJson))"
)
// Re-purchase and receive a verified transaction update with revocationDate != nil -> immediate revoke.
requireS3(
paywall2.applyVerifiedTransactionUpdate(activeSnap, host: vcFreshPaywall.hostPointer!, now: fixedNow),
"Re-applying active entitlement must succeed"
)
let revokedSnap = PaywallEntitlementSnapshot(
transactionId: "tx-ios-1",
productId: "app.affine.pro.Monthly",
jwsRepresentation: "eyJhbGciOiJFUzI1NiJ9.eyJzdWIiOiIxIn0.c2ln",
expirationDate: futureExp,
revocationDate: fixedNow
)
requireS3(
paywall2.applyVerifiedTransactionUpdate(revokedSnap, host: vcFreshPaywall.hostPointer!, now: fixedNow),
"Applying revoked transaction update must succeed"
)
let revokedPaywallJson = paywall2.stateJson(host: vcFreshPaywall.hostPointer!)
requireS3(
!revokedPaywallJson.contains("\"phase\":\"verified\"")
&& revokedPaywallJson.contains("\"verified_transaction_id\":null")
&& paywall2.activeEntitlements.isEmpty
&& !FileManager.default.fileExists(atPath: tempEntitlementFile.path),
"Revoked transaction update must immediately clear Rust state and disk cache (got \(revokedPaywallJson))"
)
// Unknown product with lexically earlier transactionId ("000-unknown") alongside valid Monthly ("tx-ios-1")
// must be filtered out BEFORE persistence and primary selection (never masking valid subscription).
let unknownSnap = PaywallEntitlementSnapshot(
transactionId: "000-unknown",
productId: "com.unknown.unlisted.item",
jwsRepresentation: "eyJhbGciOiJFUzI1NiJ9.eyJzdWIiOiIxIn0.c2ln",
expirationDate: futureExp,
revocationDate: nil
)
requireS3(
paywall2.reconcileCurrentEntitlements([unknownSnap, activeSnap], host: vcFreshPaywall.hostPointer!, now: fixedNow),
"reconcileCurrentEntitlements must succeed when unknown product coexists with valid Monthly"
)
let coexistingJson = paywall2.stateJson(host: vcFreshPaywall.hostPointer!)
requireS3(
coexistingJson.contains("\"phase\":\"verified\"")
&& coexistingJson.contains("tx-ios-1")
&& !coexistingJson.contains("000-unknown")
&& paywall2.activeEntitlements.keys.sorted() == ["tx-ios-1"],
"Unknown product must never mask valid subscription or enter activeEntitlements (got \(coexistingJson))"
)
// Disk persistence failure rollback: pointing entitlementFileUrl at an existing directory causes atomic write
// to fail and MUST leave both Swift memory and Rust paywall state untouched.
let unwritableDirUrl = FileManager.default.temporaryDirectory
.appendingPathComponent("affine-ios-paywall-unwritable-\(UUID().uuidString)", isDirectory: true)
try! FileManager.default.createDirectory(at: unwritableDirUrl, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: unwritableDirUrl) }
let paywallUnwritable = AffinePaywallBridge(entitlementFileUrl: unwritableDirUrl)
requireS3(
!paywallUnwritable.applyVerifiedTransactionUpdate(activeSnap, host: handle, now: fixedNow),
"Disk write failure must fail applyVerifiedTransactionUpdate"
)
requireS3(
paywallUnwritable.activeEntitlements.isEmpty,
"Disk write failure must roll back in-memory activeEntitlements"
)
requireS3(
vc.handleIncomingUrl(URL(string: "affine://share-inbox")!),
"MetalHostViewController.handleIncomingUrl must route affine://share-inbox deep links"
)
// Verify WorkspaceStorageBridge lock safety under concurrent background FFI + main-actor close().
do {
let raceDir = FileManager.default.temporaryDirectory
.appendingPathComponent("affine-ios-ws-lock-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: raceDir, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: raceDir) }
let raceBridge = try WorkspaceStorageBridge(
spaceType: "workspace",
peer: "local",
spaceId: "ws-lock-drill",
allowlistedLocalIds: ["ws-lock-drill"],
documentsDirectory: raceDir
)
let bgTask = Task.detached(priority: .utility) {
for i in 0..<24 {
_ = raceBridge.checkpointPassive()
_ = raceBridge.readDoc(docId: "doc-\(i)")
}
}
raceBridge.close()
await bgTask.value
requireS3(raceBridge.readDoc(docId: "doc-0") == nil, "closed WorkspaceStorageBridge must return nil safely")
}
// Narrow-bridge OnboardingSignInBridge two-stage state machine via MetalHostViewController.handleIncomingUrl:
requireS3(vc.onboardingSignIn.beginOAuth(host: handle, csrfState: "state-token-999"), "beginOAuth")
requireS3(
!vc.handleIncomingUrl(URL(string: "affine://auth/callback?code=c1&state=bad")!),
"OAuth callback via MetalHostViewController.handleIncomingUrl must reject CSRF mismatch"
)
requireS3(
vc.handleIncomingUrl(URL(string: "affine://auth/callback?code=c1&state=state-token-999")!),
"OAuth callback via MetalHostViewController.handleIncomingUrl must accept matching CSRF state"
)
let pendingOAuthJson = vc.onboardingSignIn.stateJson(host: handle)
requireS3(
pendingOAuthJson.contains("pending_exchange")
&& pendingOAuthJson.contains("\"authenticated_subject\":null"),
"OAuth callback must enter pending_exchange before session confirmation (got \(pendingOAuthJson))"
)
requireS3(
vc.onboardingSignIn.failSessionExchange(host: handle, reason: "simulated exchange error"),
"failSessionExchange must reset onboarding state"
)
requireS3(
vc.onboardingSignIn.stateJson(host: handle).contains("sign_in_choice"),
"Failed session exchange must reset onboarding state to sign_in_choice"
)
requireS3(vc.onboardingSignIn.beginOAuth(host: handle, csrfState: "state-token-retry"), "retry beginOAuth")
requireS3(
vc.handleIncomingUrl(URL(string: "affine://auth/callback?code=c2&state=state-token-retry")!),
"Retry OAuth callback URL must be accepted"
)
requireS3(
vc.onboardingSignIn.confirmSessionExchange(host: handle, subject: "usr-verified-1"),
"confirmSessionExchange must succeed"
)
let confirmedOAuthJson = vc.onboardingSignIn.stateJson(host: handle)
requireS3(
confirmedOAuthJson.contains("\"stage\":\"completed\"")
&& confirmedOAuthJson.contains("usr-verified-1"),
"Onboarding must reach completed with confirmed subject (got \(confirmedOAuthJson))"
)
requireS3(
vc.onboardingSignIn.completeAppleCredential(
host: handle,
userIdentifier: "apple-user-1",
identityTokenJws: "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ1MSJ9.c2ln"
),
"completeAppleCredential must accept compact 3-segment JWS into pending_exchange"
)
requireS3(
vc.onboardingSignIn.stateJson(host: handle).contains("pending_exchange"),
"Apple credential must enter pending_exchange before confirmation"
)
requireS3(
vc.onboardingSignIn.confirmSessionExchange(host: handle, subject: "usr-apple-1")
&& vc.onboardingSignIn.stateJson(host: handle).contains("usr-apple-1"),
"Apple sign-in must confirm verified subject"
)
// Reload showcase document, trigger light & dark GPU frames, and verify iOS dark chrome sync.
affine_ios_host_load_showcase_doc(handle)
let lightClear = vc.renderFrameNow(timestamp: 1.0)
requireS3(
lightClear != 0 && !affine_ios_host_is_dark_theme(handle)
&& vc.overrideUserInterfaceStyle == .light
&& vc.preferredStatusBarStyle == .darkContent,
"Light theme frame must sync light clearColor and light UIUserInterfaceStyle (clear=\(String(format: "0x%08X", lightClear)))"
)
affine_ios_host_set_dark_theme(handle, true)
let darkClear = vc.renderFrameNow(timestamp: 1.1)
let darkR = Double((darkClear >> 24) & 0xFF) / 255.0
let darkG = Double((darkClear >> 16) & 0xFF) / 255.0
let darkB = Double((darkClear >> 8) & 0xFF) / 255.0
let darkLuma = 0.2126 * darkR + 0.7152 * darkG + 0.0722 * darkB
requireS3(
darkClear != 0
&& darkClear != 0xFAFA_FCFF
&& darkLuma < 0.35
&& affine_ios_host_is_dark_theme(handle)
&& vc.overrideUserInterfaceStyle == .dark
&& vc.preferredStatusBarStyle == .lightContent
&& vc.textHostView.keyboardAppearance == .dark,
"Dark theme must sync dark clearColor (got \(String(format: "0x%08X", darkClear)), luma=\(darkLuma)), .dark overrideUserInterfaceStyle, .lightContent status bar, and .dark keyboard"
)
affine_ios_host_set_dark_theme(handle, false)
let restoredLight = vc.renderFrameNow(timestamp: 1.2)
requireS3(
restoredLight != 0
&& !affine_ios_host_is_dark_theme(handle)
&& vc.overrideUserInterfaceStyle == .light
&& vc.preferredStatusBarStyle == .darkContent,
"Restoring light theme must flip overrideUserInterfaceStyle back to .light"
)
print("PASS [6/7]: iOS native GPU editor mount, safe-area alignment, H-S1/H-S2 IME, block split/merge, UITextInteraction selection, empty-tail tap keyboard raise, native islands, and T1 readonly passed")
}
/// 7. Real WKWebView + real `<Documents>/workspaces/workspace/local/<spaceId>.db` 0.27.5
/// same-signature upgrade -> in-place edit -> rollback write-back -> old-shell readback drill.
@MainActor
static func test0275SameSignatureWebViewAndSqliteUpgradeRollbackDrill() async throws {
let tmpDocs = FileManager.default.temporaryDirectory
.appendingPathComponent("affine-ios-0275-drill-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: tmpDocs, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: tmpDocs) }
// 1) Seed 0.27.5 SQLite workspace (`<Documents>/workspaces/workspace/local/ws-0275-drill.db`)
// directly via raw `SQLite3` + genuine JavaScript `Yjs` (`yjs-npm-13.6.21`) V1 binary updates
// (zero new-host `WorkspaceStorageBridge` touched before upgrade!) AND 0.27.5 Capacitor
// WKWebView localStorage on `capacitor://localhost` (zero IDB).
let dbDir = tmpDocs
.appendingPathComponent("workspaces/workspace/local", isDirectory: true)
try FileManager.default.createDirectory(at: dbDir, withIntermediateDirectories: true)
let dbFile = dbDir.appendingPathComponent("ws-0275-drill.db")
do {
var rawDb: OpaquePointer?
let openRc = sqlite3_open_v2(
dbFile.path,
&rawDb,
SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE | SQLITE_OPEN_FULLMUTEX,
nil
)
requireS3(openRc == SQLITE_OK && rawDb != nil, "raw SQLite3 open for 0.27.5 seed must succeed")
defer { sqlite3_close(rawDb) }
let ddl = """
PRAGMA journal_mode = WAL;
CREATE TABLE _sqlx_migrations (
version BIGINT PRIMARY KEY,
description TEXT NOT NULL,
installed_on TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
success BOOLEAN NOT NULL,
checksum BLOB NOT NULL,
execution_time BIGINT NOT NULL
);
INSERT INTO _sqlx_migrations VALUES
(1, 'init_v2', '2026-11-28 12:00:00', 1, X'a1f0a1496ba1d1ff1689fc234514b13e7501ce5a3891b5943a75300b20e68444444ae71a1a80f40e46ccee2fc9e2af1a', 1),
(2, 'add_blob_sync', '2026-11-28 12:00:00', 1, X'c40244fec04822d74db419bead8486db435bb52d1f0214e4ddcc8928f4444475c7be8f96cee4c4383fd21b866fffd630', 1),
(3, 'add_idx_snapshots', '2026-11-28 12:00:00', 1, X'c13e51745e6f2d3e49f01fc82df68e88e91feabfa0a28507d658bb85b4c5cb81354ac8b23eb1038b175b1ae66311980a', 1),
(4, 'add_indexer_sync', '2026-11-28 12:00:00', 1, X'eeb9b2d07c3827f326feaed6651f587f177c2312c701d72f321c2d1a132bcd962fc914b39b12a34694003033bf29882b', 1),
(5, 'workspace_inventory', '2026-11-28 12:00:00', 1, X'c47dc6bc54f25ad6395edbf231a84399c64d0b497aabcb4ab65d9f6a2f0fd8100c423e13524b8cd3b7c6b960192601b8', 1);
CREATE TABLE "meta" (space_id VARCHAR PRIMARY KEY NOT NULL);
CREATE TABLE "snapshots" (
doc_id VARCHAR PRIMARY KEY NOT NULL,
data BLOB NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_at TIMESTAMP NOT NULL
);
CREATE TABLE "updates" (
doc_id VARCHAR NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
data BLOB NOT NULL,
PRIMARY KEY (doc_id, created_at)
);
CREATE TABLE "clocks" (
doc_id VARCHAR PRIMARY KEY NOT NULL,
timestamp TIMESTAMP NOT NULL
);
CREATE TABLE "blobs" (
key VARCHAR PRIMARY KEY NOT NULL,
data BLOB NOT NULL,
mime VARCHAR NOT NULL,
size INTEGER NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
deleted_at TIMESTAMP
);
CREATE TABLE "peer_clocks" (
peer VARCHAR NOT NULL,
doc_id VARCHAR NOT NULL,
remote_clock TIMESTAMP NOT NULL DEFAULT 0,
pulled_remote_clock TIMESTAMP NOT NULL DEFAULT 0,
pushed_clock TIMESTAMP NOT NULL DEFAULT 0,
inventory_kind TEXT,
lifecycle TEXT,
lifecycle_changed_at INTEGER,
pending_create BOOLEAN NOT NULL DEFAULT FALSE,
inventory_ready BOOLEAN NOT NULL DEFAULT FALSE,
cache_token INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (peer, doc_id)
);
CREATE INDEX peer_clocks_doc_id ON peer_clocks (doc_id);
CREATE TABLE "peer_blob_sync" (
peer VARCHAR NOT NULL,
blob_id VARCHAR NOT NULL,
uploaded_at TIMESTAMP,
PRIMARY KEY (peer, blob_id)
);
CREATE INDEX peer_blob_sync_peer ON peer_blob_sync (peer);
CREATE TABLE idx_snapshots (
index_name TEXT PRIMARY KEY NOT NULL,
data BLOB NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL
);
CREATE TABLE "indexer_sync" (
doc_id VARCHAR PRIMARY KEY NOT NULL,
indexed_clock TIMESTAMP NOT NULL DEFAULT 0,
indexer_version INTEGER NOT NULL DEFAULT 0
);
INSERT INTO meta (space_id) VALUES ('ws-0275-drill');
"""
requireS3(sqlite3_exec(rawDb, ddl, nil, nil, nil) == SQLITE_OK, "0.27.5 schema DDL must succeed")
// Genuine JavaScript Yjs (13.6.x) V1 updates for root workspace `ws-0275-drill` & page `doc-0275` (`para-0275-1` = "Seeded in 0.27.5"):
let yjsRootV1 = Data(
base64Encoded: "AQcFACcBBG1ldGEFcGFnZXMABwAFAAEoAAUBAmlkAXcIZG9jLTAyNzUoAAUBBXRpdGxlAXcUMC4yNy41IEV4aXN0aW5nIE5vdGUoAAUBCmNyZWF0ZURhdGUBe0J6IiMYOAAAJwAFAQR0YWdzACkBBnNwYWNlcwhkb2MtMDI3NQhkb2MtMDI3NXYAAA=="
)!
let yjsPageV1 = Data(
base64Encoded: "AR8FACcBBmJsb2NrcwlwYWdlLTAyNzUBKAAFAAZzeXM6aWQBdwlwYWdlLTAyNzUoAAUAC3N5czpmbGF2b3VyAXcLYWZmaW5lOnBhZ2UoAAUAC3N5czp2ZXJzaW9uAX0CJwAFAApwcm9wOnRpdGxlAgQABQQUMC4yNy41IEV4aXN0aW5nIE5vdGUnAAUADHN5czpjaGlsZHJlbgAIAAUZAncMc3VyZmFjZS0wMjc1dwlub3RlLTAyNzUnAQZibG9ja3MMc3VyZmFjZS0wMjc1ASgABRwGc3lzOmlkAXcMc3VyZmFjZS0wMjc1KAAFHAtzeXM6Zmxhdm91cgF3DmFmZmluZTpzdXJmYWNlKAAFHAtzeXM6dmVyc2lvbgF9BScABRwMc3lzOmNoaWxkcmVuACcABRwNcHJvcDplbGVtZW50cwEnAQZibG9ja3MJbm90ZS0wMjc1ASgABSIGc3lzOmlkAXcJbm90ZS0wMjc1KAAFIgtzeXM6Zmxhdm91cgF3C2FmZmluZTpub3RlKAAFIgtzeXM6dmVyc2lvbgF9ASgABSIJcHJvcDp4eXdoAXcNWzAsMCw4MDAsNDAwXSgABSIKcHJvcDppbmRleAF3AmEwKAAFIhBwcm9wOmRpc3BsYXlNb2RlAXcEYm90aCcABSIMc3lzOmNoaWxkcmVuAAgABSkBdwtwYXJhLTAyNzUtMScBBmJsb2NrcwtwYXJhLTAyNzUtMQEoAAUrBnN5czppZAF3C3BhcmEtMDI3NS0xKAAFKwtzeXM6Zmxhdm91cgF3EGFmZmluZTpwYXJhZ3JhcGgoAAUrC3N5czp2ZXJzaW9uAX0BKAAFKwlwcm9wOnR5cGUBdwR0ZXh0JwAFKwlwcm9wOnRleHQCBAAFMBBTZWVkZWQgaW4gMC4yNy41JwAFKwxzeXM6Y2hpbGRyZW4AAA=="
)!
let seedRows: [(String, String, Data)] = [
("ws-0275-drill", "2026-11-28 12:00:01.000", yjsRootV1),
("doc-0275", "2026-11-28 12:00:02.000", yjsPageV1),
]
let sqlTransient = unsafeBitCast(-1, to: sqlite3_destructor_type.self)
for (docId, tsText, bin) in seedRows {
var stmt: OpaquePointer?
requireS3(
sqlite3_prepare_v2(rawDb, "INSERT INTO updates (doc_id, created_at, data) VALUES (?1, ?2, ?3);", -1, &stmt, nil) == SQLITE_OK,
"prepare INSERT INTO updates"
)
_ = docId.withCString { sqlite3_bind_text(stmt, 1, $0, -1, sqlTransient) }
_ = tsText.withCString { sqlite3_bind_text(stmt, 2, $0, -1, sqlTransient) }
_ = bin.withUnsafeBytes { raw in
sqlite3_bind_blob(stmt, 3, raw.baseAddress, Int32(bin.count), sqlTransient)
}
requireS3(sqlite3_step(stmt) == SQLITE_DONE, "step INSERT INTO updates for \(docId)")
sqlite3_finalize(stmt)
var clkStmt: OpaquePointer?
requireS3(
sqlite3_prepare_v2(rawDb, "INSERT INTO clocks (doc_id, timestamp) VALUES (?1, ?2);", -1, &clkStmt, nil) == SQLITE_OK,
"prepare INSERT INTO clocks"
)
_ = docId.withCString { sqlite3_bind_text(clkStmt, 1, $0, -1, sqlTransient) }
_ = tsText.withCString { sqlite3_bind_text(clkStmt, 2, $0, -1, sqlTransient) }
requireS3(sqlite3_step(clkStmt) == SQLITE_DONE, "step INSERT INTO clocks for \(docId)")
sqlite3_finalize(clkStmt)
}
requireS3(sqlite3_exec(rawDb, "PRAGMA wal_checkpoint(FULL);", nil, nil, nil) == SQLITE_OK, "0.27.5 seed WAL checkpoint")
}
let probeHostWindow = UIWindow(frame: CGRect(x: 0, y: 0, width: 390, height: 844))
probeHostWindow.rootViewController = UIViewController()
probeHostWindow.makeKeyAndVisible()
defer { probeHostWindow.isHidden = true }
// 1b) Deterministic fail-closed probe timeout test (0ms wall-clock via injected timeoutScheduler):
// when LegacyLocalStorageProbe fails/times out, HostBootstrapCoordinator MUST fail closed
// (`imported == false`, `canCreateDefaultWorkspace == false`, zero SQLite mounts or deletions)
// and remain retryable on next launch.
do {
let failingProbe = LegacyLocalStorageProbe(
timeoutScheduler: { _, onTimeout in
onTimeout()
return {}
},
hostWindowProvider: { probeHostWindow }
)
let failClosedCoord = HostBootstrapCoordinator(documentsDirectory: tmpDocs, probe: failingProbe)
var sawTimeout = false
do {
_ = try await failClosedCoord.bootstrapFromLegacyStorage()
} catch let err as LegacyLocalStorageProbeError where err == .timedOut {
sawTimeout = true
}
requireS3(sawTimeout, "Deterministic probe timeout must throw LegacyLocalStorageProbeError.timedOut")
requireS3(
!failClosedCoord.imported
&& !failClosedCoord.canCreateDefaultWorkspace
&& failClosedCoord.mountedWorkspacesSnapshot().isEmpty
&& failClosedCoord.allowlistedLocalIds.isEmpty
&& failClosedCoord.lastSnapshot == nil
&& FileManager.default.fileExists(atPath: dbFile.path),
"Timed-out LegacyLocalStorageProbe must fail closed with imported=false, canCreateDefaultWorkspace=false, zero mounts, and untouched legacy DB"
)
requireS3(
probeHostWindow.subviews.allSatisfy { !($0 is WKWebView) },
"LegacyLocalStorageProbe.finish() must detach hidden WKWebView from host window even on timeout"
)
}
let probe = LegacyLocalStorageProbe(hostWindowProvider: { probeHostWindow })
let seeded = try await probe.writeBackLegacyLocalStorage(
set: [
"affine-local-workspace": "[\"ws-0275-drill\"]",
"theme": "light",
"last_workspace_id": "ws-0275-drill",
],
remove: []
)
requireS3(seeded.origin == "capacitor://localhost" && seeded.idbAccessCount == 0, "0.27.5 seed must run on capacitor://localhost with 0 IDB")
requireS3(
probeHostWindow.subviews.allSatisfy { !($0 is WKWebView) },
"LegacyLocalStorageProbe.finish() must detach hidden WKWebView from host window after writeBack"
)
// 2) New host captures real WKWebView sentinel, mounts `<Documents>/workspaces/workspace/local/ws-0275-drill.db` in place, edits existing doc & checkpoints WAL.
let coordinator = HostBootstrapCoordinator(documentsDirectory: tmpDocs, probe: probe)
let disp = try await coordinator.bootstrapFromLegacyStorage()
requireS3(
coordinator.imported && !coordinator.canCreateDefaultWorkspace,
"Bootstrapped existing user must set imported=true and canCreateDefaultWorkspace=false"
)
requireS3(disp.status == "existing_user" && disp.state.localWorkspaceIds == ["ws-0275-drill"], "new host must import ws-0275-drill from real WKWebView")
guard let ws = coordinator.workspace(id: "ws-0275-drill") else {
requireS3(false, "ws-0275-drill must mount in place")
return
}
let missingEdit = ws.editParagraphText(
docId: "non-existent-doc",
blockId: "p-1",
utf16Index: 0,
deleteLen: 0,
insertText: "must fail",
clientId: 7,
nowMs: 1_795_880_000_000
)
requireS3(missingEdit == nil, "editParagraphText must fail on non-existent document instead of auto-creating")
let editBytes = ws.editParagraphText(
docId: "doc-0275",
blockId: "para-0275-1",
utf16Index: 0,
deleteLen: 16,
insertText: "Edited in native 0.28",
clientId: 7,
nowMs: 1_795_880_000_000
)
requireS3(editBytes != nil && !editBytes!.isEmpty, "in-place SQLite edit on seeded 0.27.5 block must emit CRDT update")
requireS3(coordinator.checkpointAllPassive(), "PASSIVE WAL checkpoint must succeed")
// 3) Add a new local workspace & plan rollback write-back -> write back to real WKWebView.
try coordinator.applyLocalWorkspaceAllowlist(["ws-0275-drill", "ws-0275-added"])
let plan = try coordinator.buildRollbackWriteBackPlan()
requireS3(
(plan.set["affine-local-workspace"] ?? "").contains("ws-0275-added"),
"rollback writeback plan must include ws-0275-added"
)
let writtenBack = try await probe.writeBackLegacyLocalStorage(set: plan.set, remove: plan.remove)
requireS3(writtenBack.idbAccessCount == 0, "rollback writeback must keep idbAccessCount == 0")
coordinator.closeAll()
// 4) Simulated old 0.27.5 shell reads back from real WKWebView + re-opens in-place SQLite DB.
let oldShellReadback = try await probe.capture()
requireS3(
(oldShellReadback.entries["affine-local-workspace"] ?? "").contains("ws-0275-drill")
&& (oldShellReadback.entries["affine-local-workspace"] ?? "").contains("ws-0275-added"),
"old 0.27.5 WKWebView must read back both original and added workspaces"
)
let verifyCoord = HostBootstrapCoordinator(documentsDirectory: tmpDocs)
try verifyCoord.applyLocalWorkspaceAllowlist(["ws-0275-drill"])
let reopenedWs = verifyCoord.workspace(id: "ws-0275-drill")
let reopenedDiff = reopenedWs?.exportPendingDiff(docId: "doc-0275", remoteStateVector: nil)
let reopenedSnap = reopenedWs?.readPageSnapshotJson(docId: "doc-0275", clientId: 7) ?? ""
requireS3(
reopenedDiff != nil && !reopenedDiff!.isEmpty && reopenedSnap.contains("Edited in native 0.28"),
"old 0.27.5 SQLite workspace must preserve native-edited doc content intact (snap=\(reopenedSnap))"
)
verifyCoord.closeAll()
print("PASS [7/7]: 0.27.5 real WKWebView + in-place SQLite same-signature upgrade & rollback readback drill passed")
}
}
@@ -0,0 +1,239 @@
//! Deterministic `0.27.5` same-signature upgrade and exception-rollback writeback drill.
//!
//! Exercises realistic `0.27.5` Capacitor WebView persisted state for both iOS
//! (`capacitor://localhost`) and Android (`https://localhost`):
//! - Normal upgrade: positive sentinel -> allowlist-only workspace discovery (zero disk scan) ->
//! mutation -> lossless rollback writeback + readback verification.
//! - Unready WebView / wrong origin: fail-closed (no default workspace created, no data wiped).
//! - Corrupt allowlist + noise keys: preserved verbatim on upgrade and rollback writeback.
//! - Downgrade re-import: written-back `localStorage` map re-parses cleanly in `0.27.5`.
use std::collections::BTreeMap;
use serde_json::json;
use super::{
KEY_AFFINE_SETTINGS, KEY_I18N_LNG, KEY_LAST_WORKSPACE_FLAVOUR, KEY_LAST_WORKSPACE_ID,
KEY_LOCAL_WORKSPACE_LIST, KEY_SERVER_LIST, KEY_THEME, LegacyImportError,
LegacyLocalStorageSnapshot, LegacyServerMetadata, LocalStorageMutation, WebViewStorageSentinel,
build_writeback_changeset, import_from_sentinel, verify_writeback_readback,
};
/// Result of one simulated `0.27.5` same-signature upgrade -> mutation -> rollback drill.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct UpgradeRollbackDrillReport {
pub imported_local_ids: Vec<String>,
pub mutations: Vec<LocalStorageMutation>,
pub readback_verified: bool,
pub rolled_back_storage: BTreeMap<String, String>,
pub downgraded_snapshot: LegacyLocalStorageSnapshot,
}
/// Applies `mutations` onto a simulated WebView `localStorage` map in place.
pub fn apply_mutations_to_storage(
storage: &mut BTreeMap<String, String>,
mutations: &[LocalStorageMutation],
) {
for mutation in mutations {
match mutation {
LocalStorageMutation::Set { key, value } => {
storage.insert(key.clone(), value.clone());
}
LocalStorageMutation::Remove { key } => {
storage.remove(key);
}
}
}
}
/// Runs a full deterministic `0.27.5` upgrade + mutation + rollback writeback + downgrade
/// re-parse drill against a simulated WebView `localStorage` map.
pub fn run_upgrade_rollback_drill<F>(
origin: &str,
allowed_origins: &[&str],
initial_storage: &BTreeMap<String, String>,
mutate_native: F,
) -> Result<UpgradeRollbackDrillReport, LegacyImportError>
where
F: FnOnce(&mut LegacyLocalStorageSnapshot),
{
let keys: Vec<String> = initial_storage.keys().cloned().collect();
let entries: BTreeMap<String, String> = initial_storage
.iter()
.filter(|(k, _)| super::is_permitted_sentinel_entry_key(k))
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
let sentinel = WebViewStorageSentinel {
origin: origin.to_string(),
length: initial_storage.len(),
keys,
entries,
};
let (_eval, before_snapshot) = import_from_sentinel(&sentinel, allowed_origins)?;
let imported_local_ids = before_snapshot.local_workspace_ids.clone();
let mut after_snapshot = before_snapshot.clone();
mutate_native(&mut after_snapshot);
let mutations = build_writeback_changeset(&before_snapshot, &after_snapshot)?;
let mut rolled_back_storage = initial_storage.clone();
apply_mutations_to_storage(&mut rolled_back_storage, &mutations);
let readback = verify_writeback_readback(&mutations, &rolled_back_storage);
let post_keys: Vec<String> = rolled_back_storage.keys().cloned().collect();
let post_entries: BTreeMap<String, String> = rolled_back_storage
.iter()
.filter(|(k, _)| super::is_permitted_sentinel_entry_key(k))
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
let post_sentinel = WebViewStorageSentinel {
origin: origin.to_string(),
length: rolled_back_storage.len(),
keys: post_keys,
entries: post_entries,
};
let (_post_eval, downgraded_snapshot) = import_from_sentinel(&post_sentinel, allowed_origins)?;
Ok(UpgradeRollbackDrillReport {
imported_local_ids,
mutations,
readback_verified: readback.is_ok(),
rolled_back_storage,
downgraded_snapshot,
})
}
/// Builds a realistic `0.27.5` WebView `localStorage` fixture with local workspaces,
/// self-hosted server list/config/auth, cloud cache, feature flags, settings, and noise keys.
pub fn sample_0275_storage_fixture() -> BTreeMap<String, String> {
let mut map = BTreeMap::new();
map.insert(
KEY_LOCAL_WORKSPACE_LIST.to_string(),
r#"["ws-local-01","ws-local-02"]"#.to_string(),
);
map.insert(
KEY_SERVER_LIST.to_string(),
serde_json::to_string(&vec![LegacyServerMetadata {
id: "selfhost-1".to_string(),
base_url: "https://affine.corp.example".to_string(),
}])
.unwrap(),
);
map.insert(
"global-state:serverConfig:selfhost-1".to_string(),
json!({"serverName": "Corp AFFiNE", "features": ["copilot"]}).to_string(),
);
map.insert(
"global-state:selfhost-1-auth".to_string(),
json!({"userId": "u-42", "email": "lin@example.com"}).to_string(),
);
map.insert(
"global-state:cloud-workspace:u-42".to_string(),
r#"[{"id":"cloud-ws-1"}]"#.to_string(),
);
map.insert("affine-flag:enable_ai".to_string(), "true".to_string());
map.insert(
"global-state:affine-flag:mobile_v2".to_string(),
"true".to_string(),
);
map.insert(KEY_I18N_LNG.to_string(), "en".to_string());
map.insert(KEY_LAST_WORKSPACE_ID.to_string(), "ws-local-01".to_string());
map.insert(KEY_LAST_WORKSPACE_FLAVOUR.to_string(), "local".to_string());
map.insert(
KEY_AFFINE_SETTINGS.to_string(),
json!({"fontStyle": "Sans"}).to_string(),
);
map.insert(KEY_THEME.to_string(), "dark".to_string());
// Unrelated Capacitor/third-party noise key that must remain untouched across rollback.
map.insert("capacitor_device_hint".to_string(), "keep-me".to_string());
map
}
#[cfg(test)]
mod tests {
use super::*;
use crate::SentinelFailureReason;
#[test]
fn ios_and_android_0275_same_signature_upgrade_and_rollback_drill() {
for origin in ["capacitor://localhost", "https://localhost"] {
let initial = sample_0275_storage_fixture();
let report = run_upgrade_rollback_drill(origin, &[origin], &initial, |state| {
state.local_workspace_ids.push("ws-native-03".to_string());
state.theme = Some("light".to_string());
state.last_workspace_id = Some("ws-native-03".to_string());
})
.expect("normal 0.27.5 upgrade drill must succeed");
assert_eq!(
report.imported_local_ids,
vec!["ws-local-01", "ws-local-02"]
);
assert!(report.readback_verified);
assert_eq!(
report
.rolled_back_storage
.get("capacitor_device_hint")
.map(String::as_str),
Some("keep-me"),
"noise keys outside allowlist must never be deleted on rollback"
);
assert_eq!(
report.downgraded_snapshot.local_workspace_ids,
vec!["ws-local-01", "ws-local-02", "ws-native-03"]
);
assert_eq!(report.downgraded_snapshot.theme.as_deref(), Some("light"));
assert_eq!(report.downgraded_snapshot.server_list[0].id, "selfhost-1");
assert!(
report
.downgraded_snapshot
.cloud_workspace_caches
.contains_key("global-state:cloud-workspace:u-42")
);
}
}
#[test]
fn drill_fails_closed_on_wrong_origin_and_preserves_corrupt_allowlist_verbatim() {
let initial = sample_0275_storage_fixture();
// Wrong origin must fail closed without clearing or mutating state.
let err = run_upgrade_rollback_drill(
"https://evil.example",
&["capacitor://localhost"],
&initial,
|_| {},
)
.expect_err("wrong origin must fail closed");
assert!(matches!(
err,
LegacyImportError::SentinelFailed(SentinelFailureReason::OriginMismatch { .. })
));
// Corrupt `affine-local-workspace` must not abort upgrade or trigger fresh install,
// and must round-trip verbatim on rollback writeback.
let mut corrupt = initial;
corrupt.insert(
KEY_LOCAL_WORKSPACE_LIST.to_string(),
"{not-an-array".to_string(),
);
let report = run_upgrade_rollback_drill(
"capacitor://localhost",
&["capacitor://localhost"],
&corrupt,
|state| {
assert!(state.has_local_workspace_key);
assert!(state.local_workspace_ids.is_empty());
state.theme = Some("system".to_string());
},
)
.expect("corrupt allowlist must be preserved verbatim");
assert!(report.readback_verified);
assert_eq!(
report
.rolled_back_storage
.get(KEY_LOCAL_WORKSPACE_LIST)
.map(String::as_str),
Some("{not-an-array")
);
}
}
@@ -5,6 +5,8 @@
#![forbid(unsafe_code)]
#[cfg(test)]
mod drill;
pub mod sentinel;
pub mod writeback;