diff --git a/mobile/android/app/src/main/java/dev/backplane/mobile/DataClient.kt b/mobile/android/app/src/main/java/dev/backplane/mobile/DataClient.kt index c05a110d97..9a0622d00d 100644 --- a/mobile/android/app/src/main/java/dev/backplane/mobile/DataClient.kt +++ b/mobile/android/app/src/main/java/dev/backplane/mobile/DataClient.kt @@ -1404,6 +1404,7 @@ object DataClient { c.optJSONArray("rooms")?.let { a -> rooms = (0 until a.length()).mapNotNull { a.optJSONObject(it) }.map { Room(it.optString("id"), it.optString("name"), it.optString("markShort"), it.optBoolean("delete")) } } + c.optJSONArray("swarms")?.let { Swarms.restore(it) } c.optJSONObject("shellHashes")?.let { h -> val next = HashMap() h.keys().forEach { k -> next[k] = h.optString(k) } @@ -1412,6 +1413,7 @@ object DataClient { listsLoaded = threads.isNotEmpty() || projects.isNotEmpty() || sections.isNotEmpty() } } + internal fun scheduleSave() = save() private fun save() { saveJob?.cancel() saveJob = scope.launch { @@ -1420,7 +1422,7 @@ object DataClient { val ps = projects; val ts = threads val fs = features.sorted() val sec = sectionsJson; val gto = groupsToJson - val bs = bots; val rs = rooms + val bs = bots; val rs = rooms; val sw = Swarms.rawJson val sh = HashMap(shellHashes) val recent = ts.take(20).map { it.id }.toSet() val es = entries.filterKeys { it in recent }.mapValues { (_, v) -> v.filter { !it.sending && !it.failed }.takeLast(40) } @@ -1433,6 +1435,7 @@ object DataClient { .apply { if (sec != null) put("sections", sec); if (gto != null) put("groupsTo", gto) } .put("bots", JSONArray(bs.map { JSONObject().put("id", it.id).put("name", it.name).put("thread", it.thread).put("uber", it.uber).put("markShort", it.mark).put("note", it.note).put("delete", it.delete).put("look", it.look).put("color", it.color).put("ask", JSONObject().put("title", it.ask.title).put("body", it.ask.body).put("yes", it.ask.yes)) })) .put("rooms", JSONArray(rs.map { JSONObject().put("id", it.id).put("name", it.name).put("markShort", it.mark).put("delete", it.delete) })) + .apply { if (sw != null) put("swarms", sw) } .put("shellHashes", JSONObject().also { o -> sh.forEach { (k, v) -> o.put(k, v) } }) runCatching { cacheFile(hub).writeText(j.toString()) } } diff --git a/mobile/android/app/src/main/java/dev/backplane/mobile/DataSwarm.kt b/mobile/android/app/src/main/java/dev/backplane/mobile/DataSwarm.kt index 09bfad7521..dad62bf862 100644 --- a/mobile/android/app/src/main/java/dev/backplane/mobile/DataSwarm.kt +++ b/mobile/android/app/src/main/java/dev/backplane/mobile/DataSwarm.kt @@ -113,10 +113,20 @@ object SwarmUi { object Swarms { var all by mutableStateOf>(emptyList()); private set var ticks by mutableStateOf>(emptyMap()); private set + internal var rawJson: JSONArray? = null; private set private var due = false fun on() = DataClient.has("swarm") - fun reset() { all = emptyList(); ticks = emptyMap() } - suspend fun load() { if (on()) runCatching { DataClient.call("swarm.list", JSONObject()) }.onSuccess { all = SwarmParse.list(it) } } + fun reset() { rawJson = null; all = emptyList(); ticks = emptyMap() } + internal fun restore(a: JSONArray?) { rawJson = a; all = a.objs(SwarmParse::swarm) } + suspend fun load() { + if (on()) runCatching { DataClient.call("swarm.list", JSONObject()) }.onSuccess { + val next = SwarmParse.list(it) + val changed = next != all + rawJson = it.optJSONArray("swarms") + all = next + if (changed) DataClient.scheduleSave() + } + } fun pushed(room: String) { ticks = ticks + (room to (ticks[room] ?: 0) + 1) if (due) return; due = true diff --git a/mobile/android/app/src/main/java/dev/backplane/mobile/DataViews.kt b/mobile/android/app/src/main/java/dev/backplane/mobile/DataViews.kt index 285b2e8ada..9e0b638fe2 100644 --- a/mobile/android/app/src/main/java/dev/backplane/mobile/DataViews.kt +++ b/mobile/android/app/src/main/java/dev/backplane/mobile/DataViews.kt @@ -183,6 +183,25 @@ internal fun DBar(title: String, back: (() -> Unit)?, titleMenu: (@Composable Co } } +@Composable +private fun BoxScope.ReconnectingPill() { + if (DataClient.conn == DataClient.Conn.CONNECTING && DataClient.restartText == null && (DataClient.listsLoaded || DataClient.sections.isNotEmpty() || DataClient.projects.isNotEmpty())) { + Row( + Modifier + .align(Alignment.BottomCenter) + .padding(bottom = 10.dp) + .background(dcs.surfaceContainerHigh, RectangleShape) + .border(BorderStroke(1.dp, dcs.outlineVariant), RectangleShape) + .padding(horizontal = 10.dp, vertical = 5.dp) + .testTag("conn.reconnecting"), + verticalAlignment = Alignment.CenterVertically, + ) { + DDot(dwarn, 6); Spacer(Modifier.width(6.dp)) + DMono(Msg.mobile_conn_reconnecting, dcs.onSurfaceVariant, 11) + } + } +} + @Composable private fun ConnBanner(hub: () -> Unit, settings: () -> Unit) { MigrateBanner() @@ -558,21 +577,7 @@ private fun HomeScreen(open: (String) -> Unit, settings: () -> Unit, hub: () -> } } } - if (DataClient.conn == DataClient.Conn.CONNECTING && DataClient.restartText == null && (DataClient.listsLoaded || DataClient.sections.isNotEmpty() || DataClient.projects.isNotEmpty())) { - Row( - Modifier - .align(Alignment.BottomCenter) - .padding(bottom = 10.dp) - .background(dcs.surfaceContainerHigh, RectangleShape) - .border(BorderStroke(1.dp, dcs.outlineVariant), RectangleShape) - .padding(horizontal = 10.dp, vertical = 5.dp) - .testTag("conn.reconnecting"), - verticalAlignment = Alignment.CenterVertically, - ) { - DDot(dwarn, 6); Spacer(Modifier.width(6.dp)) - DMono(Msg.mobile_conn_reconnecting, dcs.onSurfaceVariant, 11) - } - } + ReconnectingPill() } } DLine() @@ -620,6 +625,7 @@ private fun HomeScreen(open: (String) -> Unit, settings: () -> Unit, hub: () -> // a swarm's members are left out of their project's list: the project shows the swarm once (feature swarm) val threads = DataClient.threads.filter { !it.archived && it.id !in botThreads && !it.history && !(swarmsOn && it.swarm.isNotEmpty()) } val hist = DataClient.history + Box(Modifier.weight(1f).fillMaxWidth()) { if (projects.isEmpty() && threads.isEmpty() && hist.count == 0) { // no project yet: Bub still leads the list; the empty state and Add a project come under it LazyColumn(Modifier.fillMaxSize().testTag("home.list")) { @@ -706,6 +712,8 @@ private fun HomeScreen(open: (String) -> Unit, settings: () -> Unit, hub: () -> if (DataClient.rooms.isNotEmpty()) { item("rooms") { DMono(Msg.plane_heading_rooms, dfaint, 11, Modifier.fillMaxWidth().padding(start = 12.dp, top = 12.dp, bottom = 4.dp)) } items(DataClient.rooms, key = { "r:${it.id}" }) { r -> SidebarRow("#", r.name, onMachine(Msg.android_kind_room, r.mark), onLong = if (r.delete) ({ roomDelete = r }) else null) { openRoom(r) } } } } + ReconnectingPill() + } } // end !sectioned // Delete bot (a long press on a bot the hub offers it for): asked first, then `bot.delete` botDelete?.let { b -> BotDeleteDialog(b) { botDelete = null } } diff --git a/mobile/ios/Backplane/DataViews.swift b/mobile/ios/Backplane/DataViews.swift index 978e0198bb..664159069c 100644 --- a/mobile/ios/Backplane/DataViews.swift +++ b/mobile/ios/Backplane/DataViews.swift @@ -207,24 +207,10 @@ struct DataThreadsView: View { if !client.locks.isEmpty && !sectioned { DataLocksStrip(client: client, path: $path) } // (the sections leave the hub's locks out: backend work) if client.has("search"), !query.trimmingCharacters(in: .whitespaces).isEmpty { DataSearchResults(client: client, query: query, open: { path.append($0) }, openAt: { path.append($0) }) - } else if !client.hasCachedSidebar && client.failure.isEmpty { + } else if !client.hasCachedSidebar && client.failure.isEmpty && client.conn != .offline { DLoading(text: Tr.t(client.conn == .online ? "Loading…" : "Connecting to the hub…")) } else if sectioned { tabs } else { list } } - .overlay(alignment: .bottom) { - if showReconnectingPill { - HStack(spacing: 6) { - DDot(color: BackplaneDesign.warn, size: 6) - Text(Tr.k("mobile.conn.reconnecting")).dmono(11).foregroundStyle(BackplaneDesign.dim) - } - .padding(.horizontal, 10).padding(.vertical, 5) - .background(BackplaneDesign.raised) - .overlay(Rectangle().strokeBorder(BackplaneDesign.line, lineWidth: 1)) - .padding(.bottom, sectioned ? 58 : 14) - .allowsHitTesting(false) - .accessibilityIdentifier("data.connection.reconnecting") - } - } .background(BackplaneDesign.panel) .navigationBarTitleDisplayMode(.inline) .toolbarBackground(BackplaneDesign.panel, for: .navigationBar).toolbarBackground(.visible, for: .navigationBar) @@ -315,6 +301,21 @@ struct DataThreadsView: View { } } + @ViewBuilder private var reconnectingPill: some View { + if showReconnectingPill { + HStack(spacing: 6) { + DDot(color: BackplaneDesign.warn, size: 6) + Text(Tr.k("mobile.conn.reconnecting")).dmono(11).foregroundStyle(BackplaneDesign.dim) + } + .padding(.horizontal, 10).padding(.vertical, 5) + .background(BackplaneDesign.raised) + .overlay(Rectangle().strokeBorder(BackplaneDesign.line, lineWidth: 1)) + .padding(.bottom, 14) + .allowsHitTesting(false) + .accessibilityIdentifier("data.connection.reconnecting") + } + } + private var list: some View { ScrollViewReader { proxy in listBody .onChange(of: client.focusProject, initial: true) { _, id in @@ -324,6 +325,7 @@ struct DataThreadsView: View { Task { try? await Task.sleep(nanoseconds: 150_000_000); withAnimation { proxy.scrollTo("project." + id, anchor: .top) }; try? await Task.sleep(nanoseconds: 2_500_000_000); if flash == id { flash = "" } } } } + .overlay(alignment: .bottom) { reconnectingPill } } private var listBody: some View { List { @@ -396,6 +398,7 @@ struct DataThreadsView: View { } .listStyle(.plain).scrollContentBackground(.hidden).environment(\.defaultMinListRowHeight, 1) .background(BackplaneDesign.panel).refreshable { await client.refresh() }.accessibilityIdentifier("data.home.inbox") + .overlay(alignment: .bottom) { reconnectingPill } } @ViewBuilder private func inboxRow(_ r: DSecRow) -> some View { // a swarm that waits on the person opens the swarm's page @@ -432,6 +435,7 @@ struct DataThreadsView: View { } .listStyle(.plain).scrollContentBackground(.hidden).environment(\.defaultMinListRowHeight, 1) .background(BackplaneDesign.panel).refreshable { await client.refresh() }.accessibilityIdentifier("data.home.crew") + .overlay(alignment: .bottom) { reconnectingPill } } /// Bench: the projects as the hub sections them. Pinned and Recent (the ones the person was in last) are tall rows on top; the groups, All /// projects and Quiet are folds under them, so no one scrolls through every project to reach a board. @@ -455,6 +459,7 @@ struct DataThreadsView: View { } .listStyle(.plain).scrollContentBackground(.hidden).environment(\.defaultMinListRowHeight, 1) .background(BackplaneDesign.panel).refreshable { await client.refresh() }.accessibilityIdentifier("data.home.bench") + .overlay(alignment: .bottom) { reconnectingPill } } /// A project row of the Bench (and of the Inbox's Jump back in): a press opens its page, a long press its menu. private func projectRow(_ r: DSecRow, faded: Bool = false, tall: Bool = false) -> some View { diff --git a/native/host/src/data/open.rs b/native/host/src/data/open.rs index 0dacffcaa0..0dddcd2094 100644 --- a/native/host/src/data/open.rs +++ b/native/host/src/data/open.rs @@ -51,7 +51,7 @@ pub(super) async fn thread_open(hub: &Arc, c: &mut Conn, subs: &mut Subs, p /// threads, only when the hash of the two together differs from the client's (`have["p:"]`); `removed` names the held projects that are gone. pub(super) async fn shell_sync(hub: &Arc, c: &mut Conn, subs: &mut Subs, p: &Value, is_browser: bool) -> Result { let have = p.get("have").filter(|h| h.is_object()).cloned().unwrap_or(json!({})); - let settled_n = p["settled"].as_u64().unwrap_or(25).min(200) as usize; + let settled_n = p["settled"].as_u64().map_or(25, |n| (n as usize).clamp(1, 200)); let mut projects: Vec = vec![]; let mut before = Value::Null; loop { // every project, a page at a time let mut q = json!({"limit": 200}); if !before.is_null() { q["before"] = before.clone(); } @@ -85,7 +85,10 @@ pub(super) async fn shell_sync(hub: &Arc, c: &mut Conn, subs: &mut Subs, p: } } }; - if crate::statehost::policies().and_then(|pol| pol.with_state(|st| collect_local(Some(st)))).is_none() { + if crate::statehost::with_state_of(hub, |st| collect_local(Some(st))) + .or_else(|| crate::statehost::policies().and_then(|pol| pol.with_state(|st| collect_local(Some(st))))) + .is_none() + { collect_local(None); } diff --git a/native/host/src/data/tests.rs b/native/host/src/data/tests.rs index 87b6f93fe1..fc73938b8a 100644 --- a/native/host/src/data/tests.rs +++ b/native/host/src/data/tests.rs @@ -1526,6 +1526,27 @@ async fn viewer_layout_over_a_socket_is_per_device_pushed_and_refuses_in_code_ke assert!(r["result"]["h"]["@sections"].is_string(), "{r}"); } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn shell_sync_clamps_settled_zero_to_one() { + let extra = "{\"$\":\"ThreadSettled\",\"id\":\"t1\",\"manual\":true,\"at\":1700000100}\n{\"$\":\"ThreadSettled\",\"id\":\"t2\",\"manual\":true,\"at\":1700000200}\n"; + let (h, port) = up_with("shell-settled-zero", extra).await; + let _policies = crate::statehost::start_unshared(h.hub.clone()); + for _ in 0..200 { + let ready = crate::statehost::with_state_of(&h.hub, |st| { + ["t1", "t2"].iter().all(|id| st.threads.get(*id).is_some_and(|t| shelf_flags(t).1)) + }).unwrap_or(false); + if ready { break } + tokio::time::sleep(Duration::from_millis(10)).await; + } + let mut ws = open(port, "&enc=json").await; let _ = next(&mut ws).await; + let r = ask(&mut ws, 1, "shell.sync", json!({"settled": 0})).await; + assert_eq!(r["ok"], true, "{r}"); + let p1_settled: Vec<_> = r["result"]["threads"].as_array().unwrap().iter() + .filter(|t| t["project"] == "p1" && t["settled"] == true) + .map(|t| t["id"].as_str().unwrap().to_string()) + .collect(); + assert_eq!(p1_settled, ["t2"], "settled: 0 must clamp to 1 newest settled thread: {r}"); +} + /// The home (feature `home`): `hello.home` says where the uberbot lives as this hub sees it, and a lists subscription is told when that changes (`k:"home"`). #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn the_hello_says_where_the_home_is_and_a_move_of_it_is_pushed() { let (h, port) = up("homepush").await;