Modern Apps git

← Modern-Apps.git

voxels: editors-only worlds, per-client signature checks, container and mob sync

Commit
87362fc2f04d11c3beda5c5bedcf2ff342996221
Author
Vayun Mathur <[email protected]>
When
2026-08-06 20:50 UTC (4 months ago)
Parents
4bbfb10

Diff

games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.ktindex 4996e246a5..5e9485463f 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/MainActivity.kt@@ -27,7 +27,9 @@ import com.vayunmathur.e2ee.Pqc import com.vayunmathur.library.ui.* import com.vayunmathur.library.util.GameHubComposeHook import kotlinx.coroutines.delay+import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.isActive+import kotlinx.coroutines.launch import kotlin.io.encoding.Base64 import org.json.JSONArray import org.json.JSONObject@@ -193,21 +195,26 @@ class MainActivity : ComponentActivity() {                 LaunchedEffect(online) {                     if (!online || !VoxelsNative.isAvailable) return@LaunchedEffect                     if (!VoxelsSync.init(this@MainActivity)) return@LaunchedEffect+                    val pumpScope = this                     val myId = VoxelsSync.deviceId                     try { VoxelsNative.nativeSetDevice(myId) } catch (_: Exception) {}                     val key = runCatching { Base64.decode(worldKeyB64) }.getOrNull() ?: return@LaunchedEffect                     val channel = "world:$sharedWorldId"                     // Owner bundle: the host is the owner; a client fetches it once to verify host ops.                     val ownerBundle: ByteArray? = if (netRole == 1) VoxelsSync.publicBundle else VoxelsSync.getKey(ownerDevice)-                    // Host builds the editor/member sets from the owner-signed roster to gate edits.-                    val editors = HashSet<String>().apply { add(ownerDevice); add(myId) }-                    val members = HashSet<String>().apply { add(ownerDevice); add(myId) }-                    if (netRole == 1) {-                        runCatching { VoxelsSync.fetchRoster(sharedWorldId, key, VoxelsSync.publicBundle) }.getOrNull()?.forEach { (id, r) ->-                            members.add(id)-                            if (r == VoxelsRoles.OWNER || r == VoxelsRoles.EDITOR) editors.add(id)+                    // Host: the authorized member set (all editors — no viewers) + each member's public+                    // bundle, so every client op is signature-verified, not just role-gated by id.+                    val roster = java.util.Collections.synchronizedSet(HashSet<String>())+                    val bundles = java.util.concurrent.ConcurrentHashMap<String, ByteArray>()+                    roster.add(ownerDevice); roster.add(myId)+                    VoxelsSync.publicBundle.let { bundles[myId] = it; bundles[ownerDevice] = it }+                    suspend fun refreshRoster() {+                        runCatching { VoxelsSync.fetchRoster(sharedWorldId, key, VoxelsSync.publicBundle) }.getOrNull()?.forEach { (id, _) ->+                            roster.add(id)+                            if (!bundles.containsKey(id)) VoxelsSync.getKey(id)?.let { bundles[id] = it }                         }                     }+                    if (netRole == 1) refreshRoster()                     // Verify + gate an incoming signed op, then hand the inner NetMsg to the engine.                     fun handleSignedOp(plain: String) {                         try {@@ -223,11 +230,17 @@ class MainActivity : ComponentActivity() {                                 val ok = runCatching { Pqc.verify(ob, ops.encodeToByteArray(), Base64.decode(sig)) }.getOrDefault(false)                                 if (!ok) return                             } else {-                                // Host gates by the owner-signed roster: viewers may join but not edit.-                                val type = runCatching { JSONObject(ops).optString("type") }.getOrDefault("")-                                val isEdit = type == "EditIntent" || type == "ChunkData" || type == "InvIntent" || type == "ContainerIntent"-                                val allowed = if (isEdit) editors.contains(author) else members.contains(author)-                                if (!allowed) return+                                // Host: author must be a rostered member AND the op must carry a valid+                                // signature from that member's bundle. On a cache miss, fetch it for+                                // next time and drop this op (the client resends as chunks stay dirty).+                                if (!roster.contains(author)) return+                                val ab = bundles[author]+                                if (ab == null) {+                                    pumpScope.launch(Dispatchers.IO) { runCatching { VoxelsSync.getKey(author) }.getOrNull()?.let { bundles[author] = it } }+                                    return+                                }+                                val ok = runCatching { Pqc.verify(ab, ops.encodeToByteArray(), Base64.decode(sig)) }.getOrDefault(false)+                                if (!ok) return                             }                             VoxelsNative.netPushInbound(ops)                         } catch (_: Exception) {}@@ -265,7 +278,11 @@ class MainActivity : ComponentActivity() {                             }                         },                     )+                    var rosterTick = 0                     while (isActive) {+                        // Periodically re-read the roster so newly-invited editors are accepted mid-session.+                        rosterTick+++                        if (netRole == 1 && rosterTick % 125 == 0) refreshRoster()                         val out = try { VoxelsNative.netDrainOutbound() } catch (_: Exception) { "[]" }                         try {                             val arr = JSONArray(out)@@ -337,6 +354,8 @@ class MainActivity : ComponentActivity() {                                     30 -> { // chest                                         containerJson = try { VoxelsNative.getContainerJson() } catch (_: Exception) { """{"slots":[]}""" }                                         chestOpen = true+                                        // Online clients mirror host state: ask for the real contents.+                                        if (online) try { VoxelsNative.netRequestContainer() } catch (_: Exception) {}                                         com.vayunmathur.games.voxels.util.SoundFx.playPlace()                                     }                                     41 -> com.vayunmathur.games.voxels.util.SoundFx.playPlace() // ignited a portal
games/voxels/src/main/java/com/vayunmathur/games/voxels/MenuActivity.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/MenuActivity.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/MenuActivity.ktindex 9ba5f1cd37..bf94a53e7a 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/MenuActivity.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/MenuActivity.kt@@ -147,7 +147,7 @@ class MenuActivity : ComponentActivity() {                             ShareOnlineDialog(                                 world = world,                                 onDismiss = { shareTarget = null },-                                onSend = { recipient, role ->+                                onSend = { recipient ->                                     shareTarget = null                                     scope.launch {                                         val ok = withContext(Dispatchers.IO) {@@ -156,15 +156,15 @@ class MenuActivity : ComponentActivity() {                                                 val key = Base64.decode(world.meta.keyB64)                                                 val sent = VoxelsSync.sendInvite(                                                     recipient, world.meta.worldId, key,-                                                    world.meta.name, world.meta.seed, role,+                                                    world.meta.name, world.meta.seed, VoxelsRoles.EDITOR,                                                     Base64.encode(VoxelsSync.publicBundle), deviceId,                                                 )-                                                // Publish the owner-signed roster so the host can gate edits by role.+                                                // Publish the owner-signed roster so the host can gate edits.                                                 if (sent) VoxelsSync.recordMembers(                                                     world.meta.worldId, key,                                                     listOf(                                                         VoxelsSync.Member(deviceId, "", VoxelsRoles.OWNER),-                                                        VoxelsSync.Member(recipient, "", role),+                                                        VoxelsSync.Member(recipient, "", VoxelsRoles.EDITOR),                                                     ),                                                 )                                                 sent
games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/MenuScreens.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/MenuScreens.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/MenuScreens.ktindex 673b472cb7..6d40c65dbb 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/MenuScreens.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/MenuScreens.kt@@ -178,16 +178,15 @@ private fun WorldRow(     } } -// Owner-only dialog: invite a device by id, choosing whether they can build (editor) or only look-// (viewer). Mirrors office's ShareOnlineDialog.+// Owner-only dialog: invite a device by id. Voxels worlds have no viewers — everyone invited can+// build — so there's no role choice. Mirrors office's ShareOnlineDialog. @Composable fun ShareOnlineDialog(     world: WorldInfo,     onDismiss: () -> Unit,-    onSend: (recipient: String, role: String) -> Unit,+    onSend: (recipient: String) -> Unit, ) {     var recipient by remember { mutableStateOf("") }-    var role by remember { mutableStateOf(VoxelsRoles.EDITOR) }     Dialog(onDismissRequest = onDismiss) {         Card(Modifier.fillMaxWidth().padding(8.dp)) {             Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {@@ -200,16 +199,9 @@ fun ShareOnlineDialog(                     singleLine = true,                     modifier = Modifier.fillMaxWidth()                 )-                Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {-                    val editorSel = role == VoxelsRoles.EDITOR-                    if (editorSel) Button(onClick = { role = VoxelsRoles.EDITOR }, modifier = Modifier.weight(1f)) { Text(stringResource(R.string.role_editor)) }-                    else OutlinedButton(onClick = { role = VoxelsRoles.EDITOR }, modifier = Modifier.weight(1f)) { Text(stringResource(R.string.role_editor)) }-                    if (!editorSel) Button(onClick = { role = VoxelsRoles.VIEWER }, modifier = Modifier.weight(1f)) { Text(stringResource(R.string.role_viewer)) }-                    else OutlinedButton(onClick = { role = VoxelsRoles.VIEWER }, modifier = Modifier.weight(1f)) { Text(stringResource(R.string.role_viewer)) }-                }                 Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) {                     OutlinedButton(onClick = onDismiss, modifier = Modifier.weight(1f)) { Text(stringResource(UiR.string.cancel)) }-                    Button(onClick = { onSend(recipient.trim(), role) }, enabled = recipient.isNotBlank(), modifier = Modifier.weight(1f)) { Text(stringResource(R.string.send_invite)) }+                    Button(onClick = { onSend(recipient.trim()) }, enabled = recipient.isNotBlank(), modifier = Modifier.weight(1f)) { Text(stringResource(R.string.send_invite)) }                 }             }         }
games/voxels/src/main/java/com/vayunmathur/games/voxels/util/VoxelsNative.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/VoxelsNative.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/VoxelsNative.ktindex 623aee6925..7fe845fd9d 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/VoxelsNative.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/VoxelsNative.kt@@ -68,4 +68,6 @@ object VoxelsNative {     external fun netDrainOutbound(): String     // Remote players for the HUD/avatars: [{device,x,y,z,yaw}].     external fun getPeersJson(): String+    // Client → host: ask for the currently-open chest's contents (host replies with ContainerSync).+    external fun netRequestContainer() }
games/voxels/src/main/java/com/vayunmathur/games/voxels/util/VoxelsSync.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/VoxelsSync.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/VoxelsSync.ktindex 3796a2283b..0d1b456c7e 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/VoxelsSync.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/VoxelsSync.kt@@ -337,11 +337,10 @@ object VoxelsSync {     ) } -/** World access roles — enforced entirely client-side via signature checks (relay is a pure log). */+/** World access roles — enforced entirely client-side via signature checks (relay is a pure log).+ *  Voxels worlds have no viewers: the owner (host) and invited editors can all build. */ object VoxelsRoles {     const val OWNER = "owner"     const val EDITOR = "editor"-    const val VIEWER = "viewer"-    const val REVOKED = "revoked"     fun canEdit(role: String) = role == OWNER || role == EDITOR }
games/voxels/src/main/res/values/strings.xml
diff --git a/games/voxels/src/main/res/values/strings.xml b/games/voxels/src/main/res/values/strings.xmlindex 125fa1b40a..cbb844e4e2 100644--- a/games/voxels/src/main/res/values/strings.xml+++ b/games/voxels/src/main/res/values/strings.xml@@ -69,8 +69,6 @@     <string name="shared_with_you">Shared with you</string>     <string name="share_world">Share world</string>     <string name="recipient_device_id">Recipient device ID</string>-    <string name="role_editor">Editor (can build)</string>-    <string name="role_viewer">Viewer (read-only)</string>     <string name="send_invite">Send invite</string>     <string name="invite_sent">Invite sent.</string>     <string name="invite_failed">Couldn\'t send the invite — check the device ID and your connection.</string>
games/voxels/src/main/rust/src/engine.rs
diff --git a/games/voxels/src/main/rust/src/engine.rs b/games/voxels/src/main/rust/src/engine.rsindex 415b6ff94b..42c3a44f04 100644--- a/games/voxels/src/main/rust/src/engine.rs+++ b/games/voxels/src/main/rust/src/engine.rs@@ -573,6 +573,11 @@ pub fn tick_and_render() {          // --- Mobs: AI/physics tick, spawn/despawn near the player. ---         let player_pos = state.player.pos;+        if crate::net::is_client() {+            // The host owns mob AI, spawning and combat; a client just eases its mobs toward the+            // latest host snapshot (projectiles arrive via ProjSnapshot).+            crate::net::interpolate_mobs(state, dt);+        } else {         {             let chunks = &state.chunks;             let terrain = crate::entity::Terrain {@@ -686,6 +691,7 @@ pub fn tick_and_render() {                 state.spawn_rng = rng;             }         }+        }         // Death: burn one heart of max HP (floored) and respawn at world spawn — the "lives" system.         if state.player.dead {             use crate::world::chunk::CHUNK_HEIGHT;@@ -870,7 +876,13 @@ pub fn get_health_json() -> String { cref(&HEALTH_CACHE, "{}").lock().map(|c| c. pub fn get_smelt_json() -> String { cref(&SMELT_CACHE, "{}").lock().map(|c| c.clone()).unwrap_or_else(|_| "{}".into()) } pub fn get_ambience_json() -> String { cref(&AMBIENCE_CACHE, "{}").lock().map(|c| c.clone()).unwrap_or_else(|_| "{}".into()) } -pub fn inventory_move(from: usize, to: usize) { with_engine(|s| s.inventory.move_item(from, to)); }+pub fn inventory_move(from: usize, to: usize) {+    with_engine(|s| {+        // Clients send the move as an intent; the host applies it and echoes the inventory back.+        if crate::net::is_client() { crate::net::client_inv_intent(from as u32, to as u32); return; }+        s.inventory.move_item(from, to)+    });+} pub fn inventory_give(id: Id) { with_engine(|s| s.inventory.give(id)); } pub fn inventory_craft(recipe: usize) -> bool {     with_engine(|s| {@@ -1653,12 +1665,18 @@ pub fn get_container_json() -> String { pub fn container_take(idx: usize) -> bool {     with_engine(|state| {         let Some(key) = state.open_chest else { return false; };+        // Clients don't mutate authoritative state: send the intent and wait for the host's sync.+        if crate::net::is_client() {+            crate::net::client_container_intent([key.0 as i32, key.1, key.2, key.3], true, idx as u32);+            return false;+        }         let Some(slot) = state.containers.slot_mut(key, idx) else { return false; };         if slot.id == 0 { return false; }         let mut held = *slot;         state.inventory.take_from(&mut held);         let moved = held.count < slot.count || held.id == 0;         if let Some(slot) = state.containers.slot_mut(key, idx) { *slot = held; }+        if moved { crate::net::host_container_changed(state, key); }         moved     }).unwrap_or(false) }@@ -1666,6 +1684,10 @@ pub fn container_take(idx: usize) -> bool { pub fn container_put(inv_idx: usize) -> bool {     with_engine(|state| {         let Some(key) = state.open_chest else { return false; };+        if crate::net::is_client() {+            crate::net::client_container_intent([key.0 as i32, key.1, key.2, key.3], false, inv_idx as u32);+            return false;+        }         if inv_idx >= crate::inventory::SLOTS { return false; }         let s = state.inventory.slots[inv_idx];         if s.id == 0 { return false; }@@ -1676,11 +1698,24 @@ pub fn container_put(inv_idx: usize) -> bool {         } else {             crate::inventory::InvSlot::default()         };+        crate::net::host_container_changed(state, key);         true     }).unwrap_or(false) } pub fn close_container() { with_engine(|s| s.open_chest = None); } +/// Client: ask the host to send the currently-open chest's contents (so a freshly-opened chest+/// shows what's really inside rather than an empty grid). No-op offline or on the host.+pub fn request_container_sync() {+    with_engine(|state| {+        if let Some(key) = state.open_chest {+            if crate::net::is_client() {+                crate::net::client_container_intent([key.0 as i32, key.1, key.2, key.3], true, u32::MAX);+            }+        }+    });+}+ // ---- Blessings ---- // Bind the blessing held in an inventory slot, consuming the charm. Fails if the slot doesn't hold // a blessing, it's already bound, or every attunement slot is taken.
games/voxels/src/main/rust/src/lib.rs
diff --git a/games/voxels/src/main/rust/src/lib.rs b/games/voxels/src/main/rust/src/lib.rsindex 1bf3e955d8..b584d335fc 100644--- a/games/voxels/src/main/rust/src/lib.rs+++ b/games/voxels/src/main/rust/src/lib.rs@@ -444,6 +444,13 @@ pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_getPe     match env.new_string(crate::net::peers_json()) { Ok(s) => s.into_raw(), Err(_) => null } } +#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_netRequestContainer<'l>(+    _env: JNIEnv<'l>, _class: JClass<'l>,+) {+    crate::engine::request_container_sync();+}+ #[cfg(test)] mod tests {     use crate::world::chunk::{Chunk, ChunkPos};
games/voxels/src/main/rust/src/net.rs
diff --git a/games/voxels/src/main/rust/src/net.rs b/games/voxels/src/main/rust/src/net.rsindex e480bef254..98c8e258dd 100644--- a/games/voxels/src/main/rust/src/net.rs+++ b/games/voxels/src/main/rust/src/net.rs@@ -146,8 +146,9 @@ pub enum NetMsg {     EditIntent { device: String, dim: u8, x: i32, y: i32, z: i32, id: Id, meta: u8, break_it: bool },     /// Client → host: an inventory move request.     InvIntent { device: String, from: u32, to: u32 },-    /// Client → host: a container take/put request.-    ContainerIntent { device: String, take: bool, idx: u32 },+    /// Client → host: a container take/put request against a specific chest. `key` is [dim,x,y,z];+    /// `idx == u32::MAX` is a pure "sync me this chest" request (no mutation).+    ContainerIntent { device: String, key: [i32; 4], take: bool, idx: u32 }, }  // ---- Shared state ----@@ -180,6 +181,20 @@ fn local_device() -> String { LOCAL_DEVICE.get_or_init(|| Mutex::new(String::new pub fn set_role(r: u8) { ROLE.store(r, Ordering::SeqCst); } pub fn role() -> u8 { ROLE.load(Ordering::SeqCst) } pub fn is_networked() -> bool { role() != ROLE_OFFLINE }+pub fn is_client() -> bool { role() == ROLE_CLIENT }+pub fn is_host() -> bool { role() == ROLE_HOST }++/// Client → host intent: an inventory move (the client mirrors host state, so it doesn't apply it+/// locally — the host applies and echoes the authoritative inventory back).+pub fn client_inv_intent(from: u32, to: u32) {+    enqueue(NetMsg::InvIntent { device: local_device(), from, to });+}++/// Client → host intent: a chest take/put (or, with `idx == u32::MAX`, a request to be sent the+/// chest's current contents).+pub fn client_container_intent(key: [i32; 4], take: bool, idx: u32) {+    enqueue(NetMsg::ContainerIntent { device: local_device(), key, take, idx });+}  pub fn set_local_device(id: String) {     if let Ok(mut d) = LOCAL_DEVICE.get_or_init(|| Mutex::new(String::new())).lock() { *d = id; }@@ -248,6 +263,78 @@ pub fn remote_player_poses() -> Vec<(Vec3, f32)> {     remote().lock().map(|m| m.values().map(|r| (r.pos, r.yaw)).collect()).unwrap_or_default() } +// ---- Client-side mob interpolation (host is authoritative; clients smooth between snapshots) ----++static MOB_TARGETS: OnceLock<Mutex<Vec<MobDto>>> = OnceLock::new();+fn mob_targets() -> &'static Mutex<Vec<MobDto>> { MOB_TARGETS.get_or_init(|| Mutex::new(Vec::new())) }++/// Client: adopt a host mob snapshot. The local list is rebuilt only when the population changes;+/// otherwise the existing mobs are kept and merely retargeted, so [interpolate_mobs] can ease them+/// into place instead of teleporting every snapshot.+fn set_mob_targets(state: &mut EngineState, dtos: Vec<MobDto>) {+    if state.mobs.len() != dtos.len() {+        state.mobs = dtos.iter().map(|d| d.to_mob()).collect();+    }+    if let Ok(mut t) = mob_targets().lock() { *t = dtos; }+}++/// Client tick: ease locally-held mobs toward the latest host snapshot (position + yaw).+pub fn interpolate_mobs(state: &mut EngineState, dt: f32) {+    let targets = match mob_targets().lock() { Ok(t) => t.clone(), Err(_) => return };+    if state.mobs.len() != targets.len() {+        state.mobs = targets.iter().map(|d| d.to_mob()).collect();+        return;+    }+    let a = (dt * 12.0).clamp(0.0, 1.0);+    for (m, t) in state.mobs.iter_mut().zip(targets.iter()) {+        m.pos = m.pos.lerp(t.pos, a);+        m.vel = t.vel;+        let mut d = t.yaw - m.yaw;+        while d > std::f32::consts::PI { d -= std::f32::consts::TAU; }+        while d < -std::f32::consts::PI { d += std::f32::consts::TAU; }+        m.yaw += d * a;+        m.health = t.health;+        m.max_health = t.max_health;+    }+}++// ---- Host-side container authority ----++/// Host: broadcast a chest's current contents so clients viewing it stay in sync.+fn host_broadcast_container(state: &EngineState, key: (u8, i32, i32, i32)) {+    let slots = state.containers.get(key).cloned().unwrap_or_default();+    enqueue(NetMsg::ContainerSync { key: [key.0 as i32, key.1, key.2, key.3], slots });+}++/// Host: apply a client's chest take/put against a specific chest (mirrors the engine's own+/// container_take/put, but keyed rather than using the host player's open chest).+fn apply_container_op(state: &mut EngineState, key: (u8, i32, i32, i32), take: bool, idx: usize) {+    if take {+        let Some(slot) = state.containers.slot_mut(key, idx) else { return };+        if slot.id == 0 { return; }+        let mut held = *slot;+        state.inventory.take_from(&mut held);+        if let Some(slot) = state.containers.slot_mut(key, idx) { *slot = held; }+    } else {+        if idx >= crate::inventory::SLOTS { return; }+        let s = state.inventory.slots[idx];+        if s.id == 0 { return; }+        let left = state.containers.add(key, s.id, s.count);+        if left < s.count {+            state.inventory.slots[idx] = if left > 0 {+                crate::inventory::InvSlot { id: s.id, count: left }+            } else {+                crate::inventory::InvSlot::default()+            };+        }+    }+}++/// Host: called from the engine's own container_take/put so other players see the change.+pub fn host_container_changed(state: &EngineState, key: (u8, i32, i32, i32)) {+    if is_host() { host_broadcast_container(state, key); }+}+ // Mark a chunk (and its edge neighbors) for remesh without going through the engine's edit-notify // hook — used when applying remote data so we don't echo it straight back out. fn dirty_chunk_and_neighbors(state: &mut EngineState, cx: i32, cz: i32) {@@ -301,6 +388,12 @@ pub fn apply_inbound(state: &mut EngineState) {             NetMsg::InvIntent { from, to, .. } if r == ROLE_HOST => {                 state.inventory.move_item(from as usize, to as usize);             }+            NetMsg::ContainerIntent { key, take, idx, .. } if r == ROLE_HOST => {+                let k = (key[0] as u8, key[1], key[2], key[3]);+                // idx == u32::MAX is a pure "send me this chest" request (no mutation).+                if idx != u32::MAX { apply_container_op(state, k, take, idx as usize); }+                host_broadcast_container(state, k);+            }             // A client's edited chunk, sent upstream: trust it (editor role was checked in Kotlin),             // apply, and re-mark it so the host rebroadcasts the authoritative version.             NetMsg::ChunkData { dim, cx, cz, data } if r == ROLE_HOST => {@@ -318,7 +411,7 @@ pub fn apply_inbound(state: &mut EngineState) {                 if dim == state.dim { apply_block(state, x, y, z, id, meta); }             }             NetMsg::MobSnapshot { mobs } if r == ROLE_CLIENT => {-                state.mobs = mobs.iter().map(|d| d.to_mob()).collect();+                set_mob_targets(state, mobs);             }             NetMsg::ProjSnapshot { projs } if r == ROLE_CLIENT => {                 state.projectiles = projs.iter().map(|d| d.to_proj()).collect();