BlueGit

ict rusty-teams

fix(hunt): 24 bugs from the area sweep (chat, calendar, calls, MCP)

- rows: "New messages" divider breaks a message series again
- avatars: a failed fetch is retried after 60 s instead of staying pending
- calendar: occurrences of a recurring meeting no longer merge into one
- google calendar: local zone for new events, paging, reply keeps the attendee list
- chatsvc: conversation listing stops at an empty page
- toasts: a new message never bundles into a leaving or dismissed toast
- tray: mention dot follows mentions, not only the badge number
- mentions: a mention after a heading, rule or table is still sent as mention
- spans: spaces at the edge of bold, italic or link text survive
- session: huge Retry-After no longer panics
- graph: people search reads the first page only
- mcp: an event cursor from before a restart starts over; install state refreshes after port or token change
- agents: a non-UTF-8 output line no longer hangs the run
- composer: slash command pick no longer underflows; failed edit stays out of another chat
- calls: prejoin cleared when a call begins, held call hung up on accept, failed invite removes its tile, push-to-talk released when the call window loses focus
- calling: a camera that fails to open and a share whose source is gone switch off

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-11-14 · 2 weeks ago

Hash
d3ec5ddc5e1fa9e3a7a5ae45523d6421e696284c
Parent
ba8e1484
26 files changed +458 −59
Cargo.lock +1 −0
@@ -1372,6 +1372,7 @@ dependencies = [
1372 1372 "base64 0.22.1",
1373 1373 "chrono",
1374 1374 "futures-util",
1375 "iana-time-zone",
1375 1376 "percent-encoding",
1376 1377 "rand 0.9.5",
1377 1378 "reqwest 0.13.5",
@@ -1372,6 +1372,7 @@ dependencies = [
1372 "base64 0.22.1",
1372 "base64 0.22.1",
1373 "chrono",
1373 "chrono",
1374 "futures-util",
1374 "futures-util",
1375 "iana-time-zone",
1375 "percent-encoding",
1376 "percent-encoding",
1376 "rand 0.9.5",
1377 "rand 0.9.5",
1377 "reqwest 0.13.5",
1378 "reqwest 0.13.5",
crates/agents/src/runner.rs +1 −0
@@ -229,6 +229,7 @@ async fn run_plan(
229 229 }
230 230 line = stdout_lines.next_line() => match line {
231 231 Ok(Some(line)) => handle_events(parser.feed(&line)),
232 Err(error) if error.kind() == std::io::ErrorKind::InvalidData => continue,
232 233 _ => break,
233 234 }
234 235 }
@@ -229,6 +229,7 @@ async fn run_plan(
229 }
229 }
230 line = stdout_lines.next_line() => match line {
230 line = stdout_lines.next_line() => match line {
231 Ok(Some(line)) => handle_events(parser.feed(&line)),
231 Ok(Some(line)) => handle_events(parser.feed(&line)),
232 Err(error) if error.kind() == std::io::ErrorKind::InvalidData => continue,
232 _ => break,
233 _ => break,
233 }
234 }
234 }
235 }
crates/app-state/src/app_state.rs +9 −7
@@ -625,7 +625,7 @@ impl AppState {
625 625 .cloned()
626 626 .collect();
627 627 }
628 self.resolve_pending_avatars();
628 self.resolve_pending_avatars(&[]);
629 629 self.sync_presence();
630 630 }
631 631
@@ -654,9 +654,9 @@ impl AppState {
654 654 }
655 655 if let Some(engine) = self.engine.clone().filter(|_| !uncached.is_empty()) {
656 656 self.directory.mark_avatars_pending(&uncached);
657 let done = data::fetch_avatars(&engine, uncached);
658 self.on_done(done, cx, |state, cx| {
659 state.resolve_pending_avatars();
657 let done = data::fetch_avatars(&engine, uncached.clone());
658 self.on_done(done, cx, move |state, cx| {
659 state.resolve_pending_avatars(&uncached);
660 660 cx.emit(AppEvent::Directory);
661 661 cx.notify();
662 662 });
@@ -745,10 +745,12 @@ impl AppState {
745 745 .detach();
746 746 }
747 747
748 fn resolve_pending_avatars(&mut self) {
748 fn resolve_pending_avatars(&mut self, requested: &[String]) {
749 749 for user_id in self.directory.pending_avatars() {
750 if let Some(cached) = data::cached_avatar(&self.store, &user_id) {
751 self.directory.set_avatar(&user_id, cached);
750 match data::cached_avatar(&self.store, &user_id) {
751 Some(cached) => self.directory.set_avatar(&user_id, cached),
752 None if requested.contains(&user_id) => self.directory.mark_avatar_failed(&user_id),
753 None => {}
752 754 }
753 755 }
754 756 }
@@ -625,7 +625,7 @@ impl AppState {
625 .cloned()
625 .cloned()
626 .collect();
626 .collect();
627 }
627 }
628 self.resolve_pending_avatars();
628 self.resolve_pending_avatars(&[]);
629 self.sync_presence();
629 self.sync_presence();
630 }
630 }
631
631
@@ -654,9 +654,9 @@ impl AppState {
654 }
654 }
655 if let Some(engine) = self.engine.clone().filter(|_| !uncached.is_empty()) {
655 if let Some(engine) = self.engine.clone().filter(|_| !uncached.is_empty()) {
656 self.directory.mark_avatars_pending(&uncached);
656 self.directory.mark_avatars_pending(&uncached);
657 let done = data::fetch_avatars(&engine, uncached);
657 let done = data::fetch_avatars(&engine, uncached.clone());
658 self.on_done(done, cx, |state, cx| {
658 self.on_done(done, cx, move |state, cx| {
659 state.resolve_pending_avatars();
659 state.resolve_pending_avatars(&uncached);
660 cx.emit(AppEvent::Directory);
660 cx.emit(AppEvent::Directory);
661 cx.notify();
661 cx.notify();
662 });
662 });
@@ -745,10 +745,12 @@ impl AppState {
745 .detach();
745 .detach();
746 }
746 }
747
747
748 fn resolve_pending_avatars(&mut self) {
748 fn resolve_pending_avatars(&mut self, requested: &[String]) {
749 for user_id in self.directory.pending_avatars() {
749 for user_id in self.directory.pending_avatars() {
750 if let Some(cached) = data::cached_avatar(&self.store, &user_id) {
750 match data::cached_avatar(&self.store, &user_id) {
751 self.directory.set_avatar(&user_id, cached);
751 Some(cached) => self.directory.set_avatar(&user_id, cached),
752 None if requested.contains(&user_id) => self.directory.mark_avatar_failed(&user_id),
753 None => {}
752 }
754 }
753 }
755 }
754 }
756 }
crates/app-state/src/call/actions.rs +4 −0
@@ -280,6 +280,7 @@ impl AppState {
280 280 self.call_count += 1;
281 281 let call_id = self.call_count;
282 282 self.call_end = None;
283 self.prejoin = None;
283 284 let CallHandle {
284 285 commands,
285 286 updates,
@@ -1316,6 +1317,9 @@ impl AppState {
1316 1317 if self.call.is_some() {
1317 1318 self.leave_call(cx);
1318 1319 }
1320 if let Some(held) = &self.held_call {
1321 let _ = held.commands.send(CallCommand::Hangup);
1322 }
1319 1323 self.signal_ring(ring_id, RingSignal::Accept, cx);
1320 1324 let conversation_id = entry.ring.thread_id.clone();
1321 1325 let title = conversation_id
@@ -280,6 +280,7 @@ impl AppState {
280 self.call_count += 1;
280 self.call_count += 1;
281 let call_id = self.call_count;
281 let call_id = self.call_count;
282 self.call_end = None;
282 self.call_end = None;
283 self.prejoin = None;
283 let CallHandle {
284 let CallHandle {
284 commands,
285 commands,
285 updates,
286 updates,
@@ -1316,6 +1317,9 @@ impl AppState {
1316 if self.call.is_some() {
1317 if self.call.is_some() {
1317 self.leave_call(cx);
1318 self.leave_call(cx);
1318 }
1319 }
1320 if let Some(held) = &self.held_call {
1321 let _ = held.commands.send(CallCommand::Hangup);
1322 }
1319 self.signal_ring(ring_id, RingSignal::Accept, cx);
1323 self.signal_ring(ring_id, RingSignal::Accept, cx);
1320 let conversation_id = entry.ring.thread_id.clone();
1324 let conversation_id = entry.ring.thread_id.clone();
1321 let title = conversation_id
1325 let title = conversation_id
crates/app-state/src/call/people_actions.rs +17 −2
@@ -3,7 +3,7 @@ use gpui_kit::*;
3 3
4 4 use super::actions::NOT_CONNECTED_NOTICE;
5 5 use super::features::TransferCandidate;
6 use super::model::{CallKind, Tile};
6 use super::model::{CallKind, Tile, TileState};
7 7 use super::options_dialog::OptionsDialog;
8 8 use crate::app_state::{AppEvent, AppState};
9 9 use crate::runtime;
@@ -165,6 +165,14 @@ impl AppState {
165 165 }
166 166 }
167 167
168 fn drop_invited_tile(&mut self, mri: &str) {
169 if let Some(call) = self.call.as_mut() {
170 call.model
171 .tiles
172 .retain(|tile| tile.mri != mri || tile.state != TileState::Invited);
173 }
174 }
175
168 176 pub fn invite_call_person(&mut self, target: TransferCandidate, cx: &mut Context<Self>) {
169 177 self.close_transfer_picker(cx);
170 178 let Some(call) = self.call.as_mut().filter(|call| call.model.can_invite()) else {
@@ -204,6 +212,7 @@ impl AppState {
204 212 } else {
205 213 NO_PEER_NOTICE
206 214 };
215 self.drop_invited_tile(&callee.mri);
207 216 self.raise_notice(notice.to_owned(), None, cx);
208 217 return;
209 218 };
@@ -212,6 +221,7 @@ impl AppState {
212 221 .create_group(&[peer_user_id, invited_user_id], None)
213 222 .await
214 223 });
224 let invited_mri = callee.mri.clone();
215 225 cx.spawn(async move |this, cx| {
216 226 let created = receiver.await.ok().and_then(Result::ok);
217 227 this.update(cx, |state, cx| match created {
@@ -221,7 +231,12 @@ impl AppState {
221 231 group_thread: Some(thread_id),
222 232 });
223 233 }
224 _ => state.raise_notice(INVITE_FAILED_NOTICE.to_owned(), None, cx),
234 _ => {
235 if state.call.as_ref().is_some_and(|call| call.id == call_id) {
236 state.drop_invited_tile(&invited_mri);
237 }
238 state.raise_notice(INVITE_FAILED_NOTICE.to_owned(), None, cx);
239 }
225 240 })
226 241 .ok();
227 242 })
@@ -3,7 +3,7 @@ use gpui_kit::*;
3
3
4use super::actions::NOT_CONNECTED_NOTICE;
4use super::actions::NOT_CONNECTED_NOTICE;
5use super::features::TransferCandidate;
5use super::features::TransferCandidate;
6use super::model::{CallKind, Tile};
6use super::model::{CallKind, Tile, TileState};
7use super::options_dialog::OptionsDialog;
7use super::options_dialog::OptionsDialog;
8use crate::app_state::{AppEvent, AppState};
8use crate::app_state::{AppEvent, AppState};
9use crate::runtime;
9use crate::runtime;
@@ -165,6 +165,14 @@ impl AppState {
165 }
165 }
166 }
166 }
167
167
168 fn drop_invited_tile(&mut self, mri: &str) {
169 if let Some(call) = self.call.as_mut() {
170 call.model
171 .tiles
172 .retain(|tile| tile.mri != mri || tile.state != TileState::Invited);
173 }
174 }
175
168 pub fn invite_call_person(&mut self, target: TransferCandidate, cx: &mut Context<Self>) {
176 pub fn invite_call_person(&mut self, target: TransferCandidate, cx: &mut Context<Self>) {
169 self.close_transfer_picker(cx);
177 self.close_transfer_picker(cx);
170 let Some(call) = self.call.as_mut().filter(|call| call.model.can_invite()) else {
178 let Some(call) = self.call.as_mut().filter(|call| call.model.can_invite()) else {
@@ -204,6 +212,7 @@ impl AppState {
204 } else {
212 } else {
205 NO_PEER_NOTICE
213 NO_PEER_NOTICE
206 };
214 };
215 self.drop_invited_tile(&callee.mri);
207 self.raise_notice(notice.to_owned(), None, cx);
216 self.raise_notice(notice.to_owned(), None, cx);
208 return;
217 return;
209 };
218 };
@@ -212,6 +221,7 @@ impl AppState {
212 .create_group(&[peer_user_id, invited_user_id], None)
221 .create_group(&[peer_user_id, invited_user_id], None)
213 .await
222 .await
214 });
223 });
224 let invited_mri = callee.mri.clone();
215 cx.spawn(async move |this, cx| {
225 cx.spawn(async move |this, cx| {
216 let created = receiver.await.ok().and_then(Result::ok);
226 let created = receiver.await.ok().and_then(Result::ok);
217 this.update(cx, |state, cx| match created {
227 this.update(cx, |state, cx| match created {
@@ -221,7 +231,12 @@ impl AppState {
221 group_thread: Some(thread_id),
231 group_thread: Some(thread_id),
222 });
232 });
223 }
233 }
224 _ => state.raise_notice(INVITE_FAILED_NOTICE.to_owned(), None, cx),
234 _ => {
235 if state.call.as_ref().is_some_and(|call| call.id == call_id) {
236 state.drop_invited_tile(&invited_mri);
237 }
238 state.raise_notice(INVITE_FAILED_NOTICE.to_owned(), None, cx);
239 }
225 })
240 })
226 .ok();
241 .ok();
227 })
242 })
crates/app-state/src/data.rs +31 −1
@@ -141,6 +141,7 @@ pub struct Directory {
141 141 pub images: HashMap<String, ImageEntry>,
142 142 pub images_requested: HashSet<String>,
143 143 pub images_failed: HashMap<String, Instant>,
144 pub avatars_failed: HashMap<String, Instant>,
144 145 }
145 146
146 147 const IMAGE_RETRY_AFTER: Duration = Duration::from_secs(60);
@@ -192,10 +193,26 @@ impl Directory {
192 193 let mut seen = HashSet::new();
193 194 user_ids
194 195 .into_iter()
195 .filter(|user_id| !self.avatars.contains_key(user_id) && seen.insert(user_id.clone()))
196 .filter(|user_id| {
197 let failed_recently = self
198 .avatars_failed
199 .get(user_id)
200 .is_some_and(|failed| failed.elapsed() < IMAGE_RETRY_AFTER);
201 !self.avatars.contains_key(user_id)
202 && !failed_recently
203 && seen.insert(user_id.clone())
204 })
196 205 .collect()
197 206 }
198 207
208 pub fn mark_avatar_failed(&mut self, user_id: &str) {
209 if matches!(self.avatars.get(user_id), Some(AvatarState::Pending)) {
210 self.avatars.remove(user_id);
211 self.avatars_failed
212 .insert(user_id.to_owned(), Instant::now());
213 }
214 }
215
199 216 pub fn mark_avatars_pending(&mut self, user_ids: &[String]) {
200 217 for user_id in user_ids {
201 218 self.avatars
@@ -904,6 +921,19 @@ mod tests {
904 921 assert_eq!(directory.pending_avatars().len(), 2);
905 922 }
906 923
924 #[test]
925 fn a_failed_avatar_is_requested_again_only_after_the_retry_delay() {
926 let mut directory = Directory::default();
927 directory.mark_avatars_pending(&["a".to_owned()]);
928 directory.mark_avatar_failed("a");
929 assert!(directory.pending_avatars().is_empty());
930 assert!(directory.missing_avatars(["a".to_owned()]).is_empty());
931 directory
932 .avatars_failed
933 .insert("a".to_owned(), Instant::now() - IMAGE_RETRY_AFTER);
934 assert_eq!(directory.missing_avatars(["a".to_owned()]), vec!["a"]);
935 }
936
907 937 #[test]
908 938 fn a_failed_image_is_requested_again_only_after_the_retry_delay() {
909 939 let mut directory = Directory::default();
@@ -141,6 +141,7 @@ pub struct Directory {
141 pub images: HashMap<String, ImageEntry>,
141 pub images: HashMap<String, ImageEntry>,
142 pub images_requested: HashSet<String>,
142 pub images_requested: HashSet<String>,
143 pub images_failed: HashMap<String, Instant>,
143 pub images_failed: HashMap<String, Instant>,
144 pub avatars_failed: HashMap<String, Instant>,
144}
145}
145
146
146const IMAGE_RETRY_AFTER: Duration = Duration::from_secs(60);
147const IMAGE_RETRY_AFTER: Duration = Duration::from_secs(60);
@@ -192,10 +193,26 @@ impl Directory {
192 let mut seen = HashSet::new();
193 let mut seen = HashSet::new();
193 user_ids
194 user_ids
194 .into_iter()
195 .into_iter()
195 .filter(|user_id| !self.avatars.contains_key(user_id) && seen.insert(user_id.clone()))
196 .filter(|user_id| {
197 let failed_recently = self
198 .avatars_failed
199 .get(user_id)
200 .is_some_and(|failed| failed.elapsed() < IMAGE_RETRY_AFTER);
201 !self.avatars.contains_key(user_id)
202 && !failed_recently
203 && seen.insert(user_id.clone())
204 })
196 .collect()
205 .collect()
197 }
206 }
198
207
208 pub fn mark_avatar_failed(&mut self, user_id: &str) {
209 if matches!(self.avatars.get(user_id), Some(AvatarState::Pending)) {
210 self.avatars.remove(user_id);
211 self.avatars_failed
212 .insert(user_id.to_owned(), Instant::now());
213 }
214 }
215
199 pub fn mark_avatars_pending(&mut self, user_ids: &[String]) {
216 pub fn mark_avatars_pending(&mut self, user_ids: &[String]) {
200 for user_id in user_ids {
217 for user_id in user_ids {
201 self.avatars
218 self.avatars
@@ -904,6 +921,19 @@ mod tests {
904 assert_eq!(directory.pending_avatars().len(), 2);
921 assert_eq!(directory.pending_avatars().len(), 2);
905 }
922 }
906
923
924 #[test]
925 fn a_failed_avatar_is_requested_again_only_after_the_retry_delay() {
926 let mut directory = Directory::default();
927 directory.mark_avatars_pending(&["a".to_owned()]);
928 directory.mark_avatar_failed("a");
929 assert!(directory.pending_avatars().is_empty());
930 assert!(directory.missing_avatars(["a".to_owned()]).is_empty());
931 directory
932 .avatars_failed
933 .insert("a".to_owned(), Instant::now() - IMAGE_RETRY_AFTER);
934 assert_eq!(directory.missing_avatars(["a".to_owned()]), vec!["a"]);
935 }
936
907 #[test]
937 #[test]
908 fn a_failed_image_is_requested_again_only_after_the_retry_delay() {
938 fn a_failed_image_is_requested_again_only_after_the_retry_delay() {
909 let mut directory = Directory::default();
939 let mut directory = Directory::default();
crates/app-state/src/notify/stack.rs +13 −0
@@ -236,6 +236,8 @@ impl ToastStack {
236 236 if let Some(existing) = self.toasts.iter_mut().find(|toast| {
237 237 toast.agent.is_none()
238 238 && !toast.status_change
239 && !toast.dismissed
240 && !toast.is_leaving()
239 241 && toast.conversation_id == incoming.conversation_id
240 242 }) {
241 243 let became_mention = incoming.mentions_me && !existing.mentions_me;
@@ -509,6 +511,17 @@ mod tests {
509 511 assert_eq!(stack.visible().len(), 1);
510 512 }
511 513
514 #[test]
515 fn a_message_never_bundles_into_a_dismissed_toast() {
516 let mut stack = ToastStack::default();
517 let now = Instant::now();
518 let first = stack.push(&incoming("a", false), now);
519 stack.dismiss(first.id, now, Duration::from_millis(150));
520 let second = stack.push(&incoming("a", false), now);
521 assert!(!second.bundled);
522 assert_ne!(first.id, second.id);
523 }
524
512 525 #[test]
513 526 fn bundling_restarts_timer() {
514 527 let mut stack = ToastStack::default();
@@ -236,6 +236,8 @@ impl ToastStack {
236 if let Some(existing) = self.toasts.iter_mut().find(|toast| {
236 if let Some(existing) = self.toasts.iter_mut().find(|toast| {
237 toast.agent.is_none()
237 toast.agent.is_none()
238 && !toast.status_change
238 && !toast.status_change
239 && !toast.dismissed
240 && !toast.is_leaving()
239 && toast.conversation_id == incoming.conversation_id
241 && toast.conversation_id == incoming.conversation_id
240 }) {
242 }) {
241 let became_mention = incoming.mentions_me && !existing.mentions_me;
243 let became_mention = incoming.mentions_me && !existing.mentions_me;
@@ -509,6 +511,17 @@ mod tests {
509 assert_eq!(stack.visible().len(), 1);
511 assert_eq!(stack.visible().len(), 1);
510 }
512 }
511
513
514 #[test]
515 fn a_message_never_bundles_into_a_dismissed_toast() {
516 let mut stack = ToastStack::default();
517 let now = Instant::now();
518 let first = stack.push(&incoming("a", false), now);
519 stack.dismiss(first.id, now, Duration::from_millis(150));
520 let second = stack.push(&incoming("a", false), now);
521 assert!(!second.bundled);
522 assert_ne!(first.id, second.id);
523 }
524
512 #[test]
525 #[test]
513 fn bundling_restarts_timer() {
526 fn bundling_restarts_timer() {
514 let mut stack = ToastStack::default();
527 let mut stack = ToastStack::default();
crates/app-state/src/rows.rs +17 −1
@@ -292,10 +292,11 @@ fn continues_series(previous: &MessageRow, next: &MessageRow) -> bool {
292 292 pub fn assign_series(rows: &mut [Row]) {
293 293 let mut previous: Option<usize> = None;
294 294 for index in 0..rows.len() {
295 let Row::Message(_) = &rows[index] else {
295 let Row::Message(message) = &mut rows[index] else {
296 296 previous = None;
297 297 continue;
298 298 };
299 message.series = Series::default();
299 300 if let Some(before) = previous {
300 301 let joined = match (&rows[before], &rows[index]) {
301 302 (Row::Message(a), Row::Message(b)) => continues_series(a, b),
@@ -1984,6 +1985,21 @@ mod tests {
1984 1985 );
1985 1986 }
1986 1987
1988 #[test]
1989 fn a_new_messages_marker_set_later_breaks_the_series() {
1990 let records = vec![
1991 record_by("a", "ada", 9, 0, 7),
1992 record_by("b", "ada", 9, 1, 7),
1993 ];
1994 let mut rows = flat_rows(&records, &context(), false);
1995 assert_eq!(series_of(&rows), vec![(false, true), (true, false)]);
1996 if let Some(Row::Message(message)) = rows.last_mut() {
1997 message.new_marker = true;
1998 }
1999 assign_series(&mut rows);
2000 assert_eq!(series_of(&rows), vec![(false, false), (false, false)]);
2001 }
2002
1987 2003 #[test]
1988 2004 fn series_breaks_at_a_new_day() {
1989 2005 let records = vec![
@@ -292,10 +292,11 @@ fn continues_series(previous: &MessageRow, next: &MessageRow) -> bool {
292pub fn assign_series(rows: &mut [Row]) {
292pub fn assign_series(rows: &mut [Row]) {
293 let mut previous: Option<usize> = None;
293 let mut previous: Option<usize> = None;
294 for index in 0..rows.len() {
294 for index in 0..rows.len() {
295 let Row::Message(_) = &rows[index] else {
295 let Row::Message(message) = &mut rows[index] else {
296 previous = None;
296 previous = None;
297 continue;
297 continue;
298 };
298 };
299 message.series = Series::default();
299 if let Some(before) = previous {
300 if let Some(before) = previous {
300 let joined = match (&rows[before], &rows[index]) {
301 let joined = match (&rows[before], &rows[index]) {
301 (Row::Message(a), Row::Message(b)) => continues_series(a, b),
302 (Row::Message(a), Row::Message(b)) => continues_series(a, b),
@@ -1984,6 +1985,21 @@ mod tests {
1984 );
1985 );
1985 }
1986 }
1986
1987
1988 #[test]
1989 fn a_new_messages_marker_set_later_breaks_the_series() {
1990 let records = vec![
1991 record_by("a", "ada", 9, 0, 7),
1992 record_by("b", "ada", 9, 1, 7),
1993 ];
1994 let mut rows = flat_rows(&records, &context(), false);
1995 assert_eq!(series_of(&rows), vec![(false, true), (true, false)]);
1996 if let Some(Row::Message(message)) = rows.last_mut() {
1997 message.new_marker = true;
1998 }
1999 assign_series(&mut rows);
2000 assert_eq!(series_of(&rows), vec![(false, false), (false, false)]);
2001 }
2002
1987 #[test]
2003 #[test]
1988 fn series_breaks_at_a_new_day() {
2004 fn series_breaks_at_a_new_day() {
1989 let records = vec![
2005 let records = vec![
crates/app/src/notify/center.rs +8 −2
@@ -107,6 +107,7 @@ pub struct NotificationCenter {
107 107 tray: Option<Tray>,
108 108 app_icon: AppIcon,
109 109 shown_badge: Option<Badge>,
110 shown_mention_dot: bool,
110 111 animations: bool,
111 112 _subscription: Subscription,
112 113 _activity_observation: Subscription,
@@ -187,6 +188,7 @@ impl NotificationCenter {
187 188 tray,
188 189 app_icon,
189 190 shown_badge: None,
191 shown_mention_dot: false,
190 192 animations: platform::animations_enabled(),
191 193 app,
192 194 activity,
@@ -1220,10 +1222,14 @@ impl NotificationCenter {
1220 1222 self.unread_mentions
1221 1223 .retain(|conversation_id| still_unread.contains(conversation_id.as_str()));
1222 1224 let badge = badge_for(count);
1223 if badge == self.shown_badge {
1225 let mention_dot = !self.unread_mentions.is_empty();
1226 if badge == self.shown_badge && mention_dot == self.shown_mention_dot {
1224 1227 return;
1225 1228 }
1226 if let Some(native) = self.main_native {
1229 self.shown_mention_dot = mention_dot;
1230 if badge != self.shown_badge
1231 && let Some(native) = self.main_native
1232 {
1227 1233 platform::set_badge(native, badge.as_ref());
1228 1234 if badge.is_none() && self.shown_badge.is_some() {
1229 1235 platform::stop_flash(native);
@@ -107,6 +107,7 @@ pub struct NotificationCenter {
107 tray: Option<Tray>,
107 tray: Option<Tray>,
108 app_icon: AppIcon,
108 app_icon: AppIcon,
109 shown_badge: Option<Badge>,
109 shown_badge: Option<Badge>,
110 shown_mention_dot: bool,
110 animations: bool,
111 animations: bool,
111 _subscription: Subscription,
112 _subscription: Subscription,
112 _activity_observation: Subscription,
113 _activity_observation: Subscription,
@@ -187,6 +188,7 @@ impl NotificationCenter {
187 tray,
188 tray,
188 app_icon,
189 app_icon,
189 shown_badge: None,
190 shown_badge: None,
191 shown_mention_dot: false,
190 animations: platform::animations_enabled(),
192 animations: platform::animations_enabled(),
191 app,
193 app,
192 activity,
194 activity,
@@ -1220,10 +1222,14 @@ impl NotificationCenter {
1220 self.unread_mentions
1222 self.unread_mentions
1221 .retain(|conversation_id| still_unread.contains(conversation_id.as_str()));
1223 .retain(|conversation_id| still_unread.contains(conversation_id.as_str()));
1222 let badge = badge_for(count);
1224 let badge = badge_for(count);
1223 if badge == self.shown_badge {
1225 let mention_dot = !self.unread_mentions.is_empty();
1226 if badge == self.shown_badge && mention_dot == self.shown_mention_dot {
1224 return;
1227 return;
1225 }
1228 }
1226 if let Some(native) = self.main_native {
1229 self.shown_mention_dot = mention_dot;
1230 if badge != self.shown_badge
1231 && let Some(native) = self.main_native
1232 {
1227 platform::set_badge(native, badge.as_ref());
1233 platform::set_badge(native, badge.as_ref());
1228 if badge.is_none() && self.shown_badge.is_some() {
1234 if badge.is_none() && self.shown_badge.is_some() {
1229 platform::stop_flash(native);
1235 platform::stop_flash(native);
crates/app/src/settings/mcp.rs +3 −1
@@ -269,6 +269,7 @@ impl McpView {
269 269 && port != current
270 270 {
271 271 agent_api::update_policy(cx, |policy| policy.port = port);
272 self.refresh_installs(cx);
272 273 }
273 274 self.refresh_wsl(cx);
274 275 cx.notify();
@@ -547,9 +548,10 @@ impl McpView {
547 548 .or(reinstall_note);
548 549 let url = agent_api::endpoint_url(policy.port);
549 550 let regenerate = small_button("mcp-token-new", "New")
550 .on_click(cx.listener(|_, _, _, cx| {
551 .on_click(cx.listener(|this, _, _, cx| {
551 552 if let Some(api) = agent_api::handle(cx) {
552 553 api.update(cx, |api, cx| api.regenerate_token(cx));
554 this.refresh_installs(cx);
553 555 }
554 556 }))
555 557 .into_any_element();
@@ -269,6 +269,7 @@ impl McpView {
269 && port != current
269 && port != current
270 {
270 {
271 agent_api::update_policy(cx, |policy| policy.port = port);
271 agent_api::update_policy(cx, |policy| policy.port = port);
272 self.refresh_installs(cx);
272 }
273 }
273 self.refresh_wsl(cx);
274 self.refresh_wsl(cx);
274 cx.notify();
275 cx.notify();
@@ -547,9 +548,10 @@ impl McpView {
547 .or(reinstall_note);
548 .or(reinstall_note);
548 let url = agent_api::endpoint_url(policy.port);
549 let url = agent_api::endpoint_url(policy.port);
549 let regenerate = small_button("mcp-token-new", "New")
550 let regenerate = small_button("mcp-token-new", "New")
550 .on_click(cx.listener(|_, _, _, cx| {
551 .on_click(cx.listener(|this, _, _, cx| {
551 if let Some(api) = agent_api::handle(cx) {
552 if let Some(api) = agent_api::handle(cx) {
552 api.update(cx, |api, cx| api.regenerate_token(cx));
553 api.update(cx, |api, cx| api.regenerate_token(cx));
554 this.refresh_installs(cx);
553 }
555 }
554 }))
556 }))
555 .into_any_element();
557 .into_any_element();
crates/app/src/views/call_window.rs +8 −0
@@ -51,6 +51,7 @@ pub struct CallWindowView {
51 51 was_fullscreen: bool,
52 52 _app_subscription: Subscription,
53 53 _media_subscription: Option<Subscription>,
54 _activation_subscription: Subscription,
54 55 }
55 56
56 57 impl CallWindowView {
@@ -61,6 +62,12 @@ impl CallWindowView {
61 62 .call_media
62 63 .clone()
63 64 .map(|media| cx.observe(&media, |_, _, cx| cx.notify()));
65 let activation_subscription = cx.observe_window_activation(window, |this, window, cx| {
66 if !window.is_window_active() {
67 this.app
68 .update(cx, |state, cx| state.release_push_to_talk(cx));
69 }
70 });
64 71 let closing_app = app.clone();
65 72 window.on_window_should_close(cx, move |_, cx| {
66 73 leave_or_dismiss(&closing_app, cx);
@@ -77,6 +84,7 @@ impl CallWindowView {
77 84 was_fullscreen: false,
78 85 _app_subscription: app_subscription,
79 86 _media_subscription: media_subscription,
87 _activation_subscription: activation_subscription,
80 88 }
81 89 }
82 90
@@ -51,6 +51,7 @@ pub struct CallWindowView {
51 was_fullscreen: bool,
51 was_fullscreen: bool,
52 _app_subscription: Subscription,
52 _app_subscription: Subscription,
53 _media_subscription: Option<Subscription>,
53 _media_subscription: Option<Subscription>,
54 _activation_subscription: Subscription,
54}
55}
55
56
56impl CallWindowView {
57impl CallWindowView {
@@ -61,6 +62,12 @@ impl CallWindowView {
61 .call_media
62 .call_media
62 .clone()
63 .clone()
63 .map(|media| cx.observe(&media, |_, _, cx| cx.notify()));
64 .map(|media| cx.observe(&media, |_, _, cx| cx.notify()));
65 let activation_subscription = cx.observe_window_activation(window, |this, window, cx| {
66 if !window.is_window_active() {
67 this.app
68 .update(cx, |state, cx| state.release_push_to_talk(cx));
69 }
70 });
64 let closing_app = app.clone();
71 let closing_app = app.clone();
65 window.on_window_should_close(cx, move |_, cx| {
72 window.on_window_should_close(cx, move |_, cx| {
66 leave_or_dismiss(&closing_app, cx);
73 leave_or_dismiss(&closing_app, cx);
@@ -77,6 +84,7 @@ impl CallWindowView {
77 was_fullscreen: false,
84 was_fullscreen: false,
78 _app_subscription: app_subscription,
85 _app_subscription: app_subscription,
79 _media_subscription: media_subscription,
86 _media_subscription: media_subscription,
87 _activation_subscription: activation_subscription,
80 }
88 }
81 }
89 }
82
90
crates/app/src/views/composer/slash.rs +2 −1
@@ -343,7 +343,8 @@ impl Composer {
343 343 let Some(command) = popup.selected() else {
344 344 return;
345 345 };
346 self.replace_text(popup.range, "", 0, window, cx);
346 let typed_end = popup.range.end;
347 self.replace_text(popup.range, "", typed_end, window, cx);
347 348 self.run_slash_command(command, window, cx);
348 349 cx.notify();
349 350 }
@@ -343,7 +343,8 @@ impl Composer {
343 let Some(command) = popup.selected() else {
343 let Some(command) = popup.selected() else {
344 return;
344 return;
345 };
345 };
346 self.replace_text(popup.range, "", 0, window, cx);
346 let typed_end = popup.range.end;
347 self.replace_text(popup.range, "", typed_end, window, cx);
347 self.run_slash_command(command, window, cx);
348 self.run_slash_command(command, window, cx);
348 cx.notify();
349 cx.notify();
349 }
350 }
crates/app/src/views/conversation.rs +6 −1
@@ -3247,6 +3247,7 @@ impl ConversationView {
3247 3247 self.saving_edits.insert(message_id.clone());
3248 3248 self.rebuild(false, cx);
3249 3249 let sent = outgoing.clone();
3250 let edited_conversation = conversation_id.clone();
3250 3251 let receiver = runtime::spawn(async move {
3251 3252 engine
3252 3253 .edit_message_html(
@@ -3265,7 +3266,11 @@ impl ConversationView {
3265 3266 let _ = store.upsert_messages(std::slice::from_ref(record));
3266 3267 }
3267 3268 this.rebuild(false, cx);
3268 if failed {
3269 let same_chat = this.conversation_id().as_deref() == Some(&*edited_conversation);
3270 if failed && !same_chat {
3271 this.notice = Some("Edit failed".to_owned());
3272 cx.notify();
3273 } else if failed {
3269 3274 this.show_main_composer(cx);
3270 3275 if this.composer.read(cx).is_empty(cx) {
3271 3276 this.notice =
@@ -3247,6 +3247,7 @@ impl ConversationView {
3247 self.saving_edits.insert(message_id.clone());
3247 self.saving_edits.insert(message_id.clone());
3248 self.rebuild(false, cx);
3248 self.rebuild(false, cx);
3249 let sent = outgoing.clone();
3249 let sent = outgoing.clone();
3250 let edited_conversation = conversation_id.clone();
3250 let receiver = runtime::spawn(async move {
3251 let receiver = runtime::spawn(async move {
3251 engine
3252 engine
3252 .edit_message_html(
3253 .edit_message_html(
@@ -3265,7 +3266,11 @@ impl ConversationView {
3265 let _ = store.upsert_messages(std::slice::from_ref(record));
3266 let _ = store.upsert_messages(std::slice::from_ref(record));
3266 }
3267 }
3267 this.rebuild(false, cx);
3268 this.rebuild(false, cx);
3268 if failed {
3269 let same_chat = this.conversation_id().as_deref() == Some(&*edited_conversation);
3270 if failed && !same_chat {
3271 this.notice = Some("Edit failed".to_owned());
3272 cx.notify();
3273 } else if failed {
3269 this.show_main_composer(cx);
3274 this.show_main_composer(cx);
3270 if this.composer.read(cx).is_empty(cx) {
3275 if this.composer.read(cx).is_empty(cx) {
3271 this.notice =
3276 this.notice =
crates/calling/src/call.rs +1 −0
@@ -1029,6 +1029,7 @@ async fn drive(
1029 1029 control.updates(),
1030 1030 );
1031 1031 local_video.attach_timeline(timeline.clone());
1032 local_video.attach_commands(control.command_sender());
1032 1033 let mut camera_choice = options.camera.clone();
1033 1034 if options.start_camera {
1034 1035 match local_video.preview_camera(&camera_choice) {
@@ -1029,6 +1029,7 @@ async fn drive(
1029 control.updates(),
1029 control.updates(),
1030 );
1030 );
1031 local_video.attach_timeline(timeline.clone());
1031 local_video.attach_timeline(timeline.clone());
1032 local_video.attach_commands(control.command_sender());
1032 let mut camera_choice = options.camera.clone();
1033 let mut camera_choice = options.camera.clone();
1033 if options.start_camera {
1034 if options.start_camera {
1034 match local_video.preview_camera(&camera_choice) {
1035 match local_video.preview_camera(&camera_choice) {
crates/calling/src/screen.rs +25 −3
@@ -1,9 +1,9 @@
1 1 use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
2 2 use std::sync::{Arc, Mutex};
3 use std::time::Duration;
3 use std::time::{Duration, Instant};
4 4
5 5 use libwebrtc::desktop_capturer::{
6 CaptureSource, DesktopCaptureSourceType, DesktopCapturer, DesktopCapturerOptions,
6 CaptureError, CaptureSource, DesktopCaptureSourceType, DesktopCapturer, DesktopCapturerOptions,
7 7 PortalPickerEvent,
8 8 };
9 9 use libwebrtc::native::yuv_helper::argb_to_i420;
@@ -79,6 +79,7 @@ pub fn list_share_sources() -> Vec<ShareSource> {
79 79 }
80 80
81 81 const THUMBNAIL_ATTEMPTS: u32 = 5;
82 const SOURCE_GONE_AFTER: Duration = Duration::from_secs(3);
82 83 const THUMBNAIL_RETRY: Duration = Duration::from_millis(40);
83 84
84 85 pub fn share_thumbnail(
@@ -218,14 +219,35 @@ pub fn start_screen_capture(
218 219 let Some(mut capturer) = capturer(wanted.kind) else {
219 220 return failed("screen capture is not available".to_owned());
220 221 };
222 let gone_since: Arc<Mutex<Option<Instant>>> = Arc::default();
223 let gone_mark = gone_since.clone();
221 224 capturer.start_capture(Some(source), move |result| {
222 let Ok(frame) = result else { return };
225 let frame = match result {
226 Ok(frame) => frame,
227 Err(error) => {
228 if matches!(error, CaptureError::Permanent)
229 && let Ok(mut since) = gone_mark.lock()
230 {
231 since.get_or_insert_with(Instant::now);
232 }
233 return;
234 }
235 };
236 if let Ok(mut since) = gone_mark.lock() {
237 *since = None;
238 }
223 239 let (width, height) = (frame.width() as u32 & !1, frame.height() as u32 & !1);
224 240 if width >= 2 && height >= 2 {
225 241 deliver(i420_from_bgra(frame.data(), width, height, frame.stride()));
226 242 }
227 243 });
228 244 while !stop.load(Ordering::SeqCst) {
245 let gone = gone_since
246 .lock()
247 .is_ok_and(|since| since.is_some_and(|since| since.elapsed() >= SOURCE_GONE_AFTER));
248 if gone {
249 return failed("the shared source is gone".to_owned());
250 }
229 251 pump_messages();
230 252 capturer.capture_frame();
231 253 std::thread::sleep(Duration::from_secs(1) / fps.load(Ordering::Relaxed).max(1));
@@ -1,9 +1,9 @@
1use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
1use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
2use std::sync::{Arc, Mutex};
2use std::sync::{Arc, Mutex};
3use std::time::Duration;
3use std::time::{Duration, Instant};
4
4
5use libwebrtc::desktop_capturer::{
5use libwebrtc::desktop_capturer::{
6 CaptureSource, DesktopCaptureSourceType, DesktopCapturer, DesktopCapturerOptions,
6 CaptureError, CaptureSource, DesktopCaptureSourceType, DesktopCapturer, DesktopCapturerOptions,
7 PortalPickerEvent,
7 PortalPickerEvent,
8};
8};
9use libwebrtc::native::yuv_helper::argb_to_i420;
9use libwebrtc::native::yuv_helper::argb_to_i420;
@@ -79,6 +79,7 @@ pub fn list_share_sources() -> Vec<ShareSource> {
79}
79}
80
80
81const THUMBNAIL_ATTEMPTS: u32 = 5;
81const THUMBNAIL_ATTEMPTS: u32 = 5;
82const SOURCE_GONE_AFTER: Duration = Duration::from_secs(3);
82const THUMBNAIL_RETRY: Duration = Duration::from_millis(40);
83const THUMBNAIL_RETRY: Duration = Duration::from_millis(40);
83
84
84pub fn share_thumbnail(
85pub fn share_thumbnail(
@@ -218,14 +219,35 @@ pub fn start_screen_capture(
218 let Some(mut capturer) = capturer(wanted.kind) else {
219 let Some(mut capturer) = capturer(wanted.kind) else {
219 return failed("screen capture is not available".to_owned());
220 return failed("screen capture is not available".to_owned());
220 };
221 };
222 let gone_since: Arc<Mutex<Option<Instant>>> = Arc::default();
223 let gone_mark = gone_since.clone();
221 capturer.start_capture(Some(source), move |result| {
224 capturer.start_capture(Some(source), move |result| {
222 let Ok(frame) = result else { return };
225 let frame = match result {
226 Ok(frame) => frame,
227 Err(error) => {
228 if matches!(error, CaptureError::Permanent)
229 && let Ok(mut since) = gone_mark.lock()
230 {
231 since.get_or_insert_with(Instant::now);
232 }
233 return;
234 }
235 };
236 if let Ok(mut since) = gone_mark.lock() {
237 *since = None;
238 }
223 let (width, height) = (frame.width() as u32 & !1, frame.height() as u32 & !1);
239 let (width, height) = (frame.width() as u32 & !1, frame.height() as u32 & !1);
224 if width >= 2 && height >= 2 {
240 if width >= 2 && height >= 2 {
225 deliver(i420_from_bgra(frame.data(), width, height, frame.stride()));
241 deliver(i420_from_bgra(frame.data(), width, height, frame.stride()));
226 }
242 }
227 });
243 });
228 while !stop.load(Ordering::SeqCst) {
244 while !stop.load(Ordering::SeqCst) {
245 let gone = gone_since
246 .lock()
247 .is_ok_and(|since| since.is_some_and(|since| since.elapsed() >= SOURCE_GONE_AFTER));
248 if gone {
249 return failed("the shared source is gone".to_owned());
250 }
229 pump_messages();
251 pump_messages();
230 capturer.capture_frame();
252 capturer.capture_frame();
231 std::thread::sleep(Duration::from_secs(1) / fps.load(Ordering::Relaxed).max(1));
253 std::thread::sleep(Duration::from_secs(1) / fps.load(Ordering::Relaxed).max(1));
crates/calling/src/video_send.rs +37 −3
@@ -196,6 +196,9 @@ pub struct LocalVideo {
196 196 mode: VideoMode,
197 197 hub: Arc<VideoHub>,
198 198 updates: UnboundedSender<CallUpdate>,
199 commands: Option<UnboundedSender<CallCommand>>,
200 camera_generation: Arc<AtomicU64>,
201 share_generation: Arc<AtomicU64>,
199 202 camera: Outgoing,
200 203 screen: Outgoing,
201 204 lines: Option<VideoLines>,
@@ -225,6 +228,9 @@ impl LocalVideo {
225 228 mode,
226 229 hub,
227 230 updates,
231 commands: None,
232 camera_generation: Arc::new(AtomicU64::new(0)),
233 share_generation: Arc::new(AtomicU64::new(0)),
228 234 camera: Outgoing::new(factory, CAMERA_LABEL, PatternKind::Camera, false),
229 235 screen: Outgoing::new(factory, SCREEN_LABEL, PatternKind::Screen, true),
230 236 lines: None,
@@ -242,6 +248,10 @@ impl LocalVideo {
242 248 }
243 249 }
244 250
251 pub fn attach_commands(&mut self, commands: UnboundedSender<CallCommand>) {
252 self.commands = Some(commands);
253 }
254
245 255 pub fn attach_timeline(&mut self, timeline: Timeline) {
246 256 self.timeline = Some(timeline);
247 257 }
@@ -554,10 +564,24 @@ impl LocalVideo {
554 564 .reporting_size(self.screen.frame_size.clone())
555 565 }
556 566
557 fn report_failure(&self, notice_key: &'static str) -> impl FnOnce(String) + Send + 'static {
567 /// A capture thread that was replaced meanwhile must not switch off its successor.
568 fn report_failure(
569 &self,
570 notice_key: &'static str,
571 generation: &Arc<AtomicU64>,
572 switch_off: CallCommand,
573 ) -> impl FnOnce(String) + Send + 'static {
558 574 let updates = self.updates.clone();
575 let commands = self.commands.clone();
576 let started = generation.fetch_add(1, Ordering::SeqCst) + 1;
577 let generation = generation.clone();
559 578 move |reason| {
560 579 let _ = updates.send(CallUpdate::Notice(notice_with_detail(notice_key, reason)));
580 if generation.load(Ordering::SeqCst) == started
581 && let Some(commands) = commands
582 {
583 let _ = commands.send(switch_off);
584 }
561 585 }
562 586 }
563 587
@@ -616,7 +640,11 @@ impl LocalVideo {
616 640 }
617 641 },
618 642 move |buffer| sink.push(buffer),
619 self.report_failure(CAMERA_STOPPED_NOTICE),
643 self.report_failure(
644 CAMERA_STOPPED_NOTICE,
645 &self.camera_generation,
646 CallCommand::SetCamera(false),
647 ),
620 648 )?
621 649 }
622 650 })
@@ -640,6 +668,7 @@ impl LocalVideo {
640 668 }
641 669
642 670 pub fn stop_camera(&mut self) {
671 self.camera_generation.fetch_add(1, Ordering::SeqCst);
643 672 self.camera_preview = false;
644 673 self.camera.capture = None;
645 674 self.blur.set_cutout(None);
@@ -736,7 +765,11 @@ impl LocalVideo {
736 765 source.clone(),
737 766 self.share_fps.clone(),
738 767 move |buffer| sink.push(buffer),
739 self.report_failure(SCREEN_SHARE_STOPPED_NOTICE),
768 self.report_failure(
769 SCREEN_SHARE_STOPPED_NOTICE,
770 &self.share_generation,
771 CallCommand::StopShare,
772 ),
740 773 )?,
741 774 };
742 775 self.screen.capture = Some(capture);
@@ -747,6 +780,7 @@ impl LocalVideo {
747 780 }
748 781
749 782 pub fn stop_share(&mut self) {
783 self.share_generation.fetch_add(1, Ordering::SeqCst);
750 784 self.portal_generation = self.portal_generation.wrapping_add(1);
751 785 self.portal_armed = false;
752 786 self.portal_keep = false;
@@ -196,6 +196,9 @@ pub struct LocalVideo {
196 mode: VideoMode,
196 mode: VideoMode,
197 hub: Arc<VideoHub>,
197 hub: Arc<VideoHub>,
198 updates: UnboundedSender<CallUpdate>,
198 updates: UnboundedSender<CallUpdate>,
199 commands: Option<UnboundedSender<CallCommand>>,
200 camera_generation: Arc<AtomicU64>,
201 share_generation: Arc<AtomicU64>,
199 camera: Outgoing,
202 camera: Outgoing,
200 screen: Outgoing,
203 screen: Outgoing,
201 lines: Option<VideoLines>,
204 lines: Option<VideoLines>,
@@ -225,6 +228,9 @@ impl LocalVideo {
225 mode,
228 mode,
226 hub,
229 hub,
227 updates,
230 updates,
231 commands: None,
232 camera_generation: Arc::new(AtomicU64::new(0)),
233 share_generation: Arc::new(AtomicU64::new(0)),
228 camera: Outgoing::new(factory, CAMERA_LABEL, PatternKind::Camera, false),
234 camera: Outgoing::new(factory, CAMERA_LABEL, PatternKind::Camera, false),
229 screen: Outgoing::new(factory, SCREEN_LABEL, PatternKind::Screen, true),
235 screen: Outgoing::new(factory, SCREEN_LABEL, PatternKind::Screen, true),
230 lines: None,
236 lines: None,
@@ -242,6 +248,10 @@ impl LocalVideo {
242 }
248 }
243 }
249 }
244
250
251 pub fn attach_commands(&mut self, commands: UnboundedSender<CallCommand>) {
252 self.commands = Some(commands);
253 }
254
245 pub fn attach_timeline(&mut self, timeline: Timeline) {
255 pub fn attach_timeline(&mut self, timeline: Timeline) {
246 self.timeline = Some(timeline);
256 self.timeline = Some(timeline);
247 }
257 }
@@ -554,10 +564,24 @@ impl LocalVideo {
554 .reporting_size(self.screen.frame_size.clone())
564 .reporting_size(self.screen.frame_size.clone())
555 }
565 }
556
566
557 fn report_failure(&self, notice_key: &'static str) -> impl FnOnce(String) + Send + 'static {
567 /// A capture thread that was replaced meanwhile must not switch off its successor.
568 fn report_failure(
569 &self,
570 notice_key: &'static str,
571 generation: &Arc<AtomicU64>,
572 switch_off: CallCommand,
573 ) -> impl FnOnce(String) + Send + 'static {
558 let updates = self.updates.clone();
574 let updates = self.updates.clone();
575 let commands = self.commands.clone();
576 let started = generation.fetch_add(1, Ordering::SeqCst) + 1;
577 let generation = generation.clone();
559 move |reason| {
578 move |reason| {
560 let _ = updates.send(CallUpdate::Notice(notice_with_detail(notice_key, reason)));
579 let _ = updates.send(CallUpdate::Notice(notice_with_detail(notice_key, reason)));
580 if generation.load(Ordering::SeqCst) == started
581 && let Some(commands) = commands
582 {
583 let _ = commands.send(switch_off);
584 }
561 }
585 }
562 }
586 }
563
587
@@ -616,7 +640,11 @@ impl LocalVideo {
616 }
640 }
617 },
641 },
618 move |buffer| sink.push(buffer),
642 move |buffer| sink.push(buffer),
619 self.report_failure(CAMERA_STOPPED_NOTICE),
643 self.report_failure(
644 CAMERA_STOPPED_NOTICE,
645 &self.camera_generation,
646 CallCommand::SetCamera(false),
647 ),
620 )?
648 )?
621 }
649 }
622 })
650 })
@@ -640,6 +668,7 @@ impl LocalVideo {
640 }
668 }
641
669
642 pub fn stop_camera(&mut self) {
670 pub fn stop_camera(&mut self) {
671 self.camera_generation.fetch_add(1, Ordering::SeqCst);
643 self.camera_preview = false;
672 self.camera_preview = false;
644 self.camera.capture = None;
673 self.camera.capture = None;
645 self.blur.set_cutout(None);
674 self.blur.set_cutout(None);
@@ -736,7 +765,11 @@ impl LocalVideo {
736 source.clone(),
765 source.clone(),
737 self.share_fps.clone(),
766 self.share_fps.clone(),
738 move |buffer| sink.push(buffer),
767 move |buffer| sink.push(buffer),
739 self.report_failure(SCREEN_SHARE_STOPPED_NOTICE),
768 self.report_failure(
769 SCREEN_SHARE_STOPPED_NOTICE,
770 &self.share_generation,
771 CallCommand::StopShare,
772 ),
740 )?,
773 )?,
741 };
774 };
742 self.screen.capture = Some(capture);
775 self.screen.capture = Some(capture);
@@ -747,6 +780,7 @@ impl LocalVideo {
747 }
780 }
748
781
749 pub fn stop_share(&mut self) {
782 pub fn stop_share(&mut self) {
783 self.share_generation.fetch_add(1, Ordering::SeqCst);
750 self.portal_generation = self.portal_generation.wrapping_add(1);
784 self.portal_generation = self.portal_generation.wrapping_add(1);
751 self.portal_armed = false;
785 self.portal_armed = false;
752 self.portal_keep = false;
786 self.portal_keep = false;
crates/chatsvc/Cargo.toml +1 −0
@@ -8,6 +8,7 @@ publish.workspace = true
8 8 [dependencies]
9 9 base64.workspace = true
10 10 chrono.workspace = true
11 iana-time-zone = "0.1"
11 12 futures-util.workspace = true
12 13 percent-encoding.workspace = true
13 14 rand = "0.9"
@@ -8,6 +8,7 @@ publish.workspace = true
8[dependencies]
8[dependencies]
9base64.workspace = true
9base64.workspace = true
10chrono.workspace = true
10chrono.workspace = true
11iana-time-zone = "0.1"
11futures-util.workspace = true
12futures-util.workspace = true
12percent-encoding.workspace = true
13percent-encoding.workspace = true
13rand = "0.9"
14rand = "0.9"
crates/chatsvc/src/conversations.rs +5 −1
@@ -80,7 +80,11 @@ impl<T: MessageTransport> Conversations<T> {
80 80 };
81 81 let answer = self.transport.send(Request::get(&url)).await?;
82 82 ensure_success(&answer)?;
83 states.extend(states_in_page(&answer.body)?);
83 let page = states_in_page(&answer.body)?;
84 if page.is_empty() {
85 break;
86 }
87 states.extend(page);
84 88 next_url = backward_link(&answer.body).filter(|link| *link != url);
85 89 }
86 90 Ok(states)
@@ -80,7 +80,11 @@ impl<T: MessageTransport> Conversations<T> {
80 };
80 };
81 let answer = self.transport.send(Request::get(&url)).await?;
81 let answer = self.transport.send(Request::get(&url)).await?;
82 ensure_success(&answer)?;
82 ensure_success(&answer)?;
83 states.extend(states_in_page(&answer.body)?);
83 let page = states_in_page(&answer.body)?;
84 if page.is_empty() {
85 break;
86 }
87 states.extend(page);
84 next_url = backward_link(&answer.body).filter(|link| *link != url);
88 next_url = backward_link(&answer.body).filter(|link| *link != url);
85 }
89 }
86 Ok(states)
90 Ok(states)
crates/chatsvc/src/google_calendar/merge.rs +19 −0
@@ -37,6 +37,12 @@ pub fn merge_calendar_events(events: Vec<CalendarEvent>) -> Vec<CalendarEvent> {
37 37 }
38 38
39 39 fn same_meeting(left: &CalendarEvent, right: &CalendarEvent) -> bool {
40 let same_all_day = left.all_day
41 && right.all_day
42 && (left.start - right.start).abs() < chrono::Duration::days(1);
43 if left.start != right.start && !same_all_day {
44 return false;
45 }
40 46 if let (Some(a), Some(b)) = (&left.ical_uid, &right.ical_uid) {
41 47 if !a.is_empty() && a == b {
42 48 return true;
@@ -104,6 +110,19 @@ mod tests {
104 110 assert!(merged[0].join_url.is_some());
105 111 }
106 112
113 #[test]
114 fn occurrences_of_one_series_stay_separate() {
115 let join = Some("https://teams.microsoft.com/l/meetup-join/x");
116 let mut next_day = event("o2", CalendarSource::Outlook, Some("uid"), join);
117 next_day.start += chrono::Duration::days(1);
118 next_day.end += chrono::Duration::days(1);
119 let merged = merge_calendar_events(vec![
120 event("o1", CalendarSource::Outlook, Some("uid"), join),
121 next_day,
122 ]);
123 assert_eq!(merged.len(), 2);
124 }
125
107 126 #[test]
108 127 fn merges_on_normalized_join_url() {
109 128 let merged = merge_calendar_events(vec![
@@ -37,6 +37,12 @@ pub fn merge_calendar_events(events: Vec<CalendarEvent>) -> Vec<CalendarEvent> {
37}
37}
38
38
39fn same_meeting(left: &CalendarEvent, right: &CalendarEvent) -> bool {
39fn same_meeting(left: &CalendarEvent, right: &CalendarEvent) -> bool {
40 let same_all_day = left.all_day
41 && right.all_day
42 && (left.start - right.start).abs() < chrono::Duration::days(1);
43 if left.start != right.start && !same_all_day {
44 return false;
45 }
40 if let (Some(a), Some(b)) = (&left.ical_uid, &right.ical_uid) {
46 if let (Some(a), Some(b)) = (&left.ical_uid, &right.ical_uid) {
41 if !a.is_empty() && a == b {
47 if !a.is_empty() && a == b {
42 return true;
48 return true;
@@ -104,6 +110,19 @@ mod tests {
104 assert!(merged[0].join_url.is_some());
110 assert!(merged[0].join_url.is_some());
105 }
111 }
106
112
113 #[test]
114 fn occurrences_of_one_series_stay_separate() {
115 let join = Some("https://teams.microsoft.com/l/meetup-join/x");
116 let mut next_day = event("o2", CalendarSource::Outlook, Some("uid"), join);
117 next_day.start += chrono::Duration::days(1);
118 next_day.end += chrono::Duration::days(1);
119 let merged = merge_calendar_events(vec![
120 event("o1", CalendarSource::Outlook, Some("uid"), join),
121 next_day,
122 ]);
123 assert_eq!(merged.len(), 2);
124 }
125
107 #[test]
126 #[test]
108 fn merges_on_normalized_join_url() {
127 fn merges_on_normalized_join_url() {
109 let merged = merge_calendar_events(vec![
128 let merged = merge_calendar_events(vec![
crates/chatsvc/src/google_calendar/mod.rs +44 −10
@@ -24,6 +24,17 @@ use crate::calendar::CalendarEvent;
24 24 use crate::error::{Error, Result};
25 25
26 26 const CALENDAR_API: &str = "https://www.googleapis.com/calendar/v3";
27 const EVENTS_PAGE_SIZE: u32 = 2500;
28 const MAX_EVENT_PAGES: usize = 20;
29
30 fn attendees_with_own_reply(event: &Value, status: &str) -> Option<Vec<Value>> {
31 let mut attendees = event.get("attendees")?.as_array()?.clone();
32 let own = attendees
33 .iter_mut()
34 .find(|attendee| attendee.get("self").and_then(Value::as_bool) == Some(true))?;
35 own["responseStatus"] = Value::String(status.to_owned());
36 Some(attendees)
37 }
27 38
28 39 pub struct GoogleCalendar {
29 40 client: Client,
@@ -52,12 +63,35 @@ impl GoogleCalendar {
52 63 let encoded =
53 64 percent_encoding::utf8_percent_encode(calendar_id, percent_encoding::NON_ALPHANUMERIC);
54 65 let url = format!(
55 "{CALENDAR_API}/calendars/{encoded}/events?singleEvents=true&orderBy=startTime&timeMin={}&timeMax={}",
66 "{CALENDAR_API}/calendars/{encoded}/events?singleEvents=true&orderBy=startTime&maxResults={EVENTS_PAGE_SIZE}&timeMin={}&timeMax={}",
56 67 start.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
57 68 end.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
58 69 );
59 let body = self.get(&url).await?;
60 Ok(parse_google_events(&body, None, Some(calendar_id)))
70 let mut events = Vec::new();
71 let mut page_token: Option<String> = None;
72 for _ in 0..MAX_EVENT_PAGES {
73 let page_url = match &page_token {
74 Some(token) => format!(
75 "{url}&pageToken={}",
76 percent_encoding::utf8_percent_encode(
77 token,
78 percent_encoding::NON_ALPHANUMERIC
79 )
80 ),
81 None => url.clone(),
82 };
83 let body = self.get(&page_url).await?;
84 events.extend(parse_google_events(&body, None, Some(calendar_id)));
85 page_token = body
86 .get("nextPageToken")
87 .and_then(Value::as_str)
88 .map(str::to_owned);
89 if page_token.is_none() {
90 break;
91 }
92 }
93 events.sort_by_key(|event| (event.start, event.end));
94 Ok(events)
61 95 }
62 96
63 97 pub async fn insert_event(&self, calendar_id: &str, draft: &GoogleEventDraft) -> Result<Value> {
@@ -82,13 +116,13 @@ impl GoogleCalendar {
82 116 "{CALENDAR_API}/calendars/{encoded_cal}/events/{encoded_event}?{}",
83 117 google_rsvp_query(send_updates)
84 118 );
85 // Patch attendee self via conferenceData-free body: use attendees[].responseStatus
86 // by first getting the event is heavy; Google allows PATCH with only attendees when
87 // "self" is present. Simpler path: PATCH with a single attendees entry marked self.
88 let body = serde_json::json!({
89 "attendees": [{ "self": true, "responseStatus": status }]
90 });
91 self.patch(&url, body).await?;
119 let event_url = format!("{CALENDAR_API}/calendars/{encoded_cal}/events/{encoded_event}");
120 let event = self.get(&event_url).await?;
121 let attendees = attendees_with_own_reply(&event, status).ok_or_else(|| {
122 Error::UnexpectedAnswer("the event lists no attendee for this account".into())
123 })?;
124 self.patch(&url, serde_json::json!({ "attendees": attendees }))
125 .await?;
92 126 Ok(())
93 127 }
94 128
@@ -24,6 +24,17 @@ use crate::calendar::CalendarEvent;
24use crate::error::{Error, Result};
24use crate::error::{Error, Result};
25
25
26const CALENDAR_API: &str = "https://www.googleapis.com/calendar/v3";
26const CALENDAR_API: &str = "https://www.googleapis.com/calendar/v3";
27const EVENTS_PAGE_SIZE: u32 = 2500;
28const MAX_EVENT_PAGES: usize = 20;
29
30fn attendees_with_own_reply(event: &Value, status: &str) -> Option<Vec<Value>> {
31 let mut attendees = event.get("attendees")?.as_array()?.clone();
32 let own = attendees
33 .iter_mut()
34 .find(|attendee| attendee.get("self").and_then(Value::as_bool) == Some(true))?;
35 own["responseStatus"] = Value::String(status.to_owned());
36 Some(attendees)
37}
27
38
28pub struct GoogleCalendar {
39pub struct GoogleCalendar {
29 client: Client,
40 client: Client,
@@ -52,12 +63,35 @@ impl GoogleCalendar {
52 let encoded =
63 let encoded =
53 percent_encoding::utf8_percent_encode(calendar_id, percent_encoding::NON_ALPHANUMERIC);
64 percent_encoding::utf8_percent_encode(calendar_id, percent_encoding::NON_ALPHANUMERIC);
54 let url = format!(
65 let url = format!(
55 "{CALENDAR_API}/calendars/{encoded}/events?singleEvents=true&orderBy=startTime&timeMin={}&timeMax={}",
66 "{CALENDAR_API}/calendars/{encoded}/events?singleEvents=true&orderBy=startTime&maxResults={EVENTS_PAGE_SIZE}&timeMin={}&timeMax={}",
56 start.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
67 start.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
57 end.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
68 end.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
58 );
69 );
59 let body = self.get(&url).await?;
70 let mut events = Vec::new();
60 Ok(parse_google_events(&body, None, Some(calendar_id)))
71 let mut page_token: Option<String> = None;
72 for _ in 0..MAX_EVENT_PAGES {
73 let page_url = match &page_token {
74 Some(token) => format!(
75 "{url}&pageToken={}",
76 percent_encoding::utf8_percent_encode(
77 token,
78 percent_encoding::NON_ALPHANUMERIC
79 )
80 ),
81 None => url.clone(),
82 };
83 let body = self.get(&page_url).await?;
84 events.extend(parse_google_events(&body, None, Some(calendar_id)));
85 page_token = body
86 .get("nextPageToken")
87 .and_then(Value::as_str)
88 .map(str::to_owned);
89 if page_token.is_none() {
90 break;
91 }
92 }
93 events.sort_by_key(|event| (event.start, event.end));
94 Ok(events)
61 }
95 }
62
96
63 pub async fn insert_event(&self, calendar_id: &str, draft: &GoogleEventDraft) -> Result<Value> {
97 pub async fn insert_event(&self, calendar_id: &str, draft: &GoogleEventDraft) -> Result<Value> {
@@ -82,13 +116,13 @@ impl GoogleCalendar {
82 "{CALENDAR_API}/calendars/{encoded_cal}/events/{encoded_event}?{}",
116 "{CALENDAR_API}/calendars/{encoded_cal}/events/{encoded_event}?{}",
83 google_rsvp_query(send_updates)
117 google_rsvp_query(send_updates)
84 );
118 );
85 // Patch attendee self via conferenceData-free body: use attendees[].responseStatus
119 let event_url = format!("{CALENDAR_API}/calendars/{encoded_cal}/events/{encoded_event}");
86 // by first getting the event is heavy; Google allows PATCH with only attendees when
120 let event = self.get(&event_url).await?;
87 // "self" is present. Simpler path: PATCH with a single attendees entry marked self.
121 let attendees = attendees_with_own_reply(&event, status).ok_or_else(|| {
88 let body = serde_json::json!({
122 Error::UnexpectedAnswer("the event lists no attendee for this account".into())
89 "attendees": [{ "self": true, "responseStatus": status }]
123 })?;
90 });
124 self.patch(&url, serde_json::json!({ "attendees": attendees }))
91 self.patch(&url, body).await?;
125 .await?;
92 Ok(())
126 Ok(())
93 }
127 }
94
128
crates/chatsvc/src/google_calendar/write.rs +73 −13
@@ -1,4 +1,4 @@
1 use chrono::{Datelike, Timelike};
1 use chrono::Datelike;
2 2 use serde_json::{Value, json};
3 3
4 4 use crate::calendar::{Attendee, NewEvent, Repeat, Reply};
@@ -8,18 +8,37 @@ pub struct GoogleEventDraft {
8 8 pub subject: String,
9 9 pub start: chrono::DateTime<chrono::Utc>,
10 10 pub end: chrono::DateTime<chrono::Utc>,
11 pub local: Option<LocalTimes>,
11 12 pub attendees: Vec<Attendee>,
12 13 pub details: String,
13 14 pub join_url: Option<String>,
14 15 pub repeat: Repeat,
15 16 }
16 17
18 #[derive(Debug, Clone, PartialEq, Eq)]
19 pub struct LocalTimes {
20 pub start: chrono::NaiveDateTime,
21 pub end: chrono::NaiveDateTime,
22 pub iana_zone: String,
23 }
24
25 const LOCAL_TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%S";
26
17 27 impl From<&NewEvent> for GoogleEventDraft {
18 28 fn from(event: &NewEvent) -> Self {
19 29 GoogleEventDraft {
20 30 subject: event.subject.clone(),
21 31 start: event.start,
22 32 end: event.end,
33 local: event
34 .time_zone_name
35 .as_ref()
36 .and_then(|_| iana_time_zone::get_timezone().ok())
37 .map(|iana_zone| LocalTimes {
38 start: event.local_start,
39 end: event.local_end,
40 iana_zone,
41 }),
23 42 attendees: event.attendees.clone(),
24 43 details: event.details.clone(),
25 44 join_url: None,
@@ -28,7 +47,7 @@ impl From<&NewEvent> for GoogleEventDraft {
28 47 }
29 48 }
30 49
31 pub fn rrule_for_repeat(repeat: Repeat, start: chrono::DateTime<chrono::Utc>) -> Option<String> {
50 pub fn rrule_for_repeat(repeat: Repeat, start: chrono::NaiveDateTime) -> Option<String> {
32 51 match repeat {
33 52 Repeat::Never => None,
34 53 Repeat::Daily => Some("RRULE:FREQ=DAILY".to_owned()),
@@ -56,16 +75,36 @@ pub fn google_event_body(draft: &GoogleEventDraft) -> Value {
56 75 }
57 76 description.push_str(join_url);
58 77 }
78 let (start, end) = match &draft.local {
79 Some(local) => (
80 json!({
81 "dateTime": local.start.format(LOCAL_TIME_FORMAT).to_string(),
82 "timeZone": local.iana_zone,
83 }),
84 json!({
85 "dateTime": local.end.format(LOCAL_TIME_FORMAT).to_string(),
86 "timeZone": local.iana_zone,
87 }),
88 ),
89 None => (
90 json!({
91 "dateTime": draft.start.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
92 "timeZone": "UTC",
93 }),
94 json!({
95 "dateTime": draft.end.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
96 "timeZone": "UTC",
97 }),
98 ),
99 };
100 let series_start = draft
101 .local
102 .as_ref()
103 .map_or(draft.start.naive_utc(), |local| local.start);
59 104 let mut body = json!({
60 105 "summary": draft.subject,
61 "start": {
62 "dateTime": draft.start.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
63 "timeZone": "UTC",
64 },
65 "end": {
66 "dateTime": draft.end.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
67 "timeZone": "UTC",
68 },
106 "start": start,
107 "end": end,
69 108 "attendees": draft.attendees.iter().map(|attendee| json!({
70 109 "email": attendee.address,
71 110 "displayName": attendee.name,
@@ -77,10 +116,9 @@ pub fn google_event_body(draft: &GoogleEventDraft) -> Value {
77 116 if !description.is_empty() {
78 117 body["description"] = json!(description);
79 118 }
80 if let Some(rrule) = rrule_for_repeat(draft.repeat, draft.start) {
119 if let Some(rrule) = rrule_for_repeat(draft.repeat, series_start) {
81 120 body["recurrence"] = json!([rrule]);
82 121 }
83 let _ = (draft.start.hour(), draft.start.minute());
84 122 body
85 123 }
86 124
@@ -109,6 +147,7 @@ mod tests {
109 147 end: chrono::Utc
110 148 .with_ymd_and_hms(2026, 11, 11, 9, 30, 0)
111 149 .unwrap(),
150 local: None,
112 151 attendees: vec![Attendee {
113 152 name: "Mara".into(),
114 153 address: "mara@example.com".into(),
@@ -119,6 +158,24 @@ mod tests {
119 158 }
120 159 }
121 160
161 #[test]
162 fn a_weekly_series_repeats_in_the_local_zone_on_the_local_weekday() {
163 let mut weekly = draft(Repeat::Weekly);
164 let late_monday = chrono::NaiveDate::from_ymd_opt(2026, 6, 8)
165 .unwrap()
166 .and_hms_opt(0, 30, 0)
167 .unwrap();
168 weekly.local = Some(LocalTimes {
169 start: late_monday,
170 end: late_monday + chrono::Duration::minutes(30),
171 iana_zone: "Europe/Berlin".into(),
172 });
173 let body = google_event_body(&weekly);
174 assert_eq!(body["start"]["dateTime"], "2026-06-08T00:30:00");
175 assert_eq!(body["start"]["timeZone"], "Europe/Berlin");
176 assert_eq!(body["recurrence"][0], "RRULE:FREQ=WEEKLY;BYDAY=MO");
177 }
178
122 179 #[test]
123 180 fn body_puts_join_link_in_location_and_description() {
124 181 let body = google_event_body(&draft(Repeat::Never));
@@ -140,7 +197,10 @@ mod tests {
140 197 assert_eq!(
141 198 rrule_for_repeat(
142 199 Repeat::Weekdays,
143 chrono::Utc.with_ymd_and_hms(2026, 11, 11, 9, 0, 0).unwrap()
200 chrono::Utc
201 .with_ymd_and_hms(2026, 11, 11, 9, 0, 0)
202 .unwrap()
203 .naive_utc()
144 204 )
145 205 .as_deref(),
146 206 Some("RRULE:FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR")
@@ -1,4 +1,4 @@
1use chrono::{Datelike, Timelike};
1use chrono::Datelike;
2use serde_json::{Value, json};
2use serde_json::{Value, json};
3
3
4use crate::calendar::{Attendee, NewEvent, Repeat, Reply};
4use crate::calendar::{Attendee, NewEvent, Repeat, Reply};
@@ -8,18 +8,37 @@ pub struct GoogleEventDraft {
8 pub subject: String,
8 pub subject: String,
9 pub start: chrono::DateTime<chrono::Utc>,
9 pub start: chrono::DateTime<chrono::Utc>,
10 pub end: chrono::DateTime<chrono::Utc>,
10 pub end: chrono::DateTime<chrono::Utc>,
11 pub local: Option<LocalTimes>,
11 pub attendees: Vec<Attendee>,
12 pub attendees: Vec<Attendee>,
12 pub details: String,
13 pub details: String,
13 pub join_url: Option<String>,
14 pub join_url: Option<String>,
14 pub repeat: Repeat,
15 pub repeat: Repeat,
15}
16}
16
17
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct LocalTimes {
20 pub start: chrono::NaiveDateTime,
21 pub end: chrono::NaiveDateTime,
22 pub iana_zone: String,
23}
24
25const LOCAL_TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%S";
26
17impl From<&NewEvent> for GoogleEventDraft {
27impl From<&NewEvent> for GoogleEventDraft {
18 fn from(event: &NewEvent) -> Self {
28 fn from(event: &NewEvent) -> Self {
19 GoogleEventDraft {
29 GoogleEventDraft {
20 subject: event.subject.clone(),
30 subject: event.subject.clone(),
21 start: event.start,
31 start: event.start,
22 end: event.end,
32 end: event.end,
33 local: event
34 .time_zone_name
35 .as_ref()
36 .and_then(|_| iana_time_zone::get_timezone().ok())
37 .map(|iana_zone| LocalTimes {
38 start: event.local_start,
39 end: event.local_end,
40 iana_zone,
41 }),
23 attendees: event.attendees.clone(),
42 attendees: event.attendees.clone(),
24 details: event.details.clone(),
43 details: event.details.clone(),
25 join_url: None,
44 join_url: None,
@@ -28,7 +47,7 @@ impl From<&NewEvent> for GoogleEventDraft {
28 }
47 }
29}
48}
30
49
31pub fn rrule_for_repeat(repeat: Repeat, start: chrono::DateTime<chrono::Utc>) -> Option<String> {
50pub fn rrule_for_repeat(repeat: Repeat, start: chrono::NaiveDateTime) -> Option<String> {
32 match repeat {
51 match repeat {
33 Repeat::Never => None,
52 Repeat::Never => None,
34 Repeat::Daily => Some("RRULE:FREQ=DAILY".to_owned()),
53 Repeat::Daily => Some("RRULE:FREQ=DAILY".to_owned()),
@@ -56,16 +75,36 @@ pub fn google_event_body(draft: &GoogleEventDraft) -> Value {
56 }
75 }
57 description.push_str(join_url);
76 description.push_str(join_url);
58 }
77 }
78 let (start, end) = match &draft.local {
79 Some(local) => (
80 json!({
81 "dateTime": local.start.format(LOCAL_TIME_FORMAT).to_string(),
82 "timeZone": local.iana_zone,
83 }),
84 json!({
85 "dateTime": local.end.format(LOCAL_TIME_FORMAT).to_string(),
86 "timeZone": local.iana_zone,
87 }),
88 ),
89 None => (
90 json!({
91 "dateTime": draft.start.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
92 "timeZone": "UTC",
93 }),
94 json!({
95 "dateTime": draft.end.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
96 "timeZone": "UTC",
97 }),
98 ),
99 };
100 let series_start = draft
101 .local
102 .as_ref()
103 .map_or(draft.start.naive_utc(), |local| local.start);
59 let mut body = json!({
104 let mut body = json!({
60 "summary": draft.subject,
105 "summary": draft.subject,
61 "start": {
106 "start": start,
62 "dateTime": draft.start.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
107 "end": end,
63 "timeZone": "UTC",
64 },
65 "end": {
66 "dateTime": draft.end.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
67 "timeZone": "UTC",
68 },
69 "attendees": draft.attendees.iter().map(|attendee| json!({
108 "attendees": draft.attendees.iter().map(|attendee| json!({
70 "email": attendee.address,
109 "email": attendee.address,
71 "displayName": attendee.name,
110 "displayName": attendee.name,
@@ -77,10 +116,9 @@ pub fn google_event_body(draft: &GoogleEventDraft) -> Value {
77 if !description.is_empty() {
116 if !description.is_empty() {
78 body["description"] = json!(description);
117 body["description"] = json!(description);
79 }
118 }
80 if let Some(rrule) = rrule_for_repeat(draft.repeat, draft.start) {
119 if let Some(rrule) = rrule_for_repeat(draft.repeat, series_start) {
81 body["recurrence"] = json!([rrule]);
120 body["recurrence"] = json!([rrule]);
82 }
121 }
83 let _ = (draft.start.hour(), draft.start.minute());
84 body
122 body
85}
123}
86
124
@@ -109,6 +147,7 @@ mod tests {
109 end: chrono::Utc
147 end: chrono::Utc
110 .with_ymd_and_hms(2026, 11, 11, 9, 30, 0)
148 .with_ymd_and_hms(2026, 11, 11, 9, 30, 0)
111 .unwrap(),
149 .unwrap(),
150 local: None,
112 attendees: vec![Attendee {
151 attendees: vec![Attendee {
113 name: "Mara".into(),
152 name: "Mara".into(),
114 address: "mara@example.com".into(),
153 address: "mara@example.com".into(),
@@ -119,6 +158,24 @@ mod tests {
119 }
158 }
120 }
159 }
121
160
161 #[test]
162 fn a_weekly_series_repeats_in_the_local_zone_on_the_local_weekday() {
163 let mut weekly = draft(Repeat::Weekly);
164 let late_monday = chrono::NaiveDate::from_ymd_opt(2026, 6, 8)
165 .unwrap()
166 .and_hms_opt(0, 30, 0)
167 .unwrap();
168 weekly.local = Some(LocalTimes {
169 start: late_monday,
170 end: late_monday + chrono::Duration::minutes(30),
171 iana_zone: "Europe/Berlin".into(),
172 });
173 let body = google_event_body(&weekly);
174 assert_eq!(body["start"]["dateTime"], "2026-06-08T00:30:00");
175 assert_eq!(body["start"]["timeZone"], "Europe/Berlin");
176 assert_eq!(body["recurrence"][0], "RRULE:FREQ=WEEKLY;BYDAY=MO");
177 }
178
122 #[test]
179 #[test]
123 fn body_puts_join_link_in_location_and_description() {
180 fn body_puts_join_link_in_location_and_description() {
124 let body = google_event_body(&draft(Repeat::Never));
181 let body = google_event_body(&draft(Repeat::Never));
@@ -140,7 +197,10 @@ mod tests {
140 assert_eq!(
197 assert_eq!(
141 rrule_for_repeat(
198 rrule_for_repeat(
142 Repeat::Weekdays,
199 Repeat::Weekdays,
143 chrono::Utc.with_ymd_and_hms(2026, 11, 11, 9, 0, 0).unwrap()
200 chrono::Utc
201 .with_ymd_and_hms(2026, 11, 11, 9, 0, 0)
202 .unwrap()
203 .naive_utc()
144 )
204 )
145 .as_deref(),
205 .as_deref(),
146 Some("RRULE:FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR")
206 Some("RRULE:FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR")
crates/core/src/mentions.rs +27 −1
@@ -184,7 +184,25 @@ fn text_characters(html: &str) -> Vec<TextChar> {
184 184 offset += close + 1;
185 185 if matches!(
186 186 name.as_str(),
187 "br" | "p" | "div" | "li" | "ul" | "ol" | "blockquote" | "pre"
187 "br" | "p"
188 | "div"
189 | "li"
190 | "ul"
191 | "ol"
192 | "blockquote"
193 | "pre"
194 | "h1"
195 | "h2"
196 | "h3"
197 | "h4"
198 | "h5"
199 | "h6"
200 | "hr"
201 | "table"
202 | "tr"
203 | "td"
204 | "th"
205 | "figure"
188 206 ) {
189 207 characters.push(TextChar {
190 208 character: ' ',
@@ -279,6 +297,14 @@ pub(crate) fn ensure_allowed_in_chat(inputs: &[MentionInput]) -> Result<()> {
279 297 mod tests {
280 298 use super::*;
281 299
300 #[test]
301 fn a_mention_right_after_a_heading_or_rule_is_still_a_mention() {
302 for html in ["<h2>Plan</h2>@Ada please", "a<hr>@Ada please"] {
303 let (_, mentions) = apply_mentions(html, &[MentionInput::user("u1", "Ada")]);
304 assert_eq!(mentions.len(), 1, "{html}");
305 }
306 }
307
282 308 #[test]
283 309 fn mentions_become_at_tags_with_sequential_ids() {
284 310 let (html, mentions) = apply_mentions(
@@ -184,7 +184,25 @@ fn text_characters(html: &str) -> Vec<TextChar> {
184 offset += close + 1;
184 offset += close + 1;
185 if matches!(
185 if matches!(
186 name.as_str(),
186 name.as_str(),
187 "br" | "p" | "div" | "li" | "ul" | "ol" | "blockquote" | "pre"
187 "br" | "p"
188 | "div"
189 | "li"
190 | "ul"
191 | "ol"
192 | "blockquote"
193 | "pre"
194 | "h1"
195 | "h2"
196 | "h3"
197 | "h4"
198 | "h5"
199 | "h6"
200 | "hr"
201 | "table"
202 | "tr"
203 | "td"
204 | "th"
205 | "figure"
188 ) {
206 ) {
189 characters.push(TextChar {
207 characters.push(TextChar {
190 character: ' ',
208 character: ' ',
@@ -279,6 +297,14 @@ pub(crate) fn ensure_allowed_in_chat(inputs: &[MentionInput]) -> Result<()> {
279mod tests {
297mod tests {
280 use super::*;
298 use super::*;
281
299
300 #[test]
301 fn a_mention_right_after_a_heading_or_rule_is_still_a_mention() {
302 for html in ["<h2>Plan</h2>@Ada please", "a<hr>@Ada please"] {
303 let (_, mentions) = apply_mentions(html, &[MentionInput::user("u1", "Ada")]);
304 assert_eq!(mentions.len(), 1, "{html}");
305 }
306 }
307
282 #[test]
308 #[test]
283 fn mentions_become_at_tags_with_sequential_ids() {
309 fn mentions_become_at_tags_with_sequential_ids() {
284 let (html, mentions) = apply_mentions(
310 let (html, mentions) = apply_mentions(
crates/core/src/spans.rs +85 −7
@@ -474,6 +474,10 @@ fn push_text(spans: &mut Vec<Span>, text: &str) {
474 474 }
475 475
476 476 fn tidy(spans: &mut Vec<Span>) {
477 tidy_children(spans, true);
478 }
479
480 fn tidy_children(spans: &mut Vec<Span>, block: bool) {
477 481 for span in spans.iter_mut() {
478 482 match span {
479 483 Span::Bold(children)
@@ -484,22 +488,66 @@ fn tidy(spans: &mut Vec<Span>) {
484 488 | Span::Sized(_, children)
485 489 | Span::Underline(children)
486 490 | Span::Colored { children, .. }
487 | Span::Heading { children, .. }
491 | Span::Link { children, .. } => tidy_children(children, false),
492 Span::Heading { children, .. }
488 493 | Span::Quote { children, .. }
489 494 | Span::BlockQuote(children)
490 | Span::Indent { children, .. }
491 | Span::Link { children, .. } => tidy(children),
495 | Span::Indent { children, .. } => tidy(children),
492 496 Span::List { items, .. } => items.iter_mut().for_each(tidy),
493 497 Span::Table { rows, .. } => rows.iter_mut().flatten().for_each(tidy),
494 498 _ => {}
495 499 }
496 500 }
497 collapse_whitespace(spans);
501 collapse_whitespace(spans, block);
502 if block {
503 trim_inline_edge(spans, true);
504 trim_inline_edge(spans, false);
505 }
498 506 limit_breaks(spans);
499 507 trim_breaks(spans);
500 508 }
501 509
502 fn collapse_whitespace(spans: &mut Vec<Span>) {
510 fn trim_inline_edge(spans: &mut Vec<Span>, leading: bool) {
511 let edge = if leading {
512 spans.first_mut()
513 } else {
514 spans.last_mut()
515 };
516 let emptied = match edge {
517 Some(Span::Text(text)) => {
518 *text = if leading {
519 text.trim_start().to_owned()
520 } else {
521 text.trim_end().to_owned()
522 };
523 text.is_empty()
524 }
525 Some(
526 Span::Bold(children)
527 | Span::Italic(children)
528 | Span::Strike(children)
529 | Span::Superscript(children)
530 | Span::Subscript(children)
531 | Span::Sized(_, children)
532 | Span::Underline(children)
533 | Span::Colored { children, .. }
534 | Span::Link { children, .. },
535 ) => {
536 trim_inline_edge(children, leading);
537 false
538 }
539 _ => false,
540 };
541 if emptied {
542 if leading {
543 spans.remove(0);
544 } else {
545 spans.pop();
546 }
547 }
548 }
549
550 fn collapse_whitespace(spans: &mut Vec<Span>, block: bool) {
503 551 let mut collapsed: Vec<Span> = Vec::with_capacity(spans.len());
504 552 let count = spans.len();
505 553 for (index, span) in std::mem::take(spans).into_iter().enumerate() {
@@ -511,7 +559,10 @@ fn collapse_whitespace(spans: &mut Vec<Span>) {
511 559 let at_edge = |neighbour: Option<&Span>| {
512 560 matches!(
513 561 neighbour,
514 None | Some(
562 None if block
563 ) || matches!(
564 neighbour,
565 Some(
515 566 Span::LineBreak
516 567 | Span::Rule
517 568 | Span::List { .. }
@@ -526,7 +577,7 @@ fn collapse_whitespace(spans: &mut Vec<Span>) {
526 577 if at_edge(collapsed.last()) {
527 578 text = text.trim_start().to_owned();
528 579 }
529 if index + 1 == count {
580 if block && index + 1 == count {
530 581 text = text.trim_end().to_owned();
531 582 }
532 583 if !text.is_empty() {
@@ -583,3 +634,30 @@ fn trim_breaks(spans: &mut Vec<Span>) {
583 634 .count();
584 635 spans.drain(..leading);
585 636 }
637
638 #[cfg(test)]
639 mod tests {
640 use super::*;
641
642 #[test]
643 fn spaces_at_the_edge_of_inline_formatting_survive() {
644 assert_eq!(
645 html_to_spans("Hello<b> world</b>"),
646 vec![
647 Span::Text("Hello".into()),
648 Span::Bold(vec![Span::Text(" world".into())])
649 ]
650 );
651 assert_eq!(
652 html_to_spans("<b> Note </b>"),
653 vec![Span::Bold(vec![Span::Text("Note".into())])]
654 );
655 assert_eq!(
656 html_to_spans("<strong>Note: </strong>text"),
657 vec![
658 Span::Bold(vec![Span::Text("Note: ".into())]),
659 Span::Text("text".into())
660 ]
661 );
662 }
663 }
@@ -474,6 +474,10 @@ fn push_text(spans: &mut Vec<Span>, text: &str) {
474}
474}
475
475
476fn tidy(spans: &mut Vec<Span>) {
476fn tidy(spans: &mut Vec<Span>) {
477 tidy_children(spans, true);
478}
479
480fn tidy_children(spans: &mut Vec<Span>, block: bool) {
477 for span in spans.iter_mut() {
481 for span in spans.iter_mut() {
478 match span {
482 match span {
479 Span::Bold(children)
483 Span::Bold(children)
@@ -484,22 +488,66 @@ fn tidy(spans: &mut Vec<Span>) {
484 | Span::Sized(_, children)
488 | Span::Sized(_, children)
485 | Span::Underline(children)
489 | Span::Underline(children)
486 | Span::Colored { children, .. }
490 | Span::Colored { children, .. }
487 | Span::Heading { children, .. }
491 | Span::Link { children, .. } => tidy_children(children, false),
492 Span::Heading { children, .. }
488 | Span::Quote { children, .. }
493 | Span::Quote { children, .. }
489 | Span::BlockQuote(children)
494 | Span::BlockQuote(children)
490 | Span::Indent { children, .. }
495 | Span::Indent { children, .. } => tidy(children),
491 | Span::Link { children, .. } => tidy(children),
492 Span::List { items, .. } => items.iter_mut().for_each(tidy),
496 Span::List { items, .. } => items.iter_mut().for_each(tidy),
493 Span::Table { rows, .. } => rows.iter_mut().flatten().for_each(tidy),
497 Span::Table { rows, .. } => rows.iter_mut().flatten().for_each(tidy),
494 _ => {}
498 _ => {}
495 }
499 }
496 }
500 }
497 collapse_whitespace(spans);
501 collapse_whitespace(spans, block);
502 if block {
503 trim_inline_edge(spans, true);
504 trim_inline_edge(spans, false);
505 }
498 limit_breaks(spans);
506 limit_breaks(spans);
499 trim_breaks(spans);
507 trim_breaks(spans);
500}
508}
501
509
502fn collapse_whitespace(spans: &mut Vec<Span>) {
510fn trim_inline_edge(spans: &mut Vec<Span>, leading: bool) {
511 let edge = if leading {
512 spans.first_mut()
513 } else {
514 spans.last_mut()
515 };
516 let emptied = match edge {
517 Some(Span::Text(text)) => {
518 *text = if leading {
519 text.trim_start().to_owned()
520 } else {
521 text.trim_end().to_owned()
522 };
523 text.is_empty()
524 }
525 Some(
526 Span::Bold(children)
527 | Span::Italic(children)
528 | Span::Strike(children)
529 | Span::Superscript(children)
530 | Span::Subscript(children)
531 | Span::Sized(_, children)
532 | Span::Underline(children)
533 | Span::Colored { children, .. }
534 | Span::Link { children, .. },
535 ) => {
536 trim_inline_edge(children, leading);
537 false
538 }
539 _ => false,
540 };
541 if emptied {
542 if leading {
543 spans.remove(0);
544 } else {
545 spans.pop();
546 }
547 }
548}
549
550fn collapse_whitespace(spans: &mut Vec<Span>, block: bool) {
503 let mut collapsed: Vec<Span> = Vec::with_capacity(spans.len());
551 let mut collapsed: Vec<Span> = Vec::with_capacity(spans.len());
504 let count = spans.len();
552 let count = spans.len();
505 for (index, span) in std::mem::take(spans).into_iter().enumerate() {
553 for (index, span) in std::mem::take(spans).into_iter().enumerate() {
@@ -511,7 +559,10 @@ fn collapse_whitespace(spans: &mut Vec<Span>) {
511 let at_edge = |neighbour: Option<&Span>| {
559 let at_edge = |neighbour: Option<&Span>| {
512 matches!(
560 matches!(
513 neighbour,
561 neighbour,
514 None | Some(
562 None if block
563 ) || matches!(
564 neighbour,
565 Some(
515 Span::LineBreak
566 Span::LineBreak
516 | Span::Rule
567 | Span::Rule
517 | Span::List { .. }
568 | Span::List { .. }
@@ -526,7 +577,7 @@ fn collapse_whitespace(spans: &mut Vec<Span>) {
526 if at_edge(collapsed.last()) {
577 if at_edge(collapsed.last()) {
527 text = text.trim_start().to_owned();
578 text = text.trim_start().to_owned();
528 }
579 }
529 if index + 1 == count {
580 if block && index + 1 == count {
530 text = text.trim_end().to_owned();
581 text = text.trim_end().to_owned();
531 }
582 }
532 if !text.is_empty() {
583 if !text.is_empty() {
@@ -583,3 +634,30 @@ fn trim_breaks(spans: &mut Vec<Span>) {
583 .count();
634 .count();
584 spans.drain(..leading);
635 spans.drain(..leading);
585}
636}
637
638#[cfg(test)]
639mod tests {
640 use super::*;
641
642 #[test]
643 fn spaces_at_the_edge_of_inline_formatting_survive() {
644 assert_eq!(
645 html_to_spans("Hello<b> world</b>"),
646 vec![
647 Span::Text("Hello".into()),
648 Span::Bold(vec![Span::Text(" world".into())])
649 ]
650 );
651 assert_eq!(
652 html_to_spans("<b> Note </b>"),
653 vec![Span::Bold(vec![Span::Text("Note".into())])]
654 );
655 assert_eq!(
656 html_to_spans("<strong>Note: </strong>text"),
657 vec![
658 Span::Bold(vec![Span::Text("Note: ".into())]),
659 Span::Text("text".into())
660 ]
661 );
662 }
663}
crates/graph/src/client.rs +4 −2
@@ -180,8 +180,10 @@ impl Graph {
180 180 .batch(std::slice::from_ref(&request), scope)
181 181 .await?
182 182 .remove(0);
183 self.collect_pages::<User>(&request.url, answer, scope)
184 .await
183 if !answer.is_success() {
184 return Err(session::Error::api(answer.status, &request.url, answer.body).into());
185 }
186 Ok(Page::<User>::parse(answer.body, scope.clone())?.items)
185 187 }
186 188
187 189 pub async fn channel_messages(
@@ -180,8 +180,10 @@ impl Graph {
180 .batch(std::slice::from_ref(&request), scope)
180 .batch(std::slice::from_ref(&request), scope)
181 .await?
181 .await?
182 .remove(0);
182 .remove(0);
183 self.collect_pages::<User>(&request.url, answer, scope)
183 if !answer.is_success() {
184 .await
184 return Err(session::Error::api(answer.status, &request.url, answer.body).into());
185 }
186 Ok(Page::<User>::parse(answer.body, scope.clone())?.items)
185 }
187 }
186
188
187 pub async fn channel_messages(
189 pub async fn channel_messages(
crates/mcp/src/hub.rs +15 −1
@@ -675,7 +675,12 @@ impl AgentHub {
675 675
676 676 pub async fn wait_events(&self, since: Option<u64>, timeout: Duration) -> (Vec<Event>, u64) {
677 677 let deadline = tokio::time::Instant::now() + timeout;
678 let mut cursor = since.unwrap_or_else(|| self.lock().last_seq);
678 let last_seq = self.lock().last_seq;
679 let mut cursor = match since {
680 Some(cursor) if cursor <= last_seq => cursor,
681 Some(_) => 0,
682 None => last_seq,
683 };
679 684 loop {
680 685 let notified = self.wake.notified();
681 686 tokio::pin!(notified);
@@ -1150,6 +1155,15 @@ mod tests {
1150 1155 assert_eq!(next, 2);
1151 1156 }
1152 1157
1158 #[tokio::test]
1159 async fn a_cursor_from_before_a_restart_starts_over() {
1160 let (hub, _ui, _store) = hub_with(open_policy());
1161 hub.user_typing("c1");
1162 let (events, next) = hub.wait_events(Some(500), SHORT).await;
1163 assert_eq!(events.len(), 1);
1164 assert_eq!(next, 1);
1165 }
1166
1153 1167 #[tokio::test]
1154 1168 async fn a_waiter_wakes_when_an_event_arrives() {
1155 1169 let (hub, _ui, _store) = hub_with(open_policy());
@@ -675,7 +675,12 @@ impl AgentHub {
675
675
676 pub async fn wait_events(&self, since: Option<u64>, timeout: Duration) -> (Vec<Event>, u64) {
676 pub async fn wait_events(&self, since: Option<u64>, timeout: Duration) -> (Vec<Event>, u64) {
677 let deadline = tokio::time::Instant::now() + timeout;
677 let deadline = tokio::time::Instant::now() + timeout;
678 let mut cursor = since.unwrap_or_else(|| self.lock().last_seq);
678 let last_seq = self.lock().last_seq;
679 let mut cursor = match since {
680 Some(cursor) if cursor <= last_seq => cursor,
681 Some(_) => 0,
682 None => last_seq,
683 };
679 loop {
684 loop {
680 let notified = self.wake.notified();
685 let notified = self.wake.notified();
681 tokio::pin!(notified);
686 tokio::pin!(notified);
@@ -1150,6 +1155,15 @@ mod tests {
1150 assert_eq!(next, 2);
1155 assert_eq!(next, 2);
1151 }
1156 }
1152
1157
1158 #[tokio::test]
1159 async fn a_cursor_from_before_a_restart_starts_over() {
1160 let (hub, _ui, _store) = hub_with(open_policy());
1161 hub.user_typing("c1");
1162 let (events, next) = hub.wait_events(Some(500), SHORT).await;
1163 assert_eq!(events.len(), 1);
1164 assert_eq!(next, 1);
1165 }
1166
1153 #[tokio::test]
1167 #[tokio::test]
1154 async fn a_waiter_wakes_when_an_event_arrives() {
1168 async fn a_waiter_wakes_when_an_event_arrives() {
1155 let (hub, _ui, _store) = hub_with(open_policy());
1169 let (hub, _ui, _store) = hub_with(open_policy());
crates/session/src/session.rs +2 −2
@@ -356,8 +356,7 @@ impl Drop for TabHold {
356 356 pub(crate) fn retry_wait(header: Option<&str>, default: Duration) -> Duration {
357 357 header
358 358 .and_then(|value| value.trim().parse::<f64>().ok())
359 .filter(|seconds| seconds.is_finite() && *seconds >= 0.0)
360 .map(Duration::from_secs_f64)
359 .and_then(|seconds| Duration::try_from_secs_f64(seconds).ok())
361 360 .unwrap_or(default)
362 361 }
363 362
@@ -429,5 +428,6 @@ mod tests {
429 428 default
430 429 );
431 430 assert_eq!(retry_wait(Some("-3"), default), default);
431 assert_eq!(retry_wait(Some("1e20"), default), default);
432 432 }
433 433 }
@@ -356,8 +356,7 @@ impl Drop for TabHold {
356pub(crate) fn retry_wait(header: Option<&str>, default: Duration) -> Duration {
356pub(crate) fn retry_wait(header: Option<&str>, default: Duration) -> Duration {
357 header
357 header
358 .and_then(|value| value.trim().parse::<f64>().ok())
358 .and_then(|value| value.trim().parse::<f64>().ok())
359 .filter(|seconds| seconds.is_finite() && *seconds >= 0.0)
359 .and_then(|seconds| Duration::try_from_secs_f64(seconds).ok())
360 .map(Duration::from_secs_f64)
361 .unwrap_or(default)
360 .unwrap_or(default)
362}
361}
363
362
@@ -429,5 +428,6 @@ mod tests {
429 default
428 default
430 );
429 );
431 assert_eq!(retry_wait(Some("-3"), default), default);
430 assert_eq!(retry_wait(Some("-3"), default), default);
431 assert_eq!(retry_wait(Some("1e20"), default), default);
432 }
432 }
433}
433}