BlueGit

ict rusty-teams

fix(chat): load old pinned messages and jump to them like Teams

| Before | After |
|---|---|
| Pin banner shows "Pinned message" for a pin older than the cached history | Banner shows author and text, fetched with one Graph GET |
| Click on such a pin does nothing | Loads the messages around it and shows them as a separate window |
| Search, notification and agent jumps to old chat messages do nothing | Same window |

- Window: chatsvc `messages/epochTimeStamp/{id}?direction=BIDIRECTIONAL` for ids and paging, content via one Graph `$batch`, mapped by the existing `message_record`. This is how Teams web does it.
- Window pages both ways. "Jump to latest" or sending leaves it.
- The normal chat view hides cached messages older than `oldest_loaded`, so a window never shows up behind a hidden gap.
- Scroller: `force_jump_button`, `on_jump`, `stop_following`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-13 · 7 weeks ago

Hash
1ca4901aa73f44c3ed87bca5252a497a8dc439a5
Parent
a74679b4
14 files changed +1055 −46
crates/app/src/rows.rs +16 −3
@@ -21,6 +21,7 @@ use crate::translation::{TranslationContext, TranslationLine};
21 21 const POST_VISIBLE_REPLIES: usize = 3;
22 22
23 23 pub const LOAD_OLDER_KEY: &str = "load-older";
24 pub const LOAD_NEWER_KEY: &str = "load-newer";
24 25 const UNKNOWN_AUTHOR: &str = "Unknown";
25 26 const DELETED_TEXT: &str = "Message deleted";
26 27 const SERIES_GAP_MINUTES: i64 = 5;
@@ -148,6 +149,7 @@ pub const START_KEY: &str = "conversation-start";
148 149 #[derive(Debug, Clone, PartialEq)]
149 150 pub enum Row {
150 151 LoadOlder,
152 LoadNewer,
151 153 Start(StartInfo),
152 154 Skeleton(Skeleton),
153 155 Message(Box<MessageRow>),
@@ -237,6 +239,7 @@ impl Row {
237 239 pub fn key(&self) -> &str {
238 240 match self {
239 241 Row::LoadOlder => LOAD_OLDER_KEY,
242 Row::LoadNewer => LOAD_NEWER_KEY,
240 243 Row::Start(_) => START_KEY,
241 244 Row::Skeleton(skeleton) => skeleton.key,
242 245 Row::Message(message) => &message.key,
@@ -248,7 +251,9 @@ impl Row {
248 251 match self {
249 252 Row::Message(message) => Box::new(std::iter::once(message.as_ref())),
250 253 Row::Post(post) => Box::new(post.messages()),
251 Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) => Box::new(std::iter::empty()),
254 Row::LoadOlder | Row::LoadNewer | Row::Start(_) | Row::Skeleton(_) => {
255 Box::new(std::iter::empty())
256 }
252 257 }
253 258 }
254 259 }
@@ -1029,7 +1034,11 @@ mod tests {
1029 1034 .iter()
1030 1035 .map(|row| match row {
1031 1036 Row::Message(message) => message.day_header.clone(),
1032 Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) | Row::Post(_) => None,
1037 Row::LoadOlder
1038 | Row::LoadNewer
1039 | Row::Start(_)
1040 | Row::Skeleton(_)
1041 | Row::Post(_) => None,
1033 1042 })
1034 1043 .collect();
1035 1044 assert_eq!(
@@ -1290,7 +1299,11 @@ mod tests {
1290 1299 rows.iter()
1291 1300 .filter_map(|row| match row {
1292 1301 Row::Message(message) => Some((message.series.has_prev, message.series.has_next)),
1293 Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) | Row::Post(_) => None,
1302 Row::LoadOlder
1303 | Row::LoadNewer
1304 | Row::Start(_)
1305 | Row::Skeleton(_)
1306 | Row::Post(_) => None,
1294 1307 })
1295 1308 .collect()
1296 1309 }
@@ -21,6 +21,7 @@ use crate::translation::{TranslationContext, TranslationLine};
21const POST_VISIBLE_REPLIES: usize = 3;
21const POST_VISIBLE_REPLIES: usize = 3;
22
22
23pub const LOAD_OLDER_KEY: &str = "load-older";
23pub const LOAD_OLDER_KEY: &str = "load-older";
24pub const LOAD_NEWER_KEY: &str = "load-newer";
24const UNKNOWN_AUTHOR: &str = "Unknown";
25const UNKNOWN_AUTHOR: &str = "Unknown";
25const DELETED_TEXT: &str = "Message deleted";
26const DELETED_TEXT: &str = "Message deleted";
26const SERIES_GAP_MINUTES: i64 = 5;
27const SERIES_GAP_MINUTES: i64 = 5;
@@ -148,6 +149,7 @@ pub const START_KEY: &str = "conversation-start";
148#[derive(Debug, Clone, PartialEq)]
149#[derive(Debug, Clone, PartialEq)]
149pub enum Row {
150pub enum Row {
150 LoadOlder,
151 LoadOlder,
152 LoadNewer,
151 Start(StartInfo),
153 Start(StartInfo),
152 Skeleton(Skeleton),
154 Skeleton(Skeleton),
153 Message(Box<MessageRow>),
155 Message(Box<MessageRow>),
@@ -237,6 +239,7 @@ impl Row {
237 pub fn key(&self) -> &str {
239 pub fn key(&self) -> &str {
238 match self {
240 match self {
239 Row::LoadOlder => LOAD_OLDER_KEY,
241 Row::LoadOlder => LOAD_OLDER_KEY,
242 Row::LoadNewer => LOAD_NEWER_KEY,
240 Row::Start(_) => START_KEY,
243 Row::Start(_) => START_KEY,
241 Row::Skeleton(skeleton) => skeleton.key,
244 Row::Skeleton(skeleton) => skeleton.key,
242 Row::Message(message) => &message.key,
245 Row::Message(message) => &message.key,
@@ -248,7 +251,9 @@ impl Row {
248 match self {
251 match self {
249 Row::Message(message) => Box::new(std::iter::once(message.as_ref())),
252 Row::Message(message) => Box::new(std::iter::once(message.as_ref())),
250 Row::Post(post) => Box::new(post.messages()),
253 Row::Post(post) => Box::new(post.messages()),
251 Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) => Box::new(std::iter::empty()),
254 Row::LoadOlder | Row::LoadNewer | Row::Start(_) | Row::Skeleton(_) => {
255 Box::new(std::iter::empty())
256 }
252 }
257 }
253 }
258 }
254}
259}
@@ -1029,7 +1034,11 @@ mod tests {
1029 .iter()
1034 .iter()
1030 .map(|row| match row {
1035 .map(|row| match row {
1031 Row::Message(message) => message.day_header.clone(),
1036 Row::Message(message) => message.day_header.clone(),
1032 Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) | Row::Post(_) => None,
1037 Row::LoadOlder
1038 | Row::LoadNewer
1039 | Row::Start(_)
1040 | Row::Skeleton(_)
1041 | Row::Post(_) => None,
1033 })
1042 })
1034 .collect();
1043 .collect();
1035 assert_eq!(
1044 assert_eq!(
@@ -1290,7 +1299,11 @@ mod tests {
1290 rows.iter()
1299 rows.iter()
1291 .filter_map(|row| match row {
1300 .filter_map(|row| match row {
1292 Row::Message(message) => Some((message.series.has_prev, message.series.has_next)),
1301 Row::Message(message) => Some((message.series.has_prev, message.series.has_next)),
1293 Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) | Row::Post(_) => None,
1302 Row::LoadOlder
1303 | Row::LoadNewer
1304 | Row::Start(_)
1305 | Row::Skeleton(_)
1306 | Row::Post(_) => None,
1294 })
1307 })
1295 .collect()
1308 .collect()
1296 }
1309 }
crates/app/src/views/conversation.rs +127 −28
@@ -17,8 +17,11 @@ use gpui_kit::component::{
17 17 use gpui_kit::prelude::FluentBuilder as _;
18 18 use gpui_kit::*;
19 19 use store::{ChannelTabRecord, MessageRecord, OutboxState, OutboxTarget};
20 use teams_core::{ExecuteAction, FileCard, LinkPreview};
20 use teams_core::{
21 ExecuteAction, FileCard, JumpPlan, LinkPreview, WindowDirection, without_islands,
22 };
21 23
24 mod detached;
22 25 mod feed;
23 26 mod pins;
24 27 mod proposal;
@@ -68,6 +71,7 @@ use crate::sidebar_model::{AvatarSpec, Face};
68 71 use crate::theme;
69 72 use crate::translation::TranslationLine;
70 73 use crate::typing::typing_tooltip;
74 use detached::DetachedWindow;
71 75 use feed::{FeedStash, subject_input};
72 76 use render_env::RenderEnv;
73 77 use shared::SharedState;
@@ -136,6 +140,8 @@ struct Current {
136 140 fetched: bool,
137 141 first_unread: Option<String>,
138 142 sync: SyncProgress,
143 detached: Option<DetachedWindow>,
144 window_request: Option<String>,
139 145 }
140 146
141 147 struct ReactionDetails {
@@ -178,6 +184,7 @@ pub struct ConversationView {
178 184 highlighted_message: Option<String>,
179 185 pin_index: usize,
180 186 pin_previews: HashMap<String, pins::PinPreview>,
187 pin_fetches: HashSet<String>,
181 188 notice: Option<String>,
182 189 scheduled_failure: Option<scheduled::ScheduledFailure>,
183 190 scheduled_in_flight: HashSet<String>,
@@ -492,6 +499,7 @@ impl ConversationView {
492 499 highlighted_message: None,
493 500 pin_index: 0,
494 501 pin_previews: HashMap::new(),
502 pin_fetches: HashSet::new(),
495 503 notice: None,
496 504 scheduled_failure: None,
497 505 scheduled_in_flight: HashSet::new(),
@@ -806,6 +814,8 @@ impl ConversationView {
806 814 fetched: false,
807 815 first_unread,
808 816 sync: SyncProgress::default(),
817 detached: None,
818 window_request: None,
809 819 });
810 820 self.refresh_agent_runs(cx);
811 821 self.sync_generation += 1;
@@ -1020,11 +1030,28 @@ impl ConversationView {
1020 1030
1021 1031 fn jump_to_message(&mut self, conversation_id: &str, message_id: &str, cx: &mut Context<Self>) {
1022 1032 let store = self.app.read(cx).store.clone();
1023 let Some(record) = store
1033 let record = store
1024 1034 .messages_by_id(conversation_id, &[message_id.to_owned()])
1025 1035 .ok()
1026 .and_then(|mut found| found.remove(message_id))
1027 else {
1036 .and_then(|mut found| found.remove(message_id));
1037 if self.chat_id().as_deref() == Some(conversation_id) {
1038 let created_at = record.as_ref().map(|record| record.created_at);
1039 match self.jump_plan_for(conversation_id, created_at, cx) {
1040 JumpPlan::LoadWindow => {
1041 self.open_detached(conversation_id.to_owned(), message_id.to_owned(), cx);
1042 return;
1043 }
1044 plan => {
1045 if let Some(current) = self.current.as_mut() {
1046 current.window_request = None;
1047 if plan == JumpPlan::LeaveWindow {
1048 current.detached = None;
1049 }
1050 }
1051 }
1052 }
1053 }
1054 let Some(record) = record else {
1028 1055 return;
1029 1056 };
1030 1057 let messages_from_target = store
@@ -1071,6 +1098,10 @@ impl ConversationView {
1071 1098 };
1072 1099 self.reload_pending(cx);
1073 1100 self.rebuild(true, cx);
1101 self.reveal_row(target_key, cx);
1102 }
1103
1104 fn reveal_row(&mut self, target_key: String, cx: &mut Context<Self>) {
1074 1105 let index = self
1075 1106 .rows
1076 1107 .borrow()
@@ -1360,16 +1391,33 @@ impl ConversationView {
1360 1391 ViewMode::Thread(root_id) => Some(root_id.clone()),
1361 1392 ViewMode::Flat | ViewMode::ThreadList => None,
1362 1393 };
1363 let records: Vec<MessageRecord> = match &thread_root {
1364 Some(root_id) => store.thread_messages(&conversation_id, root_id),
1365 None => store.messages(&conversation_id, None, limit),
1366 }
1367 .unwrap_or_default();
1368 let sync_has_more = store
1369 .sync_state(&conversation_id)
1370 .ok()
1371 .flatten()
1372 .is_none_or(|state| state.has_more);
1394 let sync_state = store.sync_state(&conversation_id).ok().flatten();
1395 let window = current.detached.as_ref().map(|detached| {
1396 (
1397 detached.oldest,
1398 detached.newest,
1399 detached.older_cursor.is_some(),
1400 detached.newer_cursor.is_some(),
1401 )
1402 });
1403 let records: Vec<MessageRecord> = match (&thread_root, window) {
1404 (Some(root_id), _) => store
1405 .thread_messages(&conversation_id, root_id)
1406 .unwrap_or_default(),
1407 (None, Some((oldest, newest, _, _))) => store
1408 .messages_between(&conversation_id, oldest, newest)
1409 .unwrap_or_default(),
1410 (None, None) if matches!(current.selection, Selection::Chat(_)) => without_islands(
1411 store
1412 .messages(&conversation_id, None, limit)
1413 .unwrap_or_default(),
1414 sync_state.as_ref().and_then(|state| state.oldest_loaded),
1415 ),
1416 (None, None) => store
1417 .messages(&conversation_id, None, limit)
1418 .unwrap_or_default(),
1419 };
1420 let sync_has_more = sync_state.as_ref().is_none_or(|state| state.has_more);
1373 1421 let mut context = self.row_context(cx);
1374 1422 let reactor_ids: Vec<String> = records
1375 1423 .iter()
@@ -1407,14 +1455,24 @@ impl ConversationView {
1407 1455 current.has_older = false;
1408 1456 placeholder_rows()
1409 1457 }
1410 ViewMode::Flat => {
1411 current.has_older = has_older;
1412 let mut rows = flat_rows(&records, &context, has_older);
1413 if !has_older && let Some(start) = start {
1414 rows.insert(0, Row::Start(start));
1458 ViewMode::Flat => match window {
1459 Some((_, _, has_older_window, has_newer_window)) => {
1460 current.has_older = has_older_window;
1461 let mut rows = flat_rows(&records, &context, has_older_window);
1462 if has_newer_window {
1463 rows.push(Row::LoadNewer);
1464 }
1465 rows
1415 1466 }
1416 rows
1417 }
1467 None => {
1468 current.has_older = has_older;
1469 let mut rows = flat_rows(&records, &context, has_older);
1470 if !has_older && let Some(start) = start {
1471 rows.insert(0, Row::Start(start));
1472 }
1473 rows
1474 }
1475 },
1418 1476 ViewMode::ThreadList => {
1419 1477 current.has_older = has_older;
1420 1478 thread_list_rows(&records, &context, has_older)
@@ -1424,12 +1482,15 @@ impl ConversationView {
1424 1482 thread_rows(&records, root_id, &context)
1425 1483 }
1426 1484 };
1427 let local: Vec<MessageRow> = self
1428 .pending
1429 .iter()
1430 .cloned()
1431 .chain(self.scheduled_rows(context.my_user_id.as_deref(), cx))
1432 .collect();
1485 let local: Vec<MessageRow> = if window.is_some() {
1486 Vec::new()
1487 } else {
1488 self.pending
1489 .iter()
1490 .cloned()
1491 .chain(self.scheduled_rows(context.my_user_id.as_deref(), cx))
1492 .collect()
1493 };
1433 1494 if in_feed {
1434 1495 place_local_rows(&mut rows, local);
1435 1496 } else {
@@ -1454,6 +1515,10 @@ impl ConversationView {
1454 1515 }
1455 1516 assign_series(&mut rows);
1456 1517 self.apply_rows(rows, reset, cx);
1518 if self.is_detached() {
1519 self.scroller
1520 .update(cx, |scroller, _| scroller.stop_following());
1521 }
1457 1522 }
1458 1523
1459 1524 fn apply_rows(&mut self, new_rows: Vec<Row>, reset: bool, cx: &mut Context<Self>) {
@@ -1823,6 +1888,9 @@ impl ConversationView {
1823 1888 }
1824 1889
1825 1890 fn request_older(&mut self, cx: &mut Context<Self>) {
1891 if self.is_detached() {
1892 return self.request_window_page(WindowDirection::Backward, cx);
1893 }
1826 1894 let Some(engine) = self.app.read(cx).engine.clone() else {
1827 1895 return;
1828 1896 };
@@ -1952,6 +2020,7 @@ impl ConversationView {
1952 2020 }
1953 2021
1954 2022 fn send(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
2023 self.leave_detached(cx);
1955 2024 self.send_as(new_outbox_id(), outgoing, None, window, cx);
1956 2025 }
1957 2026
@@ -3143,8 +3212,11 @@ impl ConversationView {
3143 3212 header_call_controls(&self.app, app, &current.selection)
3144 3213 };
3145 3214 let sync = &current.sync;
3215 let loading_window = current.window_request.is_some();
3146 3216 if sync.failed {
3147 3217 subline = "Not up to date".to_owned();
3218 } else if loading_window {
3219 subline = "Loading message ...".to_owned();
3148 3220 } else if sync.shown_at.is_some() {
3149 3221 subline = if sync.slow {
3150 3222 "Taking longer than usual ..."
@@ -3157,7 +3229,7 @@ impl ConversationView {
3157 3229 }
3158 3230 header
3159 3231 .relative()
3160 .when(sync.shown_at.is_some(), |header| {
3232 .when(sync.shown_at.is_some() || loading_window, |header| {
3161 3233 header.child(progress_bar())
3162 3234 })
3163 3235 .children(lead)
@@ -3213,6 +3285,7 @@ impl Render for ConversationView {
3213 3285 .into_any_element();
3214 3286 }
3215 3287 let in_feed = self.in_feed();
3288 let detached = self.is_detached();
3216 3289 let rows_seen = self.feed_rows_seen.replace(usize::MAX);
3217 3290 if in_feed && rows_seen != usize::MAX {
3218 3291 self.feed_at_top = rows_seen == 0;
@@ -3262,6 +3335,25 @@ impl Render for ConversationView {
3262 3335 .child("Loading older messages")
3263 3336 .into_any_element()
3264 3337 }
3338 Some(Row::LoadNewer) => {
3339 let view = env.view.clone();
3340 cx.defer(move |cx| {
3341 view.update(cx, |this, cx| {
3342 this.request_window_page(WindowDirection::Forward, cx)
3343 })
3344 .ok();
3345 });
3346 h_flex()
3347 .w_full()
3348 .py_2()
3349 .gap(px(6.))
3350 .justify_center()
3351 .text_size(px(12.))
3352 .text_color(theme::text_muted())
3353 .child(icon(IconName::Loader, 12., theme::text_muted()))
3354 .child("Loading newer messages")
3355 .into_any_element()
3356 }
3265 3357 Some(Row::Start(start)) => {
3266 3358 let state = env.app.read(cx);
3267 3359 v_flex()
@@ -3297,6 +3389,13 @@ impl Render for ConversationView {
3297 3389 )
3298 3390 .with_row_style(StyleRefinement::default().px(px(0.)).pb(px(0.)))
3299 3391 .jump_button(!in_feed)
3392 .force_jump_button(detached)
3393 .when(detached, |scroller| {
3394 let view = cx.weak_entity();
3395 scroller.on_jump(move |_, cx| {
3396 view.update(cx, |this, cx| this.leave_detached(cx)).ok();
3397 })
3398 })
3300 3399 .with_bottom_fade(background);
3301 3400
3302 3401 root = match self.current.as_ref().filter(|_| !drafting) {
@@ -17,8 +17,11 @@ use gpui_kit::component::{
17use gpui_kit::prelude::FluentBuilder as _;
17use gpui_kit::prelude::FluentBuilder as _;
18use gpui_kit::*;
18use gpui_kit::*;
19use store::{ChannelTabRecord, MessageRecord, OutboxState, OutboxTarget};
19use store::{ChannelTabRecord, MessageRecord, OutboxState, OutboxTarget};
20use teams_core::{ExecuteAction, FileCard, LinkPreview};
20use teams_core::{
21 ExecuteAction, FileCard, JumpPlan, LinkPreview, WindowDirection, without_islands,
22};
21
23
24mod detached;
22mod feed;
25mod feed;
23mod pins;
26mod pins;
24mod proposal;
27mod proposal;
@@ -68,6 +71,7 @@ use crate::sidebar_model::{AvatarSpec, Face};
68use crate::theme;
71use crate::theme;
69use crate::translation::TranslationLine;
72use crate::translation::TranslationLine;
70use crate::typing::typing_tooltip;
73use crate::typing::typing_tooltip;
74use detached::DetachedWindow;
71use feed::{FeedStash, subject_input};
75use feed::{FeedStash, subject_input};
72use render_env::RenderEnv;
76use render_env::RenderEnv;
73use shared::SharedState;
77use shared::SharedState;
@@ -136,6 +140,8 @@ struct Current {
136 fetched: bool,
140 fetched: bool,
137 first_unread: Option<String>,
141 first_unread: Option<String>,
138 sync: SyncProgress,
142 sync: SyncProgress,
143 detached: Option<DetachedWindow>,
144 window_request: Option<String>,
139}
145}
140
146
141struct ReactionDetails {
147struct ReactionDetails {
@@ -178,6 +184,7 @@ pub struct ConversationView {
178 highlighted_message: Option<String>,
184 highlighted_message: Option<String>,
179 pin_index: usize,
185 pin_index: usize,
180 pin_previews: HashMap<String, pins::PinPreview>,
186 pin_previews: HashMap<String, pins::PinPreview>,
187 pin_fetches: HashSet<String>,
181 notice: Option<String>,
188 notice: Option<String>,
182 scheduled_failure: Option<scheduled::ScheduledFailure>,
189 scheduled_failure: Option<scheduled::ScheduledFailure>,
183 scheduled_in_flight: HashSet<String>,
190 scheduled_in_flight: HashSet<String>,
@@ -492,6 +499,7 @@ impl ConversationView {
492 highlighted_message: None,
499 highlighted_message: None,
493 pin_index: 0,
500 pin_index: 0,
494 pin_previews: HashMap::new(),
501 pin_previews: HashMap::new(),
502 pin_fetches: HashSet::new(),
495 notice: None,
503 notice: None,
496 scheduled_failure: None,
504 scheduled_failure: None,
497 scheduled_in_flight: HashSet::new(),
505 scheduled_in_flight: HashSet::new(),
@@ -806,6 +814,8 @@ impl ConversationView {
806 fetched: false,
814 fetched: false,
807 first_unread,
815 first_unread,
808 sync: SyncProgress::default(),
816 sync: SyncProgress::default(),
817 detached: None,
818 window_request: None,
809 });
819 });
810 self.refresh_agent_runs(cx);
820 self.refresh_agent_runs(cx);
811 self.sync_generation += 1;
821 self.sync_generation += 1;
@@ -1020,11 +1030,28 @@ impl ConversationView {
1020
1030
1021 fn jump_to_message(&mut self, conversation_id: &str, message_id: &str, cx: &mut Context<Self>) {
1031 fn jump_to_message(&mut self, conversation_id: &str, message_id: &str, cx: &mut Context<Self>) {
1022 let store = self.app.read(cx).store.clone();
1032 let store = self.app.read(cx).store.clone();
1023 let Some(record) = store
1033 let record = store
1024 .messages_by_id(conversation_id, &[message_id.to_owned()])
1034 .messages_by_id(conversation_id, &[message_id.to_owned()])
1025 .ok()
1035 .ok()
1026 .and_then(|mut found| found.remove(message_id))
1036 .and_then(|mut found| found.remove(message_id));
1027 else {
1037 if self.chat_id().as_deref() == Some(conversation_id) {
1038 let created_at = record.as_ref().map(|record| record.created_at);
1039 match self.jump_plan_for(conversation_id, created_at, cx) {
1040 JumpPlan::LoadWindow => {
1041 self.open_detached(conversation_id.to_owned(), message_id.to_owned(), cx);
1042 return;
1043 }
1044 plan => {
1045 if let Some(current) = self.current.as_mut() {
1046 current.window_request = None;
1047 if plan == JumpPlan::LeaveWindow {
1048 current.detached = None;
1049 }
1050 }
1051 }
1052 }
1053 }
1054 let Some(record) = record else {
1028 return;
1055 return;
1029 };
1056 };
1030 let messages_from_target = store
1057 let messages_from_target = store
@@ -1071,6 +1098,10 @@ impl ConversationView {
1071 };
1098 };
1072 self.reload_pending(cx);
1099 self.reload_pending(cx);
1073 self.rebuild(true, cx);
1100 self.rebuild(true, cx);
1101 self.reveal_row(target_key, cx);
1102 }
1103
1104 fn reveal_row(&mut self, target_key: String, cx: &mut Context<Self>) {
1074 let index = self
1105 let index = self
1075 .rows
1106 .rows
1076 .borrow()
1107 .borrow()
@@ -1360,16 +1391,33 @@ impl ConversationView {
1360 ViewMode::Thread(root_id) => Some(root_id.clone()),
1391 ViewMode::Thread(root_id) => Some(root_id.clone()),
1361 ViewMode::Flat | ViewMode::ThreadList => None,
1392 ViewMode::Flat | ViewMode::ThreadList => None,
1362 };
1393 };
1363 let records: Vec<MessageRecord> = match &thread_root {
1394 let sync_state = store.sync_state(&conversation_id).ok().flatten();
1364 Some(root_id) => store.thread_messages(&conversation_id, root_id),
1395 let window = current.detached.as_ref().map(|detached| {
1365 None => store.messages(&conversation_id, None, limit),
1396 (
1366 }
1397 detached.oldest,
1367 .unwrap_or_default();
1398 detached.newest,
1368 let sync_has_more = store
1399 detached.older_cursor.is_some(),
1369 .sync_state(&conversation_id)
1400 detached.newer_cursor.is_some(),
1370 .ok()
1401 )
1371 .flatten()
1402 });
1372 .is_none_or(|state| state.has_more);
1403 let records: Vec<MessageRecord> = match (&thread_root, window) {
1404 (Some(root_id), _) => store
1405 .thread_messages(&conversation_id, root_id)
1406 .unwrap_or_default(),
1407 (None, Some((oldest, newest, _, _))) => store
1408 .messages_between(&conversation_id, oldest, newest)
1409 .unwrap_or_default(),
1410 (None, None) if matches!(current.selection, Selection::Chat(_)) => without_islands(
1411 store
1412 .messages(&conversation_id, None, limit)
1413 .unwrap_or_default(),
1414 sync_state.as_ref().and_then(|state| state.oldest_loaded),
1415 ),
1416 (None, None) => store
1417 .messages(&conversation_id, None, limit)
1418 .unwrap_or_default(),
1419 };
1420 let sync_has_more = sync_state.as_ref().is_none_or(|state| state.has_more);
1373 let mut context = self.row_context(cx);
1421 let mut context = self.row_context(cx);
1374 let reactor_ids: Vec<String> = records
1422 let reactor_ids: Vec<String> = records
1375 .iter()
1423 .iter()
@@ -1407,14 +1455,24 @@ impl ConversationView {
1407 current.has_older = false;
1455 current.has_older = false;
1408 placeholder_rows()
1456 placeholder_rows()
1409 }
1457 }
1410 ViewMode::Flat => {
1458 ViewMode::Flat => match window {
1411 current.has_older = has_older;
1459 Some((_, _, has_older_window, has_newer_window)) => {
1412 let mut rows = flat_rows(&records, &context, has_older);
1460 current.has_older = has_older_window;
1413 if !has_older && let Some(start) = start {
1461 let mut rows = flat_rows(&records, &context, has_older_window);
1414 rows.insert(0, Row::Start(start));
1462 if has_newer_window {
1463 rows.push(Row::LoadNewer);
1464 }
1465 rows
1415 }
1466 }
1416 rows
1467 None => {
1417 }
1468 current.has_older = has_older;
1469 let mut rows = flat_rows(&records, &context, has_older);
1470 if !has_older && let Some(start) = start {
1471 rows.insert(0, Row::Start(start));
1472 }
1473 rows
1474 }
1475 },
1418 ViewMode::ThreadList => {
1476 ViewMode::ThreadList => {
1419 current.has_older = has_older;
1477 current.has_older = has_older;
1420 thread_list_rows(&records, &context, has_older)
1478 thread_list_rows(&records, &context, has_older)
@@ -1424,12 +1482,15 @@ impl ConversationView {
1424 thread_rows(&records, root_id, &context)
1482 thread_rows(&records, root_id, &context)
1425 }
1483 }
1426 };
1484 };
1427 let local: Vec<MessageRow> = self
1485 let local: Vec<MessageRow> = if window.is_some() {
1428 .pending
1486 Vec::new()
1429 .iter()
1487 } else {
1430 .cloned()
1488 self.pending
1431 .chain(self.scheduled_rows(context.my_user_id.as_deref(), cx))
1489 .iter()
1432 .collect();
1490 .cloned()
1491 .chain(self.scheduled_rows(context.my_user_id.as_deref(), cx))
1492 .collect()
1493 };
1433 if in_feed {
1494 if in_feed {
1434 place_local_rows(&mut rows, local);
1495 place_local_rows(&mut rows, local);
1435 } else {
1496 } else {
@@ -1454,6 +1515,10 @@ impl ConversationView {
1454 }
1515 }
1455 assign_series(&mut rows);
1516 assign_series(&mut rows);
1456 self.apply_rows(rows, reset, cx);
1517 self.apply_rows(rows, reset, cx);
1518 if self.is_detached() {
1519 self.scroller
1520 .update(cx, |scroller, _| scroller.stop_following());
1521 }
1457 }
1522 }
1458
1523
1459 fn apply_rows(&mut self, new_rows: Vec<Row>, reset: bool, cx: &mut Context<Self>) {
1524 fn apply_rows(&mut self, new_rows: Vec<Row>, reset: bool, cx: &mut Context<Self>) {
@@ -1823,6 +1888,9 @@ impl ConversationView {
1823 }
1888 }
1824
1889
1825 fn request_older(&mut self, cx: &mut Context<Self>) {
1890 fn request_older(&mut self, cx: &mut Context<Self>) {
1891 if self.is_detached() {
1892 return self.request_window_page(WindowDirection::Backward, cx);
1893 }
1826 let Some(engine) = self.app.read(cx).engine.clone() else {
1894 let Some(engine) = self.app.read(cx).engine.clone() else {
1827 return;
1895 return;
1828 };
1896 };
@@ -1952,6 +2020,7 @@ impl ConversationView {
1952 }
2020 }
1953
2021
1954 fn send(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
2022 fn send(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
2023 self.leave_detached(cx);
1955 self.send_as(new_outbox_id(), outgoing, None, window, cx);
2024 self.send_as(new_outbox_id(), outgoing, None, window, cx);
1956 }
2025 }
1957
2026
@@ -3143,8 +3212,11 @@ impl ConversationView {
3143 header_call_controls(&self.app, app, &current.selection)
3212 header_call_controls(&self.app, app, &current.selection)
3144 };
3213 };
3145 let sync = &current.sync;
3214 let sync = &current.sync;
3215 let loading_window = current.window_request.is_some();
3146 if sync.failed {
3216 if sync.failed {
3147 subline = "Not up to date".to_owned();
3217 subline = "Not up to date".to_owned();
3218 } else if loading_window {
3219 subline = "Loading message ...".to_owned();
3148 } else if sync.shown_at.is_some() {
3220 } else if sync.shown_at.is_some() {
3149 subline = if sync.slow {
3221 subline = if sync.slow {
3150 "Taking longer than usual ..."
3222 "Taking longer than usual ..."
@@ -3157,7 +3229,7 @@ impl ConversationView {
3157 }
3229 }
3158 header
3230 header
3159 .relative()
3231 .relative()
3160 .when(sync.shown_at.is_some(), |header| {
3232 .when(sync.shown_at.is_some() || loading_window, |header| {
3161 header.child(progress_bar())
3233 header.child(progress_bar())
3162 })
3234 })
3163 .children(lead)
3235 .children(lead)
@@ -3213,6 +3285,7 @@ impl Render for ConversationView {
3213 .into_any_element();
3285 .into_any_element();
3214 }
3286 }
3215 let in_feed = self.in_feed();
3287 let in_feed = self.in_feed();
3288 let detached = self.is_detached();
3216 let rows_seen = self.feed_rows_seen.replace(usize::MAX);
3289 let rows_seen = self.feed_rows_seen.replace(usize::MAX);
3217 if in_feed && rows_seen != usize::MAX {
3290 if in_feed && rows_seen != usize::MAX {
3218 self.feed_at_top = rows_seen == 0;
3291 self.feed_at_top = rows_seen == 0;
@@ -3262,6 +3335,25 @@ impl Render for ConversationView {
3262 .child("Loading older messages")
3335 .child("Loading older messages")
3263 .into_any_element()
3336 .into_any_element()
3264 }
3337 }
3338 Some(Row::LoadNewer) => {
3339 let view = env.view.clone();
3340 cx.defer(move |cx| {
3341 view.update(cx, |this, cx| {
3342 this.request_window_page(WindowDirection::Forward, cx)
3343 })
3344 .ok();
3345 });
3346 h_flex()
3347 .w_full()
3348 .py_2()
3349 .gap(px(6.))
3350 .justify_center()
3351 .text_size(px(12.))
3352 .text_color(theme::text_muted())
3353 .child(icon(IconName::Loader, 12., theme::text_muted()))
3354 .child("Loading newer messages")
3355 .into_any_element()
3356 }
3265 Some(Row::Start(start)) => {
3357 Some(Row::Start(start)) => {
3266 let state = env.app.read(cx);
3358 let state = env.app.read(cx);
3267 v_flex()
3359 v_flex()
@@ -3297,6 +3389,13 @@ impl Render for ConversationView {
3297 )
3389 )
3298 .with_row_style(StyleRefinement::default().px(px(0.)).pb(px(0.)))
3390 .with_row_style(StyleRefinement::default().px(px(0.)).pb(px(0.)))
3299 .jump_button(!in_feed)
3391 .jump_button(!in_feed)
3392 .force_jump_button(detached)
3393 .when(detached, |scroller| {
3394 let view = cx.weak_entity();
3395 scroller.on_jump(move |_, cx| {
3396 view.update(cx, |this, cx| this.leave_detached(cx)).ok();
3397 })
3398 })
3300 .with_bottom_fade(background);
3399 .with_bottom_fade(background);
3301
3400
3302 root = match self.current.as_ref().filter(|_| !drafting) {
3401 root = match self.current.as_ref().filter(|_| !drafting) {
crates/app/src/views/conversation/detached.rs added +261 −0
@@ -0,0 +1,261 @@
1 use chrono::{DateTime, Utc};
2 use gpui_kit::*;
3 use teams_core::{JumpPlan, WindowDirection, WindowPage, jump_plan};
4
5 use super::ConversationView;
6 use crate::notice::short_error;
7 use crate::runtime;
8
9 pub(super) struct DetachedWindow {
10 pub(super) anchor_id: String,
11 pub(super) oldest: DateTime<Utc>,
12 pub(super) newest: DateTime<Utc>,
13 pub(super) older_cursor: Option<String>,
14 pub(super) newer_cursor: Option<String>,
15 pub(super) loading: bool,
16 }
17
18 impl ConversationView {
19 pub(super) fn is_detached(&self) -> bool {
20 self.current
21 .as_ref()
22 .is_some_and(|current| current.detached.is_some())
23 }
24
25 pub(super) fn jump_plan_for(
26 &self,
27 chat_id: &str,
28 target_created_at: Option<DateTime<Utc>>,
29 cx: &App,
30 ) -> JumpPlan {
31 let oldest_loaded = self
32 .app
33 .read(cx)
34 .store
35 .sync_state(chat_id)
36 .ok()
37 .flatten()
38 .and_then(|state| state.oldest_loaded);
39 let window = self
40 .current
41 .as_ref()
42 .and_then(|current| current.detached.as_ref())
43 .map(|detached| (detached.oldest, detached.newest));
44 jump_plan(window, target_created_at, oldest_loaded)
45 }
46
47 pub(super) fn open_detached(
48 &mut self,
49 chat_id: String,
50 message_id: String,
51 cx: &mut Context<Self>,
52 ) {
53 let Some(engine) = self.app.read(cx).engine.clone() else {
54 return;
55 };
56 let Some(current) = self.current.as_mut() else {
57 return;
58 };
59 if current.window_request.as_deref() == Some(message_id.as_str()) {
60 return;
61 }
62 current.window_request = Some(message_id.clone());
63 cx.notify();
64 let task_chat_id = chat_id.clone();
65 let task_message_id = message_id.clone();
66 let receiver =
67 runtime::spawn(
68 async move { engine.load_window(&task_chat_id, &task_message_id).await },
69 );
70 cx.spawn(async move |this, cx| {
71 let result = receiver.await;
72 this.update(cx, |this, cx| {
73 this.finish_open_detached(&chat_id, message_id, result, cx)
74 })
75 .ok();
76 })
77 .detach();
78 }
79
80 fn finish_open_detached(
81 &mut self,
82 chat_id: &str,
83 message_id: String,
84 result: Result<teams_core::Result<WindowPage>, tokio::sync::oneshot::error::RecvError>,
85 cx: &mut Context<Self>,
86 ) {
87 if self.chat_id().as_deref() != Some(chat_id) {
88 return;
89 }
90 let Some(current) = self
91 .current
92 .as_mut()
93 .filter(|current| current.window_request.as_deref() == Some(message_id.as_str()))
94 else {
95 return;
96 };
97 current.window_request = None;
98 cx.notify();
99 let page = match result {
100 Ok(Ok(page)) => page,
101 Ok(Err(error)) => {
102 self.notice = Some(format!(
103 "Could not load the message: {}",
104 short_error(&error)
105 ));
106 cx.notify();
107 return;
108 }
109 Err(_) => return,
110 };
111 let (Some(oldest), Some(newest)) = (page.oldest, page.newest) else {
112 self.notice = Some("Could not find the message".to_owned());
113 cx.notify();
114 return;
115 };
116 let Some(current) = self.current.as_mut() else {
117 return;
118 };
119 current.first_unread = None;
120 current.detached = Some(DetachedWindow {
121 anchor_id: message_id.clone(),
122 oldest,
123 newest,
124 older_cursor: page.older_cursor,
125 newer_cursor: page.newer_cursor,
126 loading: false,
127 });
128 self.reload_pending(cx);
129 self.rebuild(true, cx);
130 self.reveal_row(message_id, cx);
131 }
132
133 pub(super) fn leave_detached(&mut self, cx: &mut Context<Self>) {
134 let Some(current) = self.current.as_mut() else {
135 return;
136 };
137 if current.detached.take().is_none() {
138 return;
139 }
140 self.rebuild(true, cx);
141 }
142
143 pub(super) fn request_window_page(
144 &mut self,
145 direction: WindowDirection,
146 cx: &mut Context<Self>,
147 ) {
148 let Some(engine) = self.app.read(cx).engine.clone() else {
149 return;
150 };
151 let Some(chat_id) = self.chat_id() else {
152 return;
153 };
154 let Some(detached) = self
155 .current
156 .as_mut()
157 .and_then(|current| current.detached.as_mut())
158 else {
159 return;
160 };
161 let cursor = match direction {
162 WindowDirection::Backward => detached.older_cursor.clone(),
163 WindowDirection::Forward => detached.newer_cursor.clone(),
164 WindowDirection::Bidirectional => None,
165 };
166 let Some(cursor) = cursor.filter(|_| !detached.loading) else {
167 return;
168 };
169 detached.loading = true;
170 let anchor_id = detached.anchor_id.clone();
171 let task_chat_id = chat_id.clone();
172 let receiver = runtime::spawn(async move {
173 engine
174 .load_window_page(&task_chat_id, &cursor, direction)
175 .await
176 });
177 cx.spawn(async move |this, cx| {
178 let result = receiver.await;
179 this.update(cx, |this, cx| {
180 this.finish_window_page(&chat_id, &anchor_id, direction, result, cx)
181 })
182 .ok();
183 })
184 .detach();
185 }
186
187 fn finish_window_page(
188 &mut self,
189 chat_id: &str,
190 anchor_id: &str,
191 direction: WindowDirection,
192 result: Result<teams_core::Result<WindowPage>, tokio::sync::oneshot::error::RecvError>,
193 cx: &mut Context<Self>,
194 ) {
195 if self.chat_id().as_deref() != Some(chat_id) {
196 return;
197 }
198 let Some(detached) = self
199 .current
200 .as_mut()
201 .and_then(|current| current.detached.as_mut())
202 .filter(|detached| detached.anchor_id == anchor_id)
203 else {
204 return;
205 };
206 detached.loading = false;
207 let page = match result {
208 Ok(Ok(page)) => page,
209 failure => {
210 match direction {
211 WindowDirection::Backward => detached.older_cursor = None,
212 _ => detached.newer_cursor = None,
213 }
214 if let Ok(Err(error)) = failure {
215 self.notice = Some(format!("Could not load messages: {}", short_error(&error)));
216 }
217 self.rebuild(false, cx);
218 return;
219 }
220 };
221 match direction {
222 WindowDirection::Backward => {
223 detached.older_cursor = page.older_cursor;
224 detached.oldest = page
225 .oldest
226 .map_or(detached.oldest, |oldest| oldest.min(detached.oldest));
227 }
228 _ => {
229 detached.newer_cursor = page.newer_cursor;
230 detached.newest = page
231 .newest
232 .map_or(detached.newest, |newest| newest.max(detached.newest));
233 }
234 }
235 let reached_latest = direction == WindowDirection::Forward
236 && (detached.newer_cursor.is_none() || self.window_reaches_newest_cached(chat_id, cx));
237 if reached_latest {
238 self.leave_detached(cx);
239 } else {
240 self.rebuild(false, cx);
241 }
242 }
243
244 fn window_reaches_newest_cached(&self, chat_id: &str, cx: &App) -> bool {
245 let Some(newest) = self
246 .current
247 .as_ref()
248 .and_then(|current| current.detached.as_ref())
249 .map(|detached| detached.newest)
250 else {
251 return false;
252 };
253 self.app
254 .read(cx)
255 .store
256 .messages(chat_id, None, 1)
257 .ok()
258 .and_then(|latest| latest.last().map(|record| record.created_at))
259 .is_none_or(|latest| newest >= latest)
260 }
261 }
@@ -0,0 +1,261 @@
1use chrono::{DateTime, Utc};
2use gpui_kit::*;
3use teams_core::{JumpPlan, WindowDirection, WindowPage, jump_plan};
4
5use super::ConversationView;
6use crate::notice::short_error;
7use crate::runtime;
8
9pub(super) struct DetachedWindow {
10 pub(super) anchor_id: String,
11 pub(super) oldest: DateTime<Utc>,
12 pub(super) newest: DateTime<Utc>,
13 pub(super) older_cursor: Option<String>,
14 pub(super) newer_cursor: Option<String>,
15 pub(super) loading: bool,
16}
17
18impl ConversationView {
19 pub(super) fn is_detached(&self) -> bool {
20 self.current
21 .as_ref()
22 .is_some_and(|current| current.detached.is_some())
23 }
24
25 pub(super) fn jump_plan_for(
26 &self,
27 chat_id: &str,
28 target_created_at: Option<DateTime<Utc>>,
29 cx: &App,
30 ) -> JumpPlan {
31 let oldest_loaded = self
32 .app
33 .read(cx)
34 .store
35 .sync_state(chat_id)
36 .ok()
37 .flatten()
38 .and_then(|state| state.oldest_loaded);
39 let window = self
40 .current
41 .as_ref()
42 .and_then(|current| current.detached.as_ref())
43 .map(|detached| (detached.oldest, detached.newest));
44 jump_plan(window, target_created_at, oldest_loaded)
45 }
46
47 pub(super) fn open_detached(
48 &mut self,
49 chat_id: String,
50 message_id: String,
51 cx: &mut Context<Self>,
52 ) {
53 let Some(engine) = self.app.read(cx).engine.clone() else {
54 return;
55 };
56 let Some(current) = self.current.as_mut() else {
57 return;
58 };
59 if current.window_request.as_deref() == Some(message_id.as_str()) {
60 return;
61 }
62 current.window_request = Some(message_id.clone());
63 cx.notify();
64 let task_chat_id = chat_id.clone();
65 let task_message_id = message_id.clone();
66 let receiver =
67 runtime::spawn(
68 async move { engine.load_window(&task_chat_id, &task_message_id).await },
69 );
70 cx.spawn(async move |this, cx| {
71 let result = receiver.await;
72 this.update(cx, |this, cx| {
73 this.finish_open_detached(&chat_id, message_id, result, cx)
74 })
75 .ok();
76 })
77 .detach();
78 }
79
80 fn finish_open_detached(
81 &mut self,
82 chat_id: &str,
83 message_id: String,
84 result: Result<teams_core::Result<WindowPage>, tokio::sync::oneshot::error::RecvError>,
85 cx: &mut Context<Self>,
86 ) {
87 if self.chat_id().as_deref() != Some(chat_id) {
88 return;
89 }
90 let Some(current) = self
91 .current
92 .as_mut()
93 .filter(|current| current.window_request.as_deref() == Some(message_id.as_str()))
94 else {
95 return;
96 };
97 current.window_request = None;
98 cx.notify();
99 let page = match result {
100 Ok(Ok(page)) => page,
101 Ok(Err(error)) => {
102 self.notice = Some(format!(
103 "Could not load the message: {}",
104 short_error(&error)
105 ));
106 cx.notify();
107 return;
108 }
109 Err(_) => return,
110 };
111 let (Some(oldest), Some(newest)) = (page.oldest, page.newest) else {
112 self.notice = Some("Could not find the message".to_owned());
113 cx.notify();
114 return;
115 };
116 let Some(current) = self.current.as_mut() else {
117 return;
118 };
119 current.first_unread = None;
120 current.detached = Some(DetachedWindow {
121 anchor_id: message_id.clone(),
122 oldest,
123 newest,
124 older_cursor: page.older_cursor,
125 newer_cursor: page.newer_cursor,
126 loading: false,
127 });
128 self.reload_pending(cx);
129 self.rebuild(true, cx);
130 self.reveal_row(message_id, cx);
131 }
132
133 pub(super) fn leave_detached(&mut self, cx: &mut Context<Self>) {
134 let Some(current) = self.current.as_mut() else {
135 return;
136 };
137 if current.detached.take().is_none() {
138 return;
139 }
140 self.rebuild(true, cx);
141 }
142
143 pub(super) fn request_window_page(
144 &mut self,
145 direction: WindowDirection,
146 cx: &mut Context<Self>,
147 ) {
148 let Some(engine) = self.app.read(cx).engine.clone() else {
149 return;
150 };
151 let Some(chat_id) = self.chat_id() else {
152 return;
153 };
154 let Some(detached) = self
155 .current
156 .as_mut()
157 .and_then(|current| current.detached.as_mut())
158 else {
159 return;
160 };
161 let cursor = match direction {
162 WindowDirection::Backward => detached.older_cursor.clone(),
163 WindowDirection::Forward => detached.newer_cursor.clone(),
164 WindowDirection::Bidirectional => None,
165 };
166 let Some(cursor) = cursor.filter(|_| !detached.loading) else {
167 return;
168 };
169 detached.loading = true;
170 let anchor_id = detached.anchor_id.clone();
171 let task_chat_id = chat_id.clone();
172 let receiver = runtime::spawn(async move {
173 engine
174 .load_window_page(&task_chat_id, &cursor, direction)
175 .await
176 });
177 cx.spawn(async move |this, cx| {
178 let result = receiver.await;
179 this.update(cx, |this, cx| {
180 this.finish_window_page(&chat_id, &anchor_id, direction, result, cx)
181 })
182 .ok();
183 })
184 .detach();
185 }
186
187 fn finish_window_page(
188 &mut self,
189 chat_id: &str,
190 anchor_id: &str,
191 direction: WindowDirection,
192 result: Result<teams_core::Result<WindowPage>, tokio::sync::oneshot::error::RecvError>,
193 cx: &mut Context<Self>,
194 ) {
195 if self.chat_id().as_deref() != Some(chat_id) {
196 return;
197 }
198 let Some(detached) = self
199 .current
200 .as_mut()
201 .and_then(|current| current.detached.as_mut())
202 .filter(|detached| detached.anchor_id == anchor_id)
203 else {
204 return;
205 };
206 detached.loading = false;
207 let page = match result {
208 Ok(Ok(page)) => page,
209 failure => {
210 match direction {
211 WindowDirection::Backward => detached.older_cursor = None,
212 _ => detached.newer_cursor = None,
213 }
214 if let Ok(Err(error)) = failure {
215 self.notice = Some(format!("Could not load messages: {}", short_error(&error)));
216 }
217 self.rebuild(false, cx);
218 return;
219 }
220 };
221 match direction {
222 WindowDirection::Backward => {
223 detached.older_cursor = page.older_cursor;
224 detached.oldest = page
225 .oldest
226 .map_or(detached.oldest, |oldest| oldest.min(detached.oldest));
227 }
228 _ => {
229 detached.newer_cursor = page.newer_cursor;
230 detached.newest = page
231 .newest
232 .map_or(detached.newest, |newest| newest.max(detached.newest));
233 }
234 }
235 let reached_latest = direction == WindowDirection::Forward
236 && (detached.newer_cursor.is_none() || self.window_reaches_newest_cached(chat_id, cx));
237 if reached_latest {
238 self.leave_detached(cx);
239 } else {
240 self.rebuild(false, cx);
241 }
242 }
243
244 fn window_reaches_newest_cached(&self, chat_id: &str, cx: &App) -> bool {
245 let Some(newest) = self
246 .current
247 .as_ref()
248 .and_then(|current| current.detached.as_ref())
249 .map(|detached| detached.newest)
250 else {
251 return false;
252 };
253 self.app
254 .read(cx)
255 .store
256 .messages(chat_id, None, 1)
257 .ok()
258 .and_then(|latest| latest.last().map(|record| record.created_at))
259 .is_none_or(|latest| newest >= latest)
260 }
261}
crates/app/src/views/conversation/pins.rs +58 −8
@@ -1,10 +1,13 @@
1 use std::collections::HashMap;
1 2 use std::rc::Rc;
2 3
3 4 use gpui_kit::*;
5 use store::MessageRecord;
4 6
5 7 use super::ConversationView;
6 8 use crate::app_state::Selection;
7 9 use crate::rows::reply_excerpt;
10 use crate::runtime;
8 11 use crate::views::message_actions::Action;
9 12 use crate::views::pin_banner::{PinBannerActions, PinBannerData, cycle_pin, render_pin_banner};
10 13
@@ -13,6 +16,15 @@ pub(super) struct PinPreview {
13 16 text: String,
14 17 }
15 18
19 impl PinPreview {
20 fn of(record: &MessageRecord) -> Self {
21 PinPreview {
22 author: record.sender_name.clone(),
23 text: reply_excerpt(record),
24 }
25 }
26 }
27
16 28 impl ConversationView {
17 29 pub(super) fn chat_id(&self) -> Option<String> {
18 30 match self.current.as_ref()?.selection {
@@ -23,6 +35,7 @@ impl ConversationView {
23 35
24 36 pub(super) fn refresh_pin_previews(&mut self, cx: &mut Context<Self>) {
25 37 self.pin_previews.clear();
38 self.pin_fetches.clear();
26 39 self.pin_index = 0;
27 40 let Some(chat_id) = self.chat_id() else {
28 41 return;
@@ -51,20 +64,57 @@ impl ConversationView {
51 64 .store
52 65 .messages_by_id(chat_id, &ids)
53 66 .unwrap_or_default();
54 self.pin_previews = records
67 let mut previews: HashMap<String, PinPreview> = records
55 68 .into_iter()
56 .map(|(message_id, record)| {
57 let preview = PinPreview {
58 author: record.sender_name.clone(),
59 text: reply_excerpt(&record),
60 };
61 (message_id, preview)
62 })
69 .map(|(message_id, record)| (message_id, PinPreview::of(&record)))
63 70 .collect();
71 for id in &ids {
72 if !previews.contains_key(id)
73 && let Some(preview) = self.pin_previews.remove(id)
74 {
75 previews.insert(id.clone(), preview);
76 }
77 }
78 self.pin_previews = previews;
64 79 let count = ids.len();
65 80 if self.pin_index >= count {
66 81 self.pin_index = 0;
67 82 }
83 for id in ids {
84 if !self.pin_previews.contains_key(&id) {
85 self.fetch_pin_preview(chat_id, id, cx);
86 }
87 }
88 }
89
90 fn fetch_pin_preview(&mut self, chat_id: &str, message_id: String, cx: &mut Context<Self>) {
91 let Some(engine) = self.app.read(cx).engine.clone() else {
92 return;
93 };
94 if !self.pin_fetches.insert(message_id.clone()) {
95 return;
96 }
97 let chat_id = chat_id.to_owned();
98 let task_chat_id = chat_id.clone();
99 let task_message_id = message_id.clone();
100 let receiver = runtime::spawn(async move {
101 engine
102 .fetch_chat_message(&task_chat_id, &task_message_id)
103 .await
104 });
105 cx.spawn(async move |this, cx| {
106 let Ok(Ok(Some(record))) = receiver.await else {
107 return;
108 };
109 this.update(cx, |this, cx| {
110 if this.chat_id().as_deref() == Some(chat_id.as_str()) {
111 this.pin_previews.insert(message_id, PinPreview::of(&record));
112 cx.notify();
113 }
114 })
115 .ok();
116 })
117 .detach();
68 118 }
69 119
70 120 fn pin_action(
@@ -1,10 +1,13 @@
1use std::collections::HashMap;
1use std::rc::Rc;
2use std::rc::Rc;
2
3
3use gpui_kit::*;
4use gpui_kit::*;
5use store::MessageRecord;
4
6
5use super::ConversationView;
7use super::ConversationView;
6use crate::app_state::Selection;
8use crate::app_state::Selection;
7use crate::rows::reply_excerpt;
9use crate::rows::reply_excerpt;
10use crate::runtime;
8use crate::views::message_actions::Action;
11use crate::views::message_actions::Action;
9use crate::views::pin_banner::{PinBannerActions, PinBannerData, cycle_pin, render_pin_banner};
12use crate::views::pin_banner::{PinBannerActions, PinBannerData, cycle_pin, render_pin_banner};
10
13
@@ -13,6 +16,15 @@ pub(super) struct PinPreview {
13 text: String,
16 text: String,
14}
17}
15
18
19impl PinPreview {
20 fn of(record: &MessageRecord) -> Self {
21 PinPreview {
22 author: record.sender_name.clone(),
23 text: reply_excerpt(record),
24 }
25 }
26}
27
16impl ConversationView {
28impl ConversationView {
17 pub(super) fn chat_id(&self) -> Option<String> {
29 pub(super) fn chat_id(&self) -> Option<String> {
18 match self.current.as_ref()?.selection {
30 match self.current.as_ref()?.selection {
@@ -23,6 +35,7 @@ impl ConversationView {
23
35
24 pub(super) fn refresh_pin_previews(&mut self, cx: &mut Context<Self>) {
36 pub(super) fn refresh_pin_previews(&mut self, cx: &mut Context<Self>) {
25 self.pin_previews.clear();
37 self.pin_previews.clear();
38 self.pin_fetches.clear();
26 self.pin_index = 0;
39 self.pin_index = 0;
27 let Some(chat_id) = self.chat_id() else {
40 let Some(chat_id) = self.chat_id() else {
28 return;
41 return;
@@ -51,20 +64,57 @@ impl ConversationView {
51 .store
64 .store
52 .messages_by_id(chat_id, &ids)
65 .messages_by_id(chat_id, &ids)
53 .unwrap_or_default();
66 .unwrap_or_default();
54 self.pin_previews = records
67 let mut previews: HashMap<String, PinPreview> = records
55 .into_iter()
68 .into_iter()
56 .map(|(message_id, record)| {
69 .map(|(message_id, record)| (message_id, PinPreview::of(&record)))
57 let preview = PinPreview {
58 author: record.sender_name.clone(),
59 text: reply_excerpt(&record),
60 };
61 (message_id, preview)
62 })
63 .collect();
70 .collect();
71 for id in &ids {
72 if !previews.contains_key(id)
73 && let Some(preview) = self.pin_previews.remove(id)
74 {
75 previews.insert(id.clone(), preview);
76 }
77 }
78 self.pin_previews = previews;
64 let count = ids.len();
79 let count = ids.len();
65 if self.pin_index >= count {
80 if self.pin_index >= count {
66 self.pin_index = 0;
81 self.pin_index = 0;
67 }
82 }
83 for id in ids {
84 if !self.pin_previews.contains_key(&id) {
85 self.fetch_pin_preview(chat_id, id, cx);
86 }
87 }
88 }
89
90 fn fetch_pin_preview(&mut self, chat_id: &str, message_id: String, cx: &mut Context<Self>) {
91 let Some(engine) = self.app.read(cx).engine.clone() else {
92 return;
93 };
94 if !self.pin_fetches.insert(message_id.clone()) {
95 return;
96 }
97 let chat_id = chat_id.to_owned();
98 let task_chat_id = chat_id.clone();
99 let task_message_id = message_id.clone();
100 let receiver = runtime::spawn(async move {
101 engine
102 .fetch_chat_message(&task_chat_id, &task_message_id)
103 .await
104 });
105 cx.spawn(async move |this, cx| {
106 let Ok(Ok(Some(record))) = receiver.await else {
107 return;
108 };
109 this.update(cx, |this, cx| {
110 if this.chat_id().as_deref() == Some(chat_id.as_str()) {
111 this.pin_previews.insert(message_id, PinPreview::of(&record));
112 cx.notify();
113 }
114 })
115 .ok();
116 })
117 .detach();
68 }
118 }
69
119
70 fn pin_action(
120 fn pin_action(
crates/chatsvc/src/lib.rs +2 −0
@@ -20,6 +20,7 @@ pub mod saved;
20 20 pub mod settings;
21 21 pub mod transcripts;
22 22 pub mod translate;
23 pub mod window;
23 24
24 25 pub use calendar::{Calendar, CalendarEvent, ResponseType, meet_now_join_url, parse_calendar_events};
25 26 pub use calllog::{CallDirection, CallLogEntry, CallOutcome};
@@ -61,3 +62,4 @@ pub use translate::{
61 62 Language, MAX_TRANSLATE_BATCH, MessageLanguage, TranslateRequest, Translation,
62 63 TranslationStatus, TranslationTrigger, Translator, language_code,
63 64 };
65 pub use window::{MessageWindow, WindowDirection};
@@ -20,6 +20,7 @@ pub mod saved;
20pub mod settings;
20pub mod settings;
21pub mod transcripts;
21pub mod transcripts;
22pub mod translate;
22pub mod translate;
23pub mod window;
23
24
24pub use calendar::{Calendar, CalendarEvent, ResponseType, meet_now_join_url, parse_calendar_events};
25pub use calendar::{Calendar, CalendarEvent, ResponseType, meet_now_join_url, parse_calendar_events};
25pub use calllog::{CallDirection, CallLogEntry, CallOutcome};
26pub use calllog::{CallDirection, CallLogEntry, CallOutcome};
@@ -61,3 +62,4 @@ pub use translate::{
61 Language, MAX_TRANSLATE_BATCH, MessageLanguage, TranslateRequest, Translation,
62 Language, MAX_TRANSLATE_BATCH, MessageLanguage, TranslateRequest, Translation,
62 TranslationStatus, TranslationTrigger, Translator, language_code,
63 TranslationStatus, TranslationTrigger, Translator, language_code,
63};
64};
65pub use window::{MessageWindow, WindowDirection};
crates/chatsvc/src/window.rs added +211 −0
@@ -0,0 +1,211 @@
1 use serde_json::Value;
2 use session::Request;
3
4 use crate::error::{Error, Result};
5 use crate::messages::{MessageTransport, Messages, encode, ensure_success};
6
7 const EPOCH_SEGMENT: &str = "epochTimeStamp/";
8
9 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
10 pub enum WindowDirection {
11 Bidirectional,
12 Backward,
13 Forward,
14 }
15
16 impl WindowDirection {
17 fn query_value(self) -> &'static str {
18 match self {
19 WindowDirection::Bidirectional => "BIDIRECTIONAL",
20 WindowDirection::Backward => "BACKWARD",
21 WindowDirection::Forward => "FORWARD",
22 }
23 }
24 }
25
26 #[derive(Debug, Clone, PartialEq, Eq)]
27 pub struct MessageWindow {
28 pub message_ids: Vec<String>,
29 pub older_cursor: Option<String>,
30 pub newer_cursor: Option<String>,
31 }
32
33 fn is_user_message(message: &Value) -> bool {
34 message
35 .get("messagetype")
36 .and_then(Value::as_str)
37 .is_some_and(|kind| kind == "Text" || kind.starts_with("RichText"))
38 }
39
40 fn message_id(message: &Value) -> Option<String> {
41 match message.get("id")? {
42 Value::String(text) if !text.is_empty() => Some(text.clone()),
43 Value::Number(number) => Some(number.to_string()),
44 _ => None,
45 }
46 }
47
48 fn cursor_of(body: &Value, link_key: &str) -> Option<String> {
49 let link = body.pointer(&format!("/_metadata/{link_key}"))?.as_str()?;
50 let tail = &link[link.find(EPOCH_SEGMENT)? + EPOCH_SEGMENT.len()..];
51 let number = tail.split(['?', '/']).next()?;
52 (!number.is_empty() && number.bytes().all(|byte| byte.is_ascii_digit()))
53 .then(|| number.to_owned())
54 }
55
56 pub fn parse_message_window(body: &Value) -> Result<MessageWindow> {
57 let messages = body
58 .get("messages")
59 .and_then(Value::as_array)
60 .ok_or_else(|| Error::UnexpectedAnswer("no messages list".into()))?;
61 Ok(MessageWindow {
62 message_ids: messages
63 .iter()
64 .filter(|message| is_user_message(message))
65 .filter_map(message_id)
66 .collect(),
67 older_cursor: cursor_of(body, "backwardLink"),
68 newer_cursor: cursor_of(body, "forwardLink"),
69 })
70 }
71
72 impl<T: MessageTransport> Messages<T> {
73 pub fn message_window_url(
74 &self,
75 chat_id: &str,
76 anchor_id: &str,
77 direction: WindowDirection,
78 page_size: usize,
79 ) -> String {
80 format!(
81 "{}/{}/messages/{EPOCH_SEGMENT}{}?pageSize={page_size}&direction={}&includeMetadata=true&locationType=Primary",
82 self.base_url,
83 encode(chat_id),
84 encode(anchor_id),
85 direction.query_value()
86 )
87 }
88
89 pub async fn message_window(
90 &self,
91 chat_id: &str,
92 anchor_id: &str,
93 direction: WindowDirection,
94 page_size: usize,
95 ) -> Result<MessageWindow> {
96 let url = self.message_window_url(chat_id, anchor_id, direction, page_size);
97 let answer = self.transport.send(Request::get(url)).await?;
98 ensure_success(&answer)?;
99 parse_message_window(&answer.body)
100 }
101 }
102
103 #[cfg(test)]
104 mod tests {
105 use std::sync::Mutex;
106
107 use serde_json::json;
108 use session::{ApiResponse, Method};
109
110 use super::*;
111
112 struct Canned {
113 body: Value,
114 requests: Mutex<Vec<Request>>,
115 }
116
117 impl MessageTransport for Canned {
118 async fn send(&self, request: Request) -> Result<ApiResponse> {
119 self.requests.lock().unwrap().push(request);
120 Ok(ApiResponse {
121 status: 200,
122 body: self.body.clone(),
123 retry_after: None,
124 })
125 }
126 }
127
128 fn fixture() -> Value {
129 json!({
130 "messages": [
131 {"id": "1791368000030", "messagetype": "RichText/Html"},
132 {"id": "1791368000025", "messagetype": "ThreadActivity/AddMember"},
133 {"id": "1791368000020", "messagetype": "Text"},
134 {"id": "1791368000015", "messagetype": "Event/Call"},
135 {"id": 1791368000010u64, "messagetype": "RichText/Media_Card"},
136 ],
137 "_metadata": {
138 "backwardLink": "https://emea.ng.msg.teams.microsoft.com/v1/users/ME/conversations/19%3Aabc%40thread.v2/messages/epochTimeStamp/1791368000009?pageSize=20&direction=BACKWARD&includeMetadata=true",
139 "forwardLink": "https://other.host/v1/users/ME/conversations/19%3Aabc%40thread.v2/messages/epochTimeStamp/1791368000031?pageSize=20&direction=FORWARD",
140 }
141 })
142 }
143
144 #[test]
145 fn parses_user_messages_and_cursors() {
146 let window = parse_message_window(&fixture()).unwrap();
147 assert_eq!(
148 window.message_ids,
149 ["1791368000030", "1791368000020", "1791368000010"]
150 );
151 assert_eq!(window.older_cursor.as_deref(), Some("1791368000009"));
152 assert_eq!(window.newer_cursor.as_deref(), Some("1791368000031"));
153 }
154
155 #[test]
156 fn absent_links_mean_no_more_pages() {
157 let window = parse_message_window(&json!({
158 "messages": [{"id": "1", "messagetype": "Text"}],
159 "_metadata": {}
160 }))
161 .unwrap();
162 assert_eq!(window.older_cursor, None);
163 assert_eq!(window.newer_cursor, None);
164 let without_metadata = parse_message_window(&json!({"messages": []})).unwrap();
165 assert_eq!(without_metadata.older_cursor, None);
166 }
167
168 #[test]
169 fn link_without_a_number_gives_no_cursor() {
170 let window = parse_message_window(&json!({
171 "messages": [],
172 "_metadata": {"backwardLink": "https://h/messages/epochTimeStamp/?x=1"}
173 }))
174 .unwrap();
175 assert_eq!(window.older_cursor, None);
176 }
177
178 #[test]
179 fn missing_messages_is_unexpected() {
180 assert!(matches!(
181 parse_message_window(&json!({})),
182 Err(Error::UnexpectedAnswer(_))
183 ));
184 }
185
186 #[tokio::test]
187 async fn requests_the_window_around_the_anchor() {
188 let messages = Messages::with_transport(
189 Canned {
190 body: fixture(),
191 requests: Mutex::new(Vec::new()),
192 },
193 "emea",
194 );
195 messages
196 .message_window(
197 "19:abc@thread.v2",
198 "1791368000020",
199 WindowDirection::Bidirectional,
200 20,
201 )
202 .await
203 .unwrap();
204 let requests = messages.transport.requests.lock().unwrap();
205 assert_eq!(requests[0].method, Method::Get);
206 assert_eq!(
207 requests[0].url,
208 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations/19%3Aabc%40thread.v2/messages/epochTimeStamp/1791368000020?pageSize=20&direction=BIDIRECTIONAL&includeMetadata=true&locationType=Primary"
209 );
210 }
211 }
@@ -0,0 +1,211 @@
1use serde_json::Value;
2use session::Request;
3
4use crate::error::{Error, Result};
5use crate::messages::{MessageTransport, Messages, encode, ensure_success};
6
7const EPOCH_SEGMENT: &str = "epochTimeStamp/";
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum WindowDirection {
11 Bidirectional,
12 Backward,
13 Forward,
14}
15
16impl WindowDirection {
17 fn query_value(self) -> &'static str {
18 match self {
19 WindowDirection::Bidirectional => "BIDIRECTIONAL",
20 WindowDirection::Backward => "BACKWARD",
21 WindowDirection::Forward => "FORWARD",
22 }
23 }
24}
25
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct MessageWindow {
28 pub message_ids: Vec<String>,
29 pub older_cursor: Option<String>,
30 pub newer_cursor: Option<String>,
31}
32
33fn is_user_message(message: &Value) -> bool {
34 message
35 .get("messagetype")
36 .and_then(Value::as_str)
37 .is_some_and(|kind| kind == "Text" || kind.starts_with("RichText"))
38}
39
40fn message_id(message: &Value) -> Option<String> {
41 match message.get("id")? {
42 Value::String(text) if !text.is_empty() => Some(text.clone()),
43 Value::Number(number) => Some(number.to_string()),
44 _ => None,
45 }
46}
47
48fn cursor_of(body: &Value, link_key: &str) -> Option<String> {
49 let link = body.pointer(&format!("/_metadata/{link_key}"))?.as_str()?;
50 let tail = &link[link.find(EPOCH_SEGMENT)? + EPOCH_SEGMENT.len()..];
51 let number = tail.split(['?', '/']).next()?;
52 (!number.is_empty() && number.bytes().all(|byte| byte.is_ascii_digit()))
53 .then(|| number.to_owned())
54}
55
56pub fn parse_message_window(body: &Value) -> Result<MessageWindow> {
57 let messages = body
58 .get("messages")
59 .and_then(Value::as_array)
60 .ok_or_else(|| Error::UnexpectedAnswer("no messages list".into()))?;
61 Ok(MessageWindow {
62 message_ids: messages
63 .iter()
64 .filter(|message| is_user_message(message))
65 .filter_map(message_id)
66 .collect(),
67 older_cursor: cursor_of(body, "backwardLink"),
68 newer_cursor: cursor_of(body, "forwardLink"),
69 })
70}
71
72impl<T: MessageTransport> Messages<T> {
73 pub fn message_window_url(
74 &self,
75 chat_id: &str,
76 anchor_id: &str,
77 direction: WindowDirection,
78 page_size: usize,
79 ) -> String {
80 format!(
81 "{}/{}/messages/{EPOCH_SEGMENT}{}?pageSize={page_size}&direction={}&includeMetadata=true&locationType=Primary",
82 self.base_url,
83 encode(chat_id),
84 encode(anchor_id),
85 direction.query_value()
86 )
87 }
88
89 pub async fn message_window(
90 &self,
91 chat_id: &str,
92 anchor_id: &str,
93 direction: WindowDirection,
94 page_size: usize,
95 ) -> Result<MessageWindow> {
96 let url = self.message_window_url(chat_id, anchor_id, direction, page_size);
97 let answer = self.transport.send(Request::get(url)).await?;
98 ensure_success(&answer)?;
99 parse_message_window(&answer.body)
100 }
101}
102
103#[cfg(test)]
104mod tests {
105 use std::sync::Mutex;
106
107 use serde_json::json;
108 use session::{ApiResponse, Method};
109
110 use super::*;
111
112 struct Canned {
113 body: Value,
114 requests: Mutex<Vec<Request>>,
115 }
116
117 impl MessageTransport for Canned {
118 async fn send(&self, request: Request) -> Result<ApiResponse> {
119 self.requests.lock().unwrap().push(request);
120 Ok(ApiResponse {
121 status: 200,
122 body: self.body.clone(),
123 retry_after: None,
124 })
125 }
126 }
127
128 fn fixture() -> Value {
129 json!({
130 "messages": [
131 {"id": "1791368000030", "messagetype": "RichText/Html"},
132 {"id": "1791368000025", "messagetype": "ThreadActivity/AddMember"},
133 {"id": "1791368000020", "messagetype": "Text"},
134 {"id": "1791368000015", "messagetype": "Event/Call"},
135 {"id": 1791368000010u64, "messagetype": "RichText/Media_Card"},
136 ],
137 "_metadata": {
138 "backwardLink": "https://emea.ng.msg.teams.microsoft.com/v1/users/ME/conversations/19%3Aabc%40thread.v2/messages/epochTimeStamp/1791368000009?pageSize=20&direction=BACKWARD&includeMetadata=true",
139 "forwardLink": "https://other.host/v1/users/ME/conversations/19%3Aabc%40thread.v2/messages/epochTimeStamp/1791368000031?pageSize=20&direction=FORWARD",
140 }
141 })
142 }
143
144 #[test]
145 fn parses_user_messages_and_cursors() {
146 let window = parse_message_window(&fixture()).unwrap();
147 assert_eq!(
148 window.message_ids,
149 ["1791368000030", "1791368000020", "1791368000010"]
150 );
151 assert_eq!(window.older_cursor.as_deref(), Some("1791368000009"));
152 assert_eq!(window.newer_cursor.as_deref(), Some("1791368000031"));
153 }
154
155 #[test]
156 fn absent_links_mean_no_more_pages() {
157 let window = parse_message_window(&json!({
158 "messages": [{"id": "1", "messagetype": "Text"}],
159 "_metadata": {}
160 }))
161 .unwrap();
162 assert_eq!(window.older_cursor, None);
163 assert_eq!(window.newer_cursor, None);
164 let without_metadata = parse_message_window(&json!({"messages": []})).unwrap();
165 assert_eq!(without_metadata.older_cursor, None);
166 }
167
168 #[test]
169 fn link_without_a_number_gives_no_cursor() {
170 let window = parse_message_window(&json!({
171 "messages": [],
172 "_metadata": {"backwardLink": "https://h/messages/epochTimeStamp/?x=1"}
173 }))
174 .unwrap();
175 assert_eq!(window.older_cursor, None);
176 }
177
178 #[test]
179 fn missing_messages_is_unexpected() {
180 assert!(matches!(
181 parse_message_window(&json!({})),
182 Err(Error::UnexpectedAnswer(_))
183 ));
184 }
185
186 #[tokio::test]
187 async fn requests_the_window_around_the_anchor() {
188 let messages = Messages::with_transport(
189 Canned {
190 body: fixture(),
191 requests: Mutex::new(Vec::new()),
192 },
193 "emea",
194 );
195 messages
196 .message_window(
197 "19:abc@thread.v2",
198 "1791368000020",
199 WindowDirection::Bidirectional,
200 20,
201 )
202 .await
203 .unwrap();
204 let requests = messages.transport.requests.lock().unwrap();
205 assert_eq!(requests[0].method, Method::Get);
206 assert_eq!(
207 requests[0].url,
208 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations/19%3Aabc%40thread.v2/messages/epochTimeStamp/1791368000020?pageSize=20&direction=BIDIRECTIONAL&includeMetadata=true&locationType=Primary"
209 );
210 }
211}
crates/core/src/lib.rs +3 −1
@@ -32,6 +32,7 @@ mod mentions;
32 32 mod message_actions;
33 33 mod meeting_join;
34 34 mod message_link;
35 mod message_window;
35 36 mod people;
36 37 mod presence;
37 38 mod preview;
@@ -79,7 +80,7 @@ pub use card_widgets::{
79 80 pub use card_width::{TargetWidth, WidthClass};
80 81 pub use chatsvc::{
81 82 CallDirection, CallLogEntry, CallOutcome, ChatApp, ForcedAvailability, ForcedKind, ForwardResult, Gif, PinnedMessage, PresenceStatus,
82 SavedMessage, ScheduledDraft, StatusNote, WorkLocation, WorkLocationKind, WorkLocationSource,
83 SavedMessage, ScheduledDraft, StatusNote, WindowDirection, WorkLocation, WorkLocationKind, WorkLocationSource,
83 84 };
84 85 pub use chatsvc::{ChatSection, ChatSectionSettings};
85 86 pub use draft::{
@@ -102,6 +103,7 @@ pub use download::LibraryFile;
102 103 pub use images::StoredImage;
103 104 pub use links::{LinkPreview, first_public_link, is_public_link, link_preview, public_links};
104 105 pub use mapping::{chat_record, message_record};
106 pub use message_window::{JumpPlan, WINDOW_PAGE_SIZE, WindowPage, jump_plan, without_islands};
105 107 pub use markdown::{card_markdown_to_html, escape_html, markdown_to_html, plain_text_to_html};
106 108 pub use mentions::MentionInput;
107 109 pub use meeting_join::{
@@ -32,6 +32,7 @@ mod mentions;
32mod message_actions;
32mod message_actions;
33mod meeting_join;
33mod meeting_join;
34mod message_link;
34mod message_link;
35mod message_window;
35mod people;
36mod people;
36mod presence;
37mod presence;
37mod preview;
38mod preview;
@@ -79,7 +80,7 @@ pub use card_widgets::{
79pub use card_width::{TargetWidth, WidthClass};
80pub use card_width::{TargetWidth, WidthClass};
80pub use chatsvc::{
81pub use chatsvc::{
81 CallDirection, CallLogEntry, CallOutcome, ChatApp, ForcedAvailability, ForcedKind, ForwardResult, Gif, PinnedMessage, PresenceStatus,
82 CallDirection, CallLogEntry, CallOutcome, ChatApp, ForcedAvailability, ForcedKind, ForwardResult, Gif, PinnedMessage, PresenceStatus,
82 SavedMessage, ScheduledDraft, StatusNote, WorkLocation, WorkLocationKind, WorkLocationSource,
83 SavedMessage, ScheduledDraft, StatusNote, WindowDirection, WorkLocation, WorkLocationKind, WorkLocationSource,
83};
84};
84pub use chatsvc::{ChatSection, ChatSectionSettings};
85pub use chatsvc::{ChatSection, ChatSectionSettings};
85pub use draft::{
86pub use draft::{
@@ -102,6 +103,7 @@ pub use download::LibraryFile;
102pub use images::StoredImage;
103pub use images::StoredImage;
103pub use links::{LinkPreview, first_public_link, is_public_link, link_preview, public_links};
104pub use links::{LinkPreview, first_public_link, is_public_link, link_preview, public_links};
104pub use mapping::{chat_record, message_record};
105pub use mapping::{chat_record, message_record};
106pub use message_window::{JumpPlan, WINDOW_PAGE_SIZE, WindowPage, jump_plan, without_islands};
105pub use markdown::{card_markdown_to_html, escape_html, markdown_to_html, plain_text_to_html};
107pub use markdown::{card_markdown_to_html, escape_html, markdown_to_html, plain_text_to_html};
106pub use mentions::MentionInput;
108pub use mentions::MentionInput;
107pub use meeting_join::{
109pub use meeting_join::{
crates/core/src/message_window.rs added +170 −0
@@ -0,0 +1,170 @@
1 use chatsvc::{MessageWindow, WindowDirection};
2 use chrono::{DateTime, Utc};
3 use store::MessageRecord;
4
5 use crate::engine::{SyncEngine, sorted};
6 use crate::error::Result;
7 use crate::mapping::message_record;
8 use crate::remote::Remote;
9
10 pub const WINDOW_PAGE_SIZE: usize = 20;
11
12 #[derive(Debug, Clone, Default)]
13 pub struct WindowPage {
14 pub records: Vec<MessageRecord>,
15 pub older_cursor: Option<String>,
16 pub newer_cursor: Option<String>,
17 pub oldest: Option<DateTime<Utc>>,
18 pub newest: Option<DateTime<Utc>>,
19 }
20
21 impl<R: Remote> SyncEngine<R> {
22 pub async fn fetch_chat_message(
23 &self,
24 chat_id: &str,
25 message_id: &str,
26 ) -> Result<Option<MessageRecord>> {
27 let message = self.remote.chat_message(chat_id, message_id).await?;
28 Ok(message_record(chat_id, &message))
29 }
30
31 pub async fn load_window(&self, chat_id: &str, anchor_id: &str) -> Result<WindowPage> {
32 self.window_page(chat_id, anchor_id, WindowDirection::Bidirectional)
33 .await
34 }
35
36 pub async fn load_window_page(
37 &self,
38 chat_id: &str,
39 cursor: &str,
40 direction: WindowDirection,
41 ) -> Result<WindowPage> {
42 self.window_page(chat_id, cursor, direction).await
43 }
44
45 async fn window_page(
46 &self,
47 chat_id: &str,
48 position: &str,
49 direction: WindowDirection,
50 ) -> Result<WindowPage> {
51 let MessageWindow {
52 message_ids,
53 older_cursor,
54 newer_cursor,
55 } = self
56 .remote
57 .chat_message_window(chat_id, position, direction, WINDOW_PAGE_SIZE)
58 .await?;
59 let mut records = Vec::with_capacity(message_ids.len());
60 for answer in self
61 .remote
62 .chat_messages_by_id(chat_id, &message_ids)
63 .await?
64 {
65 if let Some(record) = answer
66 .ok()
67 .and_then(|message| message_record(chat_id, &message))
68 {
69 records.push(record);
70 }
71 }
72 let records = sorted(records);
73 self.ingest(chat_id, records.clone())?;
74 self.announce(chat_id, !records.is_empty());
75 Ok(WindowPage {
76 oldest: records.first().map(|record| record.created_at),
77 newest: records.last().map(|record| record.created_at),
78 records,
79 older_cursor,
80 newer_cursor,
81 })
82 }
83 }
84
85 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
86 pub enum JumpPlan {
87 InPlace,
88 LeaveWindow,
89 LoadWindow,
90 }
91
92 pub fn jump_plan(
93 window: Option<(DateTime<Utc>, DateTime<Utc>)>,
94 target_created_at: Option<DateTime<Utc>>,
95 oldest_loaded: Option<DateTime<Utc>>,
96 ) -> JumpPlan {
97 let Some(created_at) = target_created_at else {
98 return JumpPlan::LoadWindow;
99 };
100 if window.is_some_and(|(oldest, newest)| oldest <= created_at && created_at <= newest) {
101 JumpPlan::InPlace
102 } else if oldest_loaded.is_none_or(|oldest_loaded| created_at >= oldest_loaded) {
103 JumpPlan::LeaveWindow
104 } else {
105 JumpPlan::LoadWindow
106 }
107 }
108
109 pub fn without_islands(
110 mut records: Vec<MessageRecord>,
111 oldest_loaded: Option<DateTime<Utc>>,
112 ) -> Vec<MessageRecord> {
113 if let Some(oldest_loaded) = oldest_loaded {
114 records.retain(|record| record.created_at >= oldest_loaded);
115 }
116 records
117 }
118
119 #[cfg(test)]
120 mod tests {
121 use chrono::TimeZone;
122
123 use super::*;
124
125 fn at(minute: u32) -> DateTime<Utc> {
126 Utc.with_ymd_and_hms(2026, 10, 6, 9, minute, 0).unwrap()
127 }
128
129 fn record(minute: u32) -> MessageRecord {
130 MessageRecord {
131 message_id: minute.to_string(),
132 created_at: at(minute),
133 ..MessageRecord::default()
134 }
135 }
136
137 #[test]
138 fn jump_plan_and_island_filter() {
139 assert_eq!(jump_plan(None, None, Some(at(5))), JumpPlan::LoadWindow);
140 assert_eq!(
141 jump_plan(None, Some(at(4)), Some(at(5))),
142 JumpPlan::LoadWindow
143 );
144 assert_eq!(
145 jump_plan(None, Some(at(5)), Some(at(5))),
146 JumpPlan::LeaveWindow
147 );
148 assert_eq!(jump_plan(None, Some(at(1)), None), JumpPlan::LeaveWindow);
149 let window = Some((at(10), at(20)));
150 assert_eq!(
151 jump_plan(window, Some(at(15)), Some(at(30))),
152 JumpPlan::InPlace
153 );
154 assert_eq!(
155 jump_plan(window, Some(at(25)), Some(at(5))),
156 JumpPlan::LeaveWindow
157 );
158 assert_eq!(
159 jump_plan(window, Some(at(9)), Some(at(30))),
160 JumpPlan::LoadWindow
161 );
162 let kept = without_islands(vec![record(1), record(5), record(6)], Some(at(5)));
163 let ids: Vec<&str> = kept
164 .iter()
165 .map(|record| record.message_id.as_str())
166 .collect();
167 assert_eq!(ids, ["5", "6"]);
168 assert_eq!(without_islands(vec![record(1)], None).len(), 1);
169 }
170 }
@@ -0,0 +1,170 @@
1use chatsvc::{MessageWindow, WindowDirection};
2use chrono::{DateTime, Utc};
3use store::MessageRecord;
4
5use crate::engine::{SyncEngine, sorted};
6use crate::error::Result;
7use crate::mapping::message_record;
8use crate::remote::Remote;
9
10pub const WINDOW_PAGE_SIZE: usize = 20;
11
12#[derive(Debug, Clone, Default)]
13pub struct WindowPage {
14 pub records: Vec<MessageRecord>,
15 pub older_cursor: Option<String>,
16 pub newer_cursor: Option<String>,
17 pub oldest: Option<DateTime<Utc>>,
18 pub newest: Option<DateTime<Utc>>,
19}
20
21impl<R: Remote> SyncEngine<R> {
22 pub async fn fetch_chat_message(
23 &self,
24 chat_id: &str,
25 message_id: &str,
26 ) -> Result<Option<MessageRecord>> {
27 let message = self.remote.chat_message(chat_id, message_id).await?;
28 Ok(message_record(chat_id, &message))
29 }
30
31 pub async fn load_window(&self, chat_id: &str, anchor_id: &str) -> Result<WindowPage> {
32 self.window_page(chat_id, anchor_id, WindowDirection::Bidirectional)
33 .await
34 }
35
36 pub async fn load_window_page(
37 &self,
38 chat_id: &str,
39 cursor: &str,
40 direction: WindowDirection,
41 ) -> Result<WindowPage> {
42 self.window_page(chat_id, cursor, direction).await
43 }
44
45 async fn window_page(
46 &self,
47 chat_id: &str,
48 position: &str,
49 direction: WindowDirection,
50 ) -> Result<WindowPage> {
51 let MessageWindow {
52 message_ids,
53 older_cursor,
54 newer_cursor,
55 } = self
56 .remote
57 .chat_message_window(chat_id, position, direction, WINDOW_PAGE_SIZE)
58 .await?;
59 let mut records = Vec::with_capacity(message_ids.len());
60 for answer in self
61 .remote
62 .chat_messages_by_id(chat_id, &message_ids)
63 .await?
64 {
65 if let Some(record) = answer
66 .ok()
67 .and_then(|message| message_record(chat_id, &message))
68 {
69 records.push(record);
70 }
71 }
72 let records = sorted(records);
73 self.ingest(chat_id, records.clone())?;
74 self.announce(chat_id, !records.is_empty());
75 Ok(WindowPage {
76 oldest: records.first().map(|record| record.created_at),
77 newest: records.last().map(|record| record.created_at),
78 records,
79 older_cursor,
80 newer_cursor,
81 })
82 }
83}
84
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86pub enum JumpPlan {
87 InPlace,
88 LeaveWindow,
89 LoadWindow,
90}
91
92pub fn jump_plan(
93 window: Option<(DateTime<Utc>, DateTime<Utc>)>,
94 target_created_at: Option<DateTime<Utc>>,
95 oldest_loaded: Option<DateTime<Utc>>,
96) -> JumpPlan {
97 let Some(created_at) = target_created_at else {
98 return JumpPlan::LoadWindow;
99 };
100 if window.is_some_and(|(oldest, newest)| oldest <= created_at && created_at <= newest) {
101 JumpPlan::InPlace
102 } else if oldest_loaded.is_none_or(|oldest_loaded| created_at >= oldest_loaded) {
103 JumpPlan::LeaveWindow
104 } else {
105 JumpPlan::LoadWindow
106 }
107}
108
109pub fn without_islands(
110 mut records: Vec<MessageRecord>,
111 oldest_loaded: Option<DateTime<Utc>>,
112) -> Vec<MessageRecord> {
113 if let Some(oldest_loaded) = oldest_loaded {
114 records.retain(|record| record.created_at >= oldest_loaded);
115 }
116 records
117}
118
119#[cfg(test)]
120mod tests {
121 use chrono::TimeZone;
122
123 use super::*;
124
125 fn at(minute: u32) -> DateTime<Utc> {
126 Utc.with_ymd_and_hms(2026, 10, 6, 9, minute, 0).unwrap()
127 }
128
129 fn record(minute: u32) -> MessageRecord {
130 MessageRecord {
131 message_id: minute.to_string(),
132 created_at: at(minute),
133 ..MessageRecord::default()
134 }
135 }
136
137 #[test]
138 fn jump_plan_and_island_filter() {
139 assert_eq!(jump_plan(None, None, Some(at(5))), JumpPlan::LoadWindow);
140 assert_eq!(
141 jump_plan(None, Some(at(4)), Some(at(5))),
142 JumpPlan::LoadWindow
143 );
144 assert_eq!(
145 jump_plan(None, Some(at(5)), Some(at(5))),
146 JumpPlan::LeaveWindow
147 );
148 assert_eq!(jump_plan(None, Some(at(1)), None), JumpPlan::LeaveWindow);
149 let window = Some((at(10), at(20)));
150 assert_eq!(
151 jump_plan(window, Some(at(15)), Some(at(30))),
152 JumpPlan::InPlace
153 );
154 assert_eq!(
155 jump_plan(window, Some(at(25)), Some(at(5))),
156 JumpPlan::LeaveWindow
157 );
158 assert_eq!(
159 jump_plan(window, Some(at(9)), Some(at(30))),
160 JumpPlan::LoadWindow
161 );
162 let kept = without_islands(vec![record(1), record(5), record(6)], Some(at(5)));
163 let ids: Vec<&str> = kept
164 .iter()
165 .map(|record| record.message_id.as_str())
166 .collect();
167 assert_eq!(ids, ["5", "6"]);
168 assert_eq!(without_islands(vec![record(1)], None).len(), 1);
169 }
170}
crates/core/src/remote.rs +44 −2
@@ -2,9 +2,9 @@ use chatsvc::{
2 2 CallLogEntry, CardActions, ChatApp, ConversationRef, ConversationState, Conversations,
3 3 ForcedAvailability, ForwardResult, Gif, Gifs, InvokeRequest, InvokeResponse, Language,
4 4 LanguageSettings, LanguageSettingsClient, LinkInfo, MemberHorizon, MessageLanguage,
5 MessageLinks, Messages, PinnedMessage, Pins, PresenceService, PresenceStatus, Receipts,
5 MessageLinks, MessageWindow, Messages, PinnedMessage, Pins, PresenceService, PresenceStatus, Receipts,
6 6 SavedMessage, ScheduledDraft, ScheduledDrafts, StatusNote, TranslateRequest, Translation,
7 TranslationTrigger, Translator, WorkLocationKind,
7 TranslationTrigger, Translator, WindowDirection, WorkLocationKind,
8 8 };
9 9 use chrono::{DateTime, Utc};
10 10 use graph::{
@@ -300,6 +300,24 @@ pub trait Remote {
300 300 Err(Error::Unsupported("call history"))
301 301 }
302 302
303 async fn chat_message_window(
304 &self,
305 _chat_id: &str,
306 _anchor_id: &str,
307 _direction: WindowDirection,
308 _page_size: usize,
309 ) -> Result<MessageWindow> {
310 Err(Error::Unsupported("message windows"))
311 }
312
313 async fn chat_messages_by_id(
314 &self,
315 _chat_id: &str,
316 _message_ids: &[String],
317 ) -> Result<Vec<Result<Message>>> {
318 Err(Error::Unsupported("batched message reads"))
319 }
320
303 321 async fn chat_pins(&self, _chat_id: &str) -> Result<Vec<PinnedMessage>> {
304 322 Err(Error::Unsupported("pinned messages"))
305 323 }
@@ -871,6 +889,30 @@ impl Remote for Graph {
871 889 Ok(Messages::new(self.session()).list_call_logs().await?)
872 890 }
873 891
892 async fn chat_message_window(
893 &self,
894 chat_id: &str,
895 anchor_id: &str,
896 direction: WindowDirection,
897 page_size: usize,
898 ) -> Result<MessageWindow> {
899 Ok(Messages::new(self.session())
900 .message_window(chat_id, anchor_id, direction, page_size)
901 .await?)
902 }
903
904 async fn chat_messages_by_id(
905 &self,
906 chat_id: &str,
907 message_ids: &[String],
908 ) -> Result<Vec<Result<Message>>> {
909 let messages = Graph::chat_messages_by_id(self, chat_id, message_ids).await?;
910 Ok(messages
911 .into_iter()
912 .map(|message| message.map_err(Into::into))
913 .collect())
914 }
915
874 916 async fn chat_pins(&self, chat_id: &str) -> Result<Vec<PinnedMessage>> {
875 917 Ok(Pins::new(self.session()).chat_pins(chat_id).await?)
876 918 }
@@ -2,9 +2,9 @@ use chatsvc::{
2 CallLogEntry, CardActions, ChatApp, ConversationRef, ConversationState, Conversations,
2 CallLogEntry, CardActions, ChatApp, ConversationRef, ConversationState, Conversations,
3 ForcedAvailability, ForwardResult, Gif, Gifs, InvokeRequest, InvokeResponse, Language,
3 ForcedAvailability, ForwardResult, Gif, Gifs, InvokeRequest, InvokeResponse, Language,
4 LanguageSettings, LanguageSettingsClient, LinkInfo, MemberHorizon, MessageLanguage,
4 LanguageSettings, LanguageSettingsClient, LinkInfo, MemberHorizon, MessageLanguage,
5 MessageLinks, Messages, PinnedMessage, Pins, PresenceService, PresenceStatus, Receipts,
5 MessageLinks, MessageWindow, Messages, PinnedMessage, Pins, PresenceService, PresenceStatus, Receipts,
6 SavedMessage, ScheduledDraft, ScheduledDrafts, StatusNote, TranslateRequest, Translation,
6 SavedMessage, ScheduledDraft, ScheduledDrafts, StatusNote, TranslateRequest, Translation,
7 TranslationTrigger, Translator, WorkLocationKind,
7 TranslationTrigger, Translator, WindowDirection, WorkLocationKind,
8};
8};
9use chrono::{DateTime, Utc};
9use chrono::{DateTime, Utc};
10use graph::{
10use graph::{
@@ -300,6 +300,24 @@ pub trait Remote {
300 Err(Error::Unsupported("call history"))
300 Err(Error::Unsupported("call history"))
301 }
301 }
302
302
303 async fn chat_message_window(
304 &self,
305 _chat_id: &str,
306 _anchor_id: &str,
307 _direction: WindowDirection,
308 _page_size: usize,
309 ) -> Result<MessageWindow> {
310 Err(Error::Unsupported("message windows"))
311 }
312
313 async fn chat_messages_by_id(
314 &self,
315 _chat_id: &str,
316 _message_ids: &[String],
317 ) -> Result<Vec<Result<Message>>> {
318 Err(Error::Unsupported("batched message reads"))
319 }
320
303 async fn chat_pins(&self, _chat_id: &str) -> Result<Vec<PinnedMessage>> {
321 async fn chat_pins(&self, _chat_id: &str) -> Result<Vec<PinnedMessage>> {
304 Err(Error::Unsupported("pinned messages"))
322 Err(Error::Unsupported("pinned messages"))
305 }
323 }
@@ -871,6 +889,30 @@ impl Remote for Graph {
871 Ok(Messages::new(self.session()).list_call_logs().await?)
889 Ok(Messages::new(self.session()).list_call_logs().await?)
872 }
890 }
873
891
892 async fn chat_message_window(
893 &self,
894 chat_id: &str,
895 anchor_id: &str,
896 direction: WindowDirection,
897 page_size: usize,
898 ) -> Result<MessageWindow> {
899 Ok(Messages::new(self.session())
900 .message_window(chat_id, anchor_id, direction, page_size)
901 .await?)
902 }
903
904 async fn chat_messages_by_id(
905 &self,
906 chat_id: &str,
907 message_ids: &[String],
908 ) -> Result<Vec<Result<Message>>> {
909 let messages = Graph::chat_messages_by_id(self, chat_id, message_ids).await?;
910 Ok(messages
911 .into_iter()
912 .map(|message| message.map_err(Into::into))
913 .collect())
914 }
915
874 async fn chat_pins(&self, chat_id: &str) -> Result<Vec<PinnedMessage>> {
916 async fn chat_pins(&self, chat_id: &str) -> Result<Vec<PinnedMessage>> {
875 Ok(Pins::new(self.session()).chat_pins(chat_id).await?)
917 Ok(Pins::new(self.session()).chat_pins(chat_id).await?)
876 }
918 }
crates/core/tests/engine.rs +70 −0
@@ -124,6 +124,8 @@ struct Fake {
124 124 own_status_answer: Mutex<chatsvc::PresenceStatus>,
125 125 availability_puts: Mutex<Vec<Option<chatsvc::ForcedAvailability>>>,
126 126 note_puts: Mutex<Vec<Option<chatsvc::StatusNote>>>,
127 window_answer: Mutex<Option<chatsvc::MessageWindow>>,
128 window_requests: Mutex<Vec<(String, chatsvc::WindowDirection)>>,
127 129 }
128 130
129 131 impl Fake {
@@ -262,6 +264,36 @@ impl Remote for Handle {
262 264 )
263 265 }
264 266
267 async fn chat_message_window(
268 &self,
269 _chat_id: &str,
270 anchor_id: &str,
271 direction: chatsvc::WindowDirection,
272 _page_size: usize,
273 ) -> Result<chatsvc::MessageWindow> {
274 self.window_requests
275 .lock()
276 .unwrap()
277 .push((anchor_id.to_owned(), direction));
278 self.window_answer
279 .lock()
280 .unwrap()
281 .clone()
282 .ok_or(Error::Unsupported("no window"))
283 }
284
285 async fn chat_messages_by_id(
286 &self,
287 chat_id: &str,
288 message_ids: &[String],
289 ) -> Result<Vec<Result<Message>>> {
290 let mut messages = Vec::new();
291 for message_id in message_ids {
292 messages.push(self.chat_message(chat_id, message_id).await);
293 }
294 Ok(messages)
295 }
296
265 297 async fn chat_message(&self, _chat_id: &str, message_id: &str) -> Result<Message> {
266 298 self.record(format!("chat_message {message_id}"));
267 299 self.chat_messages
@@ -4333,3 +4365,41 @@ async fn translating_in_an_unknown_conversation_fails() {
4333 4365 .await;
4334 4366 assert!(matches!(outcome, Err(teams_core::Error::UnknownConversation(_))));
4335 4367 }
4368
4369 #[tokio::test]
4370 async fn load_window_ingests_found_messages_oldest_first_and_keeps_cursors() {
4371 let fake = Arc::new(Fake::default());
4372 let engine = chat_engine(&fake, small_pages()).await;
4373 fake.set_chat_messages(vec![message(3, 3, "<p>c</p>"), message(1, 1, "<p>a</p>")]);
4374 *fake.window_answer.lock().unwrap() = Some(chatsvc::MessageWindow {
4375 message_ids: vec!["m0003".into(), "m0002".into(), "m0001".into()],
4376 older_cursor: Some("100".into()),
4377 newer_cursor: None,
4378 });
4379
4380 let page = engine.load_window(CHAT, "m0003").await.unwrap();
4381
4382 let ids: Vec<&str> = page.records.iter().map(|record| record.message_id.as_str()).collect();
4383 assert_eq!(ids, ["m0001", "m0003"]);
4384 assert_eq!(page.oldest, Some(base() + Duration::minutes(1)));
4385 assert_eq!(page.newest, Some(base() + Duration::minutes(3)));
4386 assert_eq!(page.older_cursor.as_deref(), Some("100"));
4387 assert_eq!(page.newer_cursor, None);
4388 assert_eq!(engine.store().message_count(CHAT).unwrap(), 2);
4389 assert_eq!(
4390 *fake.window_requests.lock().unwrap(),
4391 [("m0003".to_owned(), chatsvc::WindowDirection::Bidirectional)]
4392 );
4393 }
4394
4395 #[tokio::test]
4396 async fn fetch_chat_message_does_not_store_the_message() {
4397 let fake = Arc::new(Fake::default());
4398 let engine = chat_engine(&fake, small_pages()).await;
4399 fake.set_chat_messages(vec![message(7, 7, "<p>pinned</p>")]);
4400
4401 let record = engine.fetch_chat_message(CHAT, "m0007").await.unwrap().unwrap();
4402
4403 assert_eq!(record.message_id, "m0007");
4404 assert_eq!(engine.store().message_count(CHAT).unwrap(), 0);
4405 }
@@ -124,6 +124,8 @@ struct Fake {
124 own_status_answer: Mutex<chatsvc::PresenceStatus>,
124 own_status_answer: Mutex<chatsvc::PresenceStatus>,
125 availability_puts: Mutex<Vec<Option<chatsvc::ForcedAvailability>>>,
125 availability_puts: Mutex<Vec<Option<chatsvc::ForcedAvailability>>>,
126 note_puts: Mutex<Vec<Option<chatsvc::StatusNote>>>,
126 note_puts: Mutex<Vec<Option<chatsvc::StatusNote>>>,
127 window_answer: Mutex<Option<chatsvc::MessageWindow>>,
128 window_requests: Mutex<Vec<(String, chatsvc::WindowDirection)>>,
127}
129}
128
130
129impl Fake {
131impl Fake {
@@ -262,6 +264,36 @@ impl Remote for Handle {
262 )
264 )
263 }
265 }
264
266
267 async fn chat_message_window(
268 &self,
269 _chat_id: &str,
270 anchor_id: &str,
271 direction: chatsvc::WindowDirection,
272 _page_size: usize,
273 ) -> Result<chatsvc::MessageWindow> {
274 self.window_requests
275 .lock()
276 .unwrap()
277 .push((anchor_id.to_owned(), direction));
278 self.window_answer
279 .lock()
280 .unwrap()
281 .clone()
282 .ok_or(Error::Unsupported("no window"))
283 }
284
285 async fn chat_messages_by_id(
286 &self,
287 chat_id: &str,
288 message_ids: &[String],
289 ) -> Result<Vec<Result<Message>>> {
290 let mut messages = Vec::new();
291 for message_id in message_ids {
292 messages.push(self.chat_message(chat_id, message_id).await);
293 }
294 Ok(messages)
295 }
296
265 async fn chat_message(&self, _chat_id: &str, message_id: &str) -> Result<Message> {
297 async fn chat_message(&self, _chat_id: &str, message_id: &str) -> Result<Message> {
266 self.record(format!("chat_message {message_id}"));
298 self.record(format!("chat_message {message_id}"));
267 self.chat_messages
299 self.chat_messages
@@ -4333,3 +4365,41 @@ async fn translating_in_an_unknown_conversation_fails() {
4333 .await;
4365 .await;
4334 assert!(matches!(outcome, Err(teams_core::Error::UnknownConversation(_))));
4366 assert!(matches!(outcome, Err(teams_core::Error::UnknownConversation(_))));
4335}
4367}
4368
4369#[tokio::test]
4370async fn load_window_ingests_found_messages_oldest_first_and_keeps_cursors() {
4371 let fake = Arc::new(Fake::default());
4372 let engine = chat_engine(&fake, small_pages()).await;
4373 fake.set_chat_messages(vec![message(3, 3, "<p>c</p>"), message(1, 1, "<p>a</p>")]);
4374 *fake.window_answer.lock().unwrap() = Some(chatsvc::MessageWindow {
4375 message_ids: vec!["m0003".into(), "m0002".into(), "m0001".into()],
4376 older_cursor: Some("100".into()),
4377 newer_cursor: None,
4378 });
4379
4380 let page = engine.load_window(CHAT, "m0003").await.unwrap();
4381
4382 let ids: Vec<&str> = page.records.iter().map(|record| record.message_id.as_str()).collect();
4383 assert_eq!(ids, ["m0001", "m0003"]);
4384 assert_eq!(page.oldest, Some(base() + Duration::minutes(1)));
4385 assert_eq!(page.newest, Some(base() + Duration::minutes(3)));
4386 assert_eq!(page.older_cursor.as_deref(), Some("100"));
4387 assert_eq!(page.newer_cursor, None);
4388 assert_eq!(engine.store().message_count(CHAT).unwrap(), 2);
4389 assert_eq!(
4390 *fake.window_requests.lock().unwrap(),
4391 [("m0003".to_owned(), chatsvc::WindowDirection::Bidirectional)]
4392 );
4393}
4394
4395#[tokio::test]
4396async fn fetch_chat_message_does_not_store_the_message() {
4397 let fake = Arc::new(Fake::default());
4398 let engine = chat_engine(&fake, small_pages()).await;
4399 fake.set_chat_messages(vec![message(7, 7, "<p>pinned</p>")]);
4400
4401 let record = engine.fetch_chat_message(CHAT, "m0007").await.unwrap().unwrap();
4402
4403 assert_eq!(record.message_id, "m0007");
4404 assert_eq!(engine.store().message_count(CHAT).unwrap(), 0);
4405}
crates/graph/src/client.rs +24 −0
@@ -62,6 +62,30 @@ impl Graph {
62 62 Ok(serde_json::from_value(body)?)
63 63 }
64 64
65 pub async fn chat_messages_by_id(
66 &self,
67 chat_id: &str,
68 message_ids: &[String],
69 ) -> Result<Vec<Result<Message>>> {
70 let scope = Scope::graph("Chat.Read");
71 let mut messages = Vec::with_capacity(message_ids.len());
72 for chunk in message_ids.chunks(BATCH_SIZE) {
73 let requests: Vec<Request> = chunk
74 .iter()
75 .map(|message_id| Request::get(urls::chat_message(chat_id, message_id)))
76 .collect();
77 let answers = self.session.batch(&requests, &scope).await?;
78 for (request, answer) in requests.iter().zip(answers) {
79 messages.push(if answer.is_success() {
80 serde_json::from_value(answer.body).map_err(Into::into)
81 } else {
82 Err(session::Error::api(answer.status, &request.url, answer.body).into())
83 });
84 }
85 }
86 Ok(messages)
87 }
88
65 89 pub async fn list_chats(&self, limit: usize) -> Result<Vec<Chat>> {
66 90 let mut page = self.chats_page(limit.clamp(1, CHAT_PAGE_SIZE)).await?;
67 91 let mut chats = std::mem::take(&mut page.items);
@@ -62,6 +62,30 @@ impl Graph {
62 Ok(serde_json::from_value(body)?)
62 Ok(serde_json::from_value(body)?)
63 }
63 }
64
64
65 pub async fn chat_messages_by_id(
66 &self,
67 chat_id: &str,
68 message_ids: &[String],
69 ) -> Result<Vec<Result<Message>>> {
70 let scope = Scope::graph("Chat.Read");
71 let mut messages = Vec::with_capacity(message_ids.len());
72 for chunk in message_ids.chunks(BATCH_SIZE) {
73 let requests: Vec<Request> = chunk
74 .iter()
75 .map(|message_id| Request::get(urls::chat_message(chat_id, message_id)))
76 .collect();
77 let answers = self.session.batch(&requests, &scope).await?;
78 for (request, answer) in requests.iter().zip(answers) {
79 messages.push(if answer.is_success() {
80 serde_json::from_value(answer.body).map_err(Into::into)
81 } else {
82 Err(session::Error::api(answer.status, &request.url, answer.body).into())
83 });
84 }
85 }
86 Ok(messages)
87 }
88
65 pub async fn list_chats(&self, limit: usize) -> Result<Vec<Chat>> {
89 pub async fn list_chats(&self, limit: usize) -> Result<Vec<Chat>> {
66 let mut page = self.chats_page(limit.clamp(1, CHAT_PAGE_SIZE)).await?;
90 let mut page = self.chats_page(limit.clamp(1, CHAT_PAGE_SIZE)).await?;
67 let mut chats = std::mem::take(&mut page.items);
91 let mut chats = std::mem::take(&mut page.items);
crates/store/src/messages.rs +21 −0
@@ -137,6 +137,27 @@ impl Store {
137 137 Ok(messages)
138 138 }
139 139
140 pub fn messages_between(
141 &self,
142 conversation_id: &str,
143 from: DateTime<Utc>,
144 to: DateTime<Utc>,
145 ) -> Result<Vec<MessageRecord>> {
146 let connection = self.lock()?;
147 let mut statement = connection.prepare_cached(&format!(
148 "SELECT {MESSAGE_COLUMNS} FROM messages
149 WHERE conversation_id = ?1 AND created_at >= ?2 AND created_at <= ?3
150 ORDER BY created_at ASC, message_id ASC"
151 ))?;
152 let messages = statement
153 .query_map(
154 params![conversation_id, to_millis(from), to_millis(to)],
155 message_from_row,
156 )?
157 .collect::<rusqlite::Result<Vec<_>>>()?;
158 Ok(messages)
159 }
160
140 161 /// Oldest-first page of the `limit` oldest messages strictly newer than `after`.
141 162 pub fn messages_after(
142 163 &self,
@@ -137,6 +137,27 @@ impl Store {
137 Ok(messages)
137 Ok(messages)
138 }
138 }
139
139
140 pub fn messages_between(
141 &self,
142 conversation_id: &str,
143 from: DateTime<Utc>,
144 to: DateTime<Utc>,
145 ) -> Result<Vec<MessageRecord>> {
146 let connection = self.lock()?;
147 let mut statement = connection.prepare_cached(&format!(
148 "SELECT {MESSAGE_COLUMNS} FROM messages
149 WHERE conversation_id = ?1 AND created_at >= ?2 AND created_at <= ?3
150 ORDER BY created_at ASC, message_id ASC"
151 ))?;
152 let messages = statement
153 .query_map(
154 params![conversation_id, to_millis(from), to_millis(to)],
155 message_from_row,
156 )?
157 .collect::<rusqlite::Result<Vec<_>>>()?;
158 Ok(messages)
159 }
160
140 /// Oldest-first page of the `limit` oldest messages strictly newer than `after`.
161 /// Oldest-first page of the `limit` oldest messages strictly newer than `after`.
141 pub fn messages_after(
162 pub fn messages_after(
142 &self,
163 &self,
crates/store/tests/store.rs +21 −0
@@ -717,6 +717,27 @@ fn counts_messages_after_a_time_from_others() {
717 717 assert_eq!(store.count_messages_after("c", None, "me").unwrap(), 2);
718 718 }
719 719
720 #[test]
721 fn messages_between_is_inclusive_and_oldest_first() {
722 let store = Store::open_in_memory().unwrap();
723 store
724 .upsert_messages(&[
725 message("c", "m4", 4),
726 message("c", "m1", 1),
727 message("c", "m3", 3),
728 message("c", "m2", 2),
729 message("other", "o3", 3),
730 ])
731 .unwrap();
732 let ids: Vec<String> = store
733 .messages_between("c", at(2), at(3))
734 .unwrap()
735 .into_iter()
736 .map(|record| record.message_id)
737 .collect();
738 assert_eq!(ids, ["m2", "m3"]);
739 }
740
720 741 fn html_message(
721 742 conversation_id: &str,
722 743 message_id: &str,
@@ -717,6 +717,27 @@ fn counts_messages_after_a_time_from_others() {
717 assert_eq!(store.count_messages_after("c", None, "me").unwrap(), 2);
717 assert_eq!(store.count_messages_after("c", None, "me").unwrap(), 2);
718}
718}
719
719
720#[test]
721fn messages_between_is_inclusive_and_oldest_first() {
722 let store = Store::open_in_memory().unwrap();
723 store
724 .upsert_messages(&[
725 message("c", "m4", 4),
726 message("c", "m1", 1),
727 message("c", "m3", 3),
728 message("c", "m2", 2),
729 message("other", "o3", 3),
730 ])
731 .unwrap();
732 let ids: Vec<String> = store
733 .messages_between("c", at(2), at(3))
734 .unwrap()
735 .into_iter()
736 .map(|record| record.message_id)
737 .collect();
738 assert_eq!(ids, ["m2", "m3"]);
739}
740
720fn html_message(
741fn html_message(
721 conversation_id: &str,
742 conversation_id: &str,
722 message_id: &str,
743 message_id: &str,
vendor/gpui-component/src/message_scroller.rs +27 −4
@@ -1,4 +1,4 @@
1 use std::{ops::Range, time::Duration};
1 use std::{ops::Range, rc::Rc, time::Duration};
2 2
3 3 use gpui::{
4 4 AnyElement, App, Axis, Context, ElementId, Entity, FollowMode, Hsla, InteractiveElement as _,
@@ -149,6 +149,11 @@ impl MessageScrollerState {
149 149 true
150 150 }
151 151
152 /// Stop following the tail until the next reset or `scroll_to_end`.
153 pub fn stop_following(&mut self) {
154 self.list_state.set_follow_mode(FollowMode::Normal);
155 }
156
152 157 /// Resume tail following and scroll to the latest row.
153 158 pub fn scroll_to_end(&mut self, cx: &mut Context<Self>) {
154 159 self.list_state.set_follow_mode(FollowMode::Tail);
@@ -177,6 +182,8 @@ pub struct MessageScroller {
177 182 bottom_fade: Option<Hsla>,
178 183 scrollbar: bool,
179 184 jump_button: bool,
185 force_jump_button: bool,
186 on_jump: Option<Rc<dyn Fn(&mut Window, &mut App)>>,
180 187 jump_button_label: SharedString,
181 188 }
182 189
@@ -207,6 +214,8 @@ impl MessageScroller {
207 214 bottom_fade: None,
208 215 scrollbar: true,
209 216 jump_button: true,
217 force_jump_button: false,
218 on_jump: None,
210 219 jump_button_label: "Jump to latest".into(),
211 220 }
212 221 }
@@ -223,6 +232,18 @@ impl MessageScroller {
223 232 self
224 233 }
225 234
235 /// Show the jump button even when the list is at its end.
236 pub fn force_jump_button(mut self, force: bool) -> Self {
237 self.force_jump_button = force;
238 self
239 }
240
241 /// Run `callback` on jump-button click instead of scrolling to the end.
242 pub fn on_jump(mut self, callback: impl Fn(&mut Window, &mut App) + 'static) -> Self {
243 self.on_jump = Some(Rc::new(callback));
244 self
245 }
246
226 247 /// Set the label used by the built-in jump-to-latest button.
227 248 pub fn with_jump_button_label(mut self, label: impl Into<SharedString>) -> Self {
228 249 self.jump_button_label = label.into();
@@ -300,7 +321,7 @@ impl RenderOnce for MessageScroller {
300 321 let state = self.state.read(cx);
301 322 (state.list_state.clone(), state.is_scrolled_up())
302 323 };
303 let show_jump_button = self.jump_button && scrolled_up;
324 let show_jump_button = self.jump_button && (scrolled_up || self.force_jump_button);
304 325 let jump_button_visibility = if self.jump_button {
305 326 transition(
306 327 (root_id.clone(), "jump-button-visibility"),
@@ -408,6 +429,7 @@ impl RenderOnce for MessageScroller {
408 429 .child(ScrollableMask::new(Axis::Vertical, &list_state).id(root_id.clone()))
409 430 .when(self.jump_button && jump_button_visibility > 0., |this| {
410 431 let state = self.state.clone();
432 let on_jump = self.on_jump.clone();
411 433
412 434 this.child(
413 435 div()
@@ -433,8 +455,9 @@ impl RenderOnce for MessageScroller {
433 455 .bg(tokens.colors.background)
434 456 .text_color(tokens.colors.foreground)
435 457 .refine_style(&jump_button_style)
436 .on_click(move |_, _, cx| {
437 state.update(cx, |state, cx| state.scroll_to_end(cx));
458 .on_click(move |_, window, cx| match &on_jump {
459 Some(on_jump) => on_jump(window, cx),
460 None => state.update(cx, |state, cx| state.scroll_to_end(cx)),
438 461 })
439 462 .when_some(jump_button_renderer, |button, renderer| {
440 463 renderer(button)
@@ -1,4 +1,4 @@
1use std::{ops::Range, time::Duration};
1use std::{ops::Range, rc::Rc, time::Duration};
2
2
3use gpui::{
3use gpui::{
4 AnyElement, App, Axis, Context, ElementId, Entity, FollowMode, Hsla, InteractiveElement as _,
4 AnyElement, App, Axis, Context, ElementId, Entity, FollowMode, Hsla, InteractiveElement as _,
@@ -149,6 +149,11 @@ impl MessageScrollerState {
149 true
149 true
150 }
150 }
151
151
152 /// Stop following the tail until the next reset or `scroll_to_end`.
153 pub fn stop_following(&mut self) {
154 self.list_state.set_follow_mode(FollowMode::Normal);
155 }
156
152 /// Resume tail following and scroll to the latest row.
157 /// Resume tail following and scroll to the latest row.
153 pub fn scroll_to_end(&mut self, cx: &mut Context<Self>) {
158 pub fn scroll_to_end(&mut self, cx: &mut Context<Self>) {
154 self.list_state.set_follow_mode(FollowMode::Tail);
159 self.list_state.set_follow_mode(FollowMode::Tail);
@@ -177,6 +182,8 @@ pub struct MessageScroller {
177 bottom_fade: Option<Hsla>,
182 bottom_fade: Option<Hsla>,
178 scrollbar: bool,
183 scrollbar: bool,
179 jump_button: bool,
184 jump_button: bool,
185 force_jump_button: bool,
186 on_jump: Option<Rc<dyn Fn(&mut Window, &mut App)>>,
180 jump_button_label: SharedString,
187 jump_button_label: SharedString,
181}
188}
182
189
@@ -207,6 +214,8 @@ impl MessageScroller {
207 bottom_fade: None,
214 bottom_fade: None,
208 scrollbar: true,
215 scrollbar: true,
209 jump_button: true,
216 jump_button: true,
217 force_jump_button: false,
218 on_jump: None,
210 jump_button_label: "Jump to latest".into(),
219 jump_button_label: "Jump to latest".into(),
211 }
220 }
212 }
221 }
@@ -223,6 +232,18 @@ impl MessageScroller {
223 self
232 self
224 }
233 }
225
234
235 /// Show the jump button even when the list is at its end.
236 pub fn force_jump_button(mut self, force: bool) -> Self {
237 self.force_jump_button = force;
238 self
239 }
240
241 /// Run `callback` on jump-button click instead of scrolling to the end.
242 pub fn on_jump(mut self, callback: impl Fn(&mut Window, &mut App) + 'static) -> Self {
243 self.on_jump = Some(Rc::new(callback));
244 self
245 }
246
226 /// Set the label used by the built-in jump-to-latest button.
247 /// Set the label used by the built-in jump-to-latest button.
227 pub fn with_jump_button_label(mut self, label: impl Into<SharedString>) -> Self {
248 pub fn with_jump_button_label(mut self, label: impl Into<SharedString>) -> Self {
228 self.jump_button_label = label.into();
249 self.jump_button_label = label.into();
@@ -300,7 +321,7 @@ impl RenderOnce for MessageScroller {
300 let state = self.state.read(cx);
321 let state = self.state.read(cx);
301 (state.list_state.clone(), state.is_scrolled_up())
322 (state.list_state.clone(), state.is_scrolled_up())
302 };
323 };
303 let show_jump_button = self.jump_button && scrolled_up;
324 let show_jump_button = self.jump_button && (scrolled_up || self.force_jump_button);
304 let jump_button_visibility = if self.jump_button {
325 let jump_button_visibility = if self.jump_button {
305 transition(
326 transition(
306 (root_id.clone(), "jump-button-visibility"),
327 (root_id.clone(), "jump-button-visibility"),
@@ -408,6 +429,7 @@ impl RenderOnce for MessageScroller {
408 .child(ScrollableMask::new(Axis::Vertical, &list_state).id(root_id.clone()))
429 .child(ScrollableMask::new(Axis::Vertical, &list_state).id(root_id.clone()))
409 .when(self.jump_button && jump_button_visibility > 0., |this| {
430 .when(self.jump_button && jump_button_visibility > 0., |this| {
410 let state = self.state.clone();
431 let state = self.state.clone();
432 let on_jump = self.on_jump.clone();
411
433
412 this.child(
434 this.child(
413 div()
435 div()
@@ -433,8 +455,9 @@ impl RenderOnce for MessageScroller {
433 .bg(tokens.colors.background)
455 .bg(tokens.colors.background)
434 .text_color(tokens.colors.foreground)
456 .text_color(tokens.colors.foreground)
435 .refine_style(&jump_button_style)
457 .refine_style(&jump_button_style)
436 .on_click(move |_, _, cx| {
458 .on_click(move |_, window, cx| match &on_jump {
437 state.update(cx, |state, cx| state.scroll_to_end(cx));
459 Some(on_jump) => on_jump(window, cx),
460 None => state.update(cx, |state, cx| state.scroll_to_end(cx)),
438 })
461 })
439 .when_some(jump_button_renderer, |button, renderer| {
462 .when_some(jump_button_renderer, |button, renderer| {
440 renderer(button)
463 renderer(button)