BlueGit

ict rusty-teams

feat(composer): schedule send, unsent messages and drafts survive a restart

- Right-click Send: schedule on the Teams server (chatsvc drafts stream), Teams delivers even when the app is closed
- Presets (later today, tomorrow or Monday morning) and a custom day + time, max 7 days
- Scheduled messages show as dashed bubbles: Edit, Send now, Delete
- Text and formatting only for now; mentions, images, files and replies disable it
- Outbox in SQLite: Sending and Failed rows survive chat switches and restarts, resend on start with a duplicate guard
- Per-chat composer drafts in SQLite, "Draft:" and "Not sent" in the sidebar
- docs/research/schedule-send.md: live-verified drafts API

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

metis Daniel Däschle · pushed by metis

Authored 2026-10-09 · 7 weeks ago

Hash
c4d09eb9ca5be71e4ff4dd10f773c7c1b644f9c8
Parent
abde01c3
52 files changed +4486 −226
Cargo.lock +1 −0
@@ -1096,6 +1096,7 @@ dependencies = [
1096 1096 "thiserror 2.0.21",
1097 1097 "tokio",
1098 1098 "tokio-tungstenite",
1099 "uuid",
1099 1100 ]
1100 1101
1101 1102 [[package]]
@@ -1096,6 +1096,7 @@ dependencies = [
1096 "thiserror 2.0.21",
1096 "thiserror 2.0.21",
1097 "tokio",
1097 "tokio",
1098 "tokio-tungstenite",
1098 "tokio-tungstenite",
1099 "uuid",
1099]
1100]
1100
1101
1101[[package]]
1102[[package]]
README.md +1 −0
@@ -15,6 +15,7 @@ It does chats and channels. Calls, meetings and channel tabs are planned (see [R
15 15 - Send, edit, delete, react, quote-reply, @mentions
16 16 - Rich text composer: format bar over a selection, `Ctrl+B` / `Ctrl+I` / `Ctrl+U`, lists, quotes, code; Markdown converts as you type or paste
17 17 - Composer picker for emoji, GIFs and stickers; GIFs and stickers also show in messages
18 - Schedule send: right-click the send button or `Ctrl+Shift+Enter`; Teams delivers the message, text and formatting only
18 19 - Emoji by `:` code with English codes and German aliases, `:thumbsup:` and `:)` convert as you type
19 20 - Link previews: card under messages, preview above the composer that goes out with the message
20 21 - Inline images, file cards, Adaptive Cards (layout, links, images, buttons: submit, execute, show card, toggle; input fields; task dialogs)
@@ -15,6 +15,7 @@ It does chats and channels. Calls, meetings and channel tabs are planned (see [R
15- Send, edit, delete, react, quote-reply, @mentions
15- Send, edit, delete, react, quote-reply, @mentions
16- Rich text composer: format bar over a selection, `Ctrl+B` / `Ctrl+I` / `Ctrl+U`, lists, quotes, code; Markdown converts as you type or paste
16- Rich text composer: format bar over a selection, `Ctrl+B` / `Ctrl+I` / `Ctrl+U`, lists, quotes, code; Markdown converts as you type or paste
17- Composer picker for emoji, GIFs and stickers; GIFs and stickers also show in messages
17- Composer picker for emoji, GIFs and stickers; GIFs and stickers also show in messages
18- Schedule send: right-click the send button or `Ctrl+Shift+Enter`; Teams delivers the message, text and formatting only
18- Emoji by `:` code with English codes and German aliases, `:thumbsup:` and `:)` convert as you type
19- Emoji by `:` code with English codes and German aliases, `:thumbsup:` and `:)` convert as you type
19- Link previews: card under messages, preview above the composer that goes out with the message
20- Link previews: card under messages, preview above the composer that goes out with the message
20- Inline images, file cards, Adaptive Cards (layout, links, images, buttons: submit, execute, show card, toggle; input fields; task dialogs)
21- Inline images, file cards, Adaptive Cards (layout, links, images, buttons: submit, execute, show card, toggle; input fields; task dialogs)
ROADMAP.md +4 −5
@@ -2,7 +2,7 @@
2 2
3 3 Feature parity with the Microsoft Teams desktop client.
4 4
5 **Parity: 70 %** (58 done, 3 partial, 24 missing of 85). Partial counts half.
5 **Parity: 72 %** (60 done, 3 partial, 22 missing of 85). Partial counts half.
6 6
7 7 ## By area
8 8
@@ -11,7 +11,7 @@ Feature parity with the Microsoft Teams desktop client.
11 11 | [Sign-in and app](#sign-in-and-app) | 92 % | 5 | 1 | 0 |
12 12 | [Chat list](#chat-list) | 90 % | 9 | 0 | 1 |
13 13 | [Reading](#reading) | 87 % | 16 | 1 | 2 |
14 | [Writing](#writing) | 86 % | 12 | 0 | 2 |
14 | [Writing](#writing) | 100 % | 14 | 0 | 0 |
15 15 | [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |
16 16 | [Channels](#channels) | 36 % | 2 | 1 | 4 |
17 17 | [Notifications](#notifications) | 88 % | 7 | 0 | 1 |
@@ -27,7 +27,6 @@ Feature parity with the Microsoft Teams desktop client.
27 27 | 1 | Channel: new post with subject, post cards | |
28 28 | 2 | Sign in on Linux without Chrome on a debug port | |
29 29 | 3 | Keyboard: Ctrl+1..9, Alt+Up/Down | |
30 | 4 | Unsent messages survive a restart | |
31 30
32 31 ## Sign-in and app
33 32
@@ -95,8 +94,8 @@ Feature parity with the Microsoft Teams desktop client.
95 94 | Formatting toolbar, Ctrl+B and Ctrl+I | Done | Bar over a selection; Ctrl+U, Ctrl+Shift+X/C, Ctrl+K link; lists, quote, code block; superscript, subscript (Ctrl+Shift+= / Ctrl+=) and Small/Large shown at real size while typing |
96 95 | Attach a file, paste or drag an image | Done | Images sit in the text at the cursor as a large preview and send at that spot; files via OneDrive or the channel's Files |
97 96 | GIFs and stickers | Done | Show and send; composer picker with Emoji, GIF and Sticker tabs; GIF search needs the org to allow it |
98 | Schedule send | Missing | |
99 | Unsent messages survive a restart | Missing | Pending sends live in memory only |
97 | Schedule send | Done | Server-side, Teams delivers. Text and formatting only for now |
98 | Unsent messages survive a restart | Done | Sends are saved before they go out and resent on start without duplicates; failed ones keep Retry and Delete. Drafts are kept per chat and show as "Draft:" in the list |
100 99
101 100 ## Message actions
102 101
@@ -2,7 +2,7 @@
2
2
3Feature parity with the Microsoft Teams desktop client.
3Feature parity with the Microsoft Teams desktop client.
4
4
5**Parity: 70 %** (58 done, 3 partial, 24 missing of 85). Partial counts half.
5**Parity: 72 %** (60 done, 3 partial, 22 missing of 85). Partial counts half.
6
6
7## By area
7## By area
8
8
@@ -11,7 +11,7 @@ Feature parity with the Microsoft Teams desktop client.
11| [Sign-in and app](#sign-in-and-app) | 92 % | 5 | 1 | 0 |
11| [Sign-in and app](#sign-in-and-app) | 92 % | 5 | 1 | 0 |
12| [Chat list](#chat-list) | 90 % | 9 | 0 | 1 |
12| [Chat list](#chat-list) | 90 % | 9 | 0 | 1 |
13| [Reading](#reading) | 87 % | 16 | 1 | 2 |
13| [Reading](#reading) | 87 % | 16 | 1 | 2 |
14| [Writing](#writing) | 86 % | 12 | 0 | 2 |
14| [Writing](#writing) | 100 % | 14 | 0 | 0 |
15| [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |
15| [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |
16| [Channels](#channels) | 36 % | 2 | 1 | 4 |
16| [Channels](#channels) | 36 % | 2 | 1 | 4 |
17| [Notifications](#notifications) | 88 % | 7 | 0 | 1 |
17| [Notifications](#notifications) | 88 % | 7 | 0 | 1 |
@@ -27,7 +27,6 @@ Feature parity with the Microsoft Teams desktop client.
27| 1 | Channel: new post with subject, post cards | |
27| 1 | Channel: new post with subject, post cards | |
28| 2 | Sign in on Linux without Chrome on a debug port | |
28| 2 | Sign in on Linux without Chrome on a debug port | |
29| 3 | Keyboard: Ctrl+1..9, Alt+Up/Down | |
29| 3 | Keyboard: Ctrl+1..9, Alt+Up/Down | |
30| 4 | Unsent messages survive a restart | |
31
30
32## Sign-in and app
31## Sign-in and app
33
32
@@ -95,8 +94,8 @@ Feature parity with the Microsoft Teams desktop client.
95| Formatting toolbar, Ctrl+B and Ctrl+I | Done | Bar over a selection; Ctrl+U, Ctrl+Shift+X/C, Ctrl+K link; lists, quote, code block; superscript, subscript (Ctrl+Shift+= / Ctrl+=) and Small/Large shown at real size while typing |
94| Formatting toolbar, Ctrl+B and Ctrl+I | Done | Bar over a selection; Ctrl+U, Ctrl+Shift+X/C, Ctrl+K link; lists, quote, code block; superscript, subscript (Ctrl+Shift+= / Ctrl+=) and Small/Large shown at real size while typing |
96| Attach a file, paste or drag an image | Done | Images sit in the text at the cursor as a large preview and send at that spot; files via OneDrive or the channel's Files |
95| Attach a file, paste or drag an image | Done | Images sit in the text at the cursor as a large preview and send at that spot; files via OneDrive or the channel's Files |
97| GIFs and stickers | Done | Show and send; composer picker with Emoji, GIF and Sticker tabs; GIF search needs the org to allow it |
96| GIFs and stickers | Done | Show and send; composer picker with Emoji, GIF and Sticker tabs; GIF search needs the org to allow it |
98| Schedule send | Missing | |
97| Schedule send | Done | Server-side, Teams delivers. Text and formatting only for now |
99| Unsent messages survive a restart | Missing | Pending sends live in memory only |
98| Unsent messages survive a restart | Done | Sends are saved before they go out and resent on start without duplicates; failed ones keep Retry and Delete. Drafts are kept per chat and show as "Draft:" in the list |
100
99
101## Message actions
100## Message actions
102
101
crates/app/Cargo.toml +1 −1
@@ -31,10 +31,10 @@ session.workspace = true
31 31 store.workspace = true
32 32 teams-core.workspace = true
33 33 tokio.workspace = true
34 uuid.workspace = true
34 35 image = { version = "0.25", default-features = false, features = ["bmp", "gif", "jpeg", "png", "webp"] }
35 36
36 37 [target.'cfg(windows)'.dependencies]
37 uuid.workspace = true
38 38 webview.workspace = true
39 39 raw-window-handle = "0.6"
40 40 rodio = { version = "0.22", default-features = false, features = ["playback", "mp3"] }
@@ -31,10 +31,10 @@ session.workspace = true
31store.workspace = true
31store.workspace = true
32teams-core.workspace = true
32teams-core.workspace = true
33tokio.workspace = true
33tokio.workspace = true
34uuid.workspace = true
34image = { version = "0.25", default-features = false, features = ["bmp", "gif", "jpeg", "png", "webp"] }
35image = { version = "0.25", default-features = false, features = ["bmp", "gif", "jpeg", "png", "webp"] }
35
36
36[target.'cfg(windows)'.dependencies]
37[target.'cfg(windows)'.dependencies]
37uuid.workspace = true
38webview.workspace = true
38webview.workspace = true
39raw-window-handle = "0.6"
39raw-window-handle = "0.6"
40rodio = { version = "0.22", default-features = false, features = ["playback", "mp3"] }
40rodio = { version = "0.22", default-features = false, features = ["playback", "mp3"] }
crates/app/assets/symbols/event.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><g fill="none" stroke="#000" stroke-width="56" stroke-linejoin="round" stroke-linecap="round"><rect x="140" y="-800" width="680" height="640" rx="50"/><path d="M140-620h680M330-880v110M630-880v110"/><rect x="560" y="-500" width="140" height="140" rx="20" fill="#000"/></g></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><g fill="none" stroke="#000" stroke-width="56" stroke-linejoin="round" stroke-linecap="round"><rect x="140" y="-800" width="680" height="640" rx="50"/><path d="M140-620h680M330-880v110M630-880v110"/><rect x="560" y="-500" width="140" height="140" rx="20" fill="#000"/></g></svg>
crates/app/assets/symbols/schedule_send.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><g fill="none" stroke="#000" stroke-width="56" stroke-linejoin="round" stroke-linecap="round"><path d="M500-840 120-700l120 190-120 190 150 60"/><path d="M240-510h140"/><circle cx="640" cy="-290" r="200"/><path d="M640-420v130l80 60"/></g></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><g fill="none" stroke="#000" stroke-width="56" stroke-linejoin="round" stroke-linecap="round"><path d="M500-840 120-700l120 190-120 190 150 60"/><path d="M240-510h140"/><circle cx="640" cy="-290" r="200"/><path d="M640-420v130l80 60"/></g></svg>
crates/app/assets/symbols/wb_sunny.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><g fill="none" stroke="#000" stroke-width="56" stroke-linecap="round"><circle cx="480" cy="-480" r="150"/><path d="M480-800v-60M480-100v-60M160-480h-60M860-480h-60M254-706l-42-42M748-212l-42-42M706-706l42-42M212-212l42-42"/></g></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><g fill="none" stroke="#000" stroke-width="56" stroke-linecap="round"><circle cx="480" cy="-480" r="150"/><path d="M480-800v-60M480-100v-60M160-480h-60M860-480h-60M254-706l-42-42M748-212l-42-42M706-706l42-42M212-212l42-42"/></g></svg>
crates/app/assets/symbols/work.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><g fill="none" stroke="#000" stroke-width="56" stroke-linejoin="round" stroke-linecap="round"><rect x="140" y="-760" width="680" height="500" rx="50"/><path d="M360-760v-70q0-30 30-30h180q30 0 30 30v70M140-500h680"/></g></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><g fill="none" stroke="#000" stroke-width="56" stroke-linejoin="round" stroke-linecap="round"><rect x="140" y="-760" width="680" height="500" rx="50"/><path d="M360-760v-70q0-30 30-30h180q30 0 30 30v70M140-500h680"/></g></svg>
crates/app/src/app_state.rs +14 −1
@@ -6,11 +6,12 @@ use chatsvc::TypingEvent;
6 6 use chrono::{DateTime, Utc};
7 7 use gpui_kit::*;
8 8 use store::{ChatRecord, Sidebar, Store};
9 use teams_core::{ChatApp, CoreEvent, ImageRef};
9 use teams_core::{ChatApp, CoreEvent, ImageRef, ScheduledDraft};
10 10
11 11 use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};
12 12 use crate::card_state::{CardState, TaskDialogState};
13 13 use crate::data::{self, Directory};
14 use crate::local_previews::{LocalPreview, load_local_previews};
14 15 use crate::notice::Notice;
15 16 use crate::notify;
16 17 use crate::typing::TypingState;
@@ -43,6 +44,9 @@ pub enum AppEvent {
43 44 Cards(String),
44 45 TaskDialog,
45 46 Typing,
47 LocalPreviews,
48 Outbox(String),
49 Scheduled,
46 50 }
47 51
48 52 #[derive(Debug, Clone, Copy, Default)]
@@ -77,6 +81,9 @@ pub struct AppState {
77 81 pub keep_unread: Option<String>,
78 82 pub typing: TypingState,
79 83 typing_timer_running: bool,
84 pub local_previews: HashMap<String, LocalPreview>,
85 pub scheduled: Vec<ScheduledDraft>,
86 pub scheduled_polling: bool,
80 87 }
81 88
82 89 pub struct AppHandle(pub Entity<AppState>);
@@ -148,7 +155,11 @@ impl AppState {
148 155 keep_unread: None,
149 156 typing: TypingState::default(),
150 157 typing_timer_running: false,
158 local_previews: HashMap::new(),
159 scheduled: Vec::new(),
160 scheduled_polling: false,
151 161 };
162 state.local_previews = load_local_previews(&state.store);
152 163 state.collapsed = state.load_collapsed();
153 164 state.followed_channels = notify::load_followed_channels(&state.store);
154 165 if !mode.demo {
@@ -550,6 +561,8 @@ impl AppState {
550 561 }
551 562 BackendEvent::Engine(engine) => {
552 563 self.engine = Some(engine);
564 self.resend_outbox(cx);
565 self.refresh_scheduled(cx);
553 566 let waiting = self.directory.waiting_presence_ids();
554 567 self.request_presence(waiting, cx);
555 568 cx.emit(AppEvent::Status);
@@ -6,11 +6,12 @@ use chatsvc::TypingEvent;
6use chrono::{DateTime, Utc};
6use chrono::{DateTime, Utc};
7use gpui_kit::*;
7use gpui_kit::*;
8use store::{ChatRecord, Sidebar, Store};
8use store::{ChatRecord, Sidebar, Store};
9use teams_core::{ChatApp, CoreEvent, ImageRef};
9use teams_core::{ChatApp, CoreEvent, ImageRef, ScheduledDraft};
10
10
11use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};
11use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};
12use crate::card_state::{CardState, TaskDialogState};
12use crate::card_state::{CardState, TaskDialogState};
13use crate::data::{self, Directory};
13use crate::data::{self, Directory};
14use crate::local_previews::{LocalPreview, load_local_previews};
14use crate::notice::Notice;
15use crate::notice::Notice;
15use crate::notify;
16use crate::notify;
16use crate::typing::TypingState;
17use crate::typing::TypingState;
@@ -43,6 +44,9 @@ pub enum AppEvent {
43 Cards(String),
44 Cards(String),
44 TaskDialog,
45 TaskDialog,
45 Typing,
46 Typing,
47 LocalPreviews,
48 Outbox(String),
49 Scheduled,
46}
50}
47
51
48#[derive(Debug, Clone, Copy, Default)]
52#[derive(Debug, Clone, Copy, Default)]
@@ -77,6 +81,9 @@ pub struct AppState {
77 pub keep_unread: Option<String>,
81 pub keep_unread: Option<String>,
78 pub typing: TypingState,
82 pub typing: TypingState,
79 typing_timer_running: bool,
83 typing_timer_running: bool,
84 pub local_previews: HashMap<String, LocalPreview>,
85 pub scheduled: Vec<ScheduledDraft>,
86 pub scheduled_polling: bool,
80}
87}
81
88
82pub struct AppHandle(pub Entity<AppState>);
89pub struct AppHandle(pub Entity<AppState>);
@@ -148,7 +155,11 @@ impl AppState {
148 keep_unread: None,
155 keep_unread: None,
149 typing: TypingState::default(),
156 typing: TypingState::default(),
150 typing_timer_running: false,
157 typing_timer_running: false,
158 local_previews: HashMap::new(),
159 scheduled: Vec::new(),
160 scheduled_polling: false,
151 };
161 };
162 state.local_previews = load_local_previews(&state.store);
152 state.collapsed = state.load_collapsed();
163 state.collapsed = state.load_collapsed();
153 state.followed_channels = notify::load_followed_channels(&state.store);
164 state.followed_channels = notify::load_followed_channels(&state.store);
154 if !mode.demo {
165 if !mode.demo {
@@ -550,6 +561,8 @@ impl AppState {
550 }
561 }
551 BackendEvent::Engine(engine) => {
562 BackendEvent::Engine(engine) => {
552 self.engine = Some(engine);
563 self.engine = Some(engine);
564 self.resend_outbox(cx);
565 self.refresh_scheduled(cx);
553 let waiting = self.directory.waiting_presence_ids();
566 let waiting = self.directory.waiting_presence_ids();
554 self.request_presence(waiting, cx);
567 self.request_presence(waiting, cx);
555 cx.emit(AppEvent::Status);
568 cx.emit(AppEvent::Status);
crates/app/src/assets.rs +5 −1
@@ -8,11 +8,15 @@ macro_rules! symbols {
8 8 };
9 9 }
10 10
11 const SYMBOLS: [(&str, &[u8]); 24] = symbols![
11 const SYMBOLS: [(&str, &[u8]); 28] = symbols![
12 12 "done",
13 13 "done_all",
14 14 "keyboard_return",
15 15 "schedule",
16 "schedule_send",
17 "event",
18 "wb_sunny",
19 "work",
16 20 "close",
17 21 "reply",
18 22 "group",
@@ -8,11 +8,15 @@ macro_rules! symbols {
8 };
8 };
9}
9}
10
10
11const SYMBOLS: [(&str, &[u8]); 24] = symbols![
11const SYMBOLS: [(&str, &[u8]); 28] = symbols![
12 "done",
12 "done",
13 "done_all",
13 "done_all",
14 "keyboard_return",
14 "keyboard_return",
15 "schedule",
15 "schedule",
16 "schedule_send",
17 "event",
18 "wb_sunny",
19 "work",
16 "close",
20 "close",
17 "reply",
21 "reply",
18 "group",
22 "group",
crates/app/src/local_previews.rs added +77 −0
@@ -0,0 +1,77 @@
1 use std::collections::HashMap;
2
3 use gpui_kit::Context;
4 use store::Store;
5
6 use crate::app_state::{AppEvent, AppState};
7
8 #[derive(Debug, Clone, PartialEq, Eq)]
9 pub enum LocalPreview {
10 Draft(String),
11 NotSent,
12 }
13
14 pub fn load_local_previews(store: &Store) -> HashMap<String, LocalPreview> {
15 let mut previews: HashMap<String, LocalPreview> = store
16 .draft_previews()
17 .unwrap_or_default()
18 .into_iter()
19 .map(|(conversation_id, text)| (conversation_id, LocalPreview::Draft(text)))
20 .collect();
21 for conversation_id in store.failed_outbox_conversations().unwrap_or_default() {
22 previews.insert(conversation_id, LocalPreview::NotSent);
23 }
24 previews
25 }
26
27 impl AppState {
28 pub fn refresh_local_previews(&mut self, cx: &mut Context<Self>) {
29 let previews = load_local_previews(&self.store);
30 if previews != self.local_previews {
31 self.local_previews = previews;
32 cx.emit(AppEvent::LocalPreviews);
33 }
34 }
35 }
36
37 #[cfg(test)]
38 mod tests {
39 use chrono::Utc;
40 use store::{DraftRecord, OutboxRecord, OutboxState, OutboxTarget};
41
42 use super::*;
43
44 fn failed_row(conversation_id: &str) -> OutboxRecord {
45 OutboxRecord {
46 id: "row".to_owned(),
47 conversation_id: conversation_id.to_owned(),
48 target: OutboxTarget::Flat,
49 thread_root_id: None,
50 payload: "{}".to_owned(),
51 images: Vec::new(),
52 state: OutboxState::Failed,
53 last_error: None,
54 created_at: Utc::now(),
55 }
56 }
57
58 #[test]
59 fn a_failed_send_beats_the_draft_in_the_same_chat() {
60 let store = Store::open_in_memory().unwrap();
61 for (conversation_id, preview) in [("a", "typing"), ("b", "also typing")] {
62 store
63 .save_draft(&DraftRecord {
64 conversation_id: conversation_id.to_owned(),
65 payload: "{}".to_owned(),
66 preview: preview.to_owned(),
67 images: Vec::new(),
68 updated_at: Utc::now(),
69 })
70 .unwrap();
71 }
72 store.put_outbox(&failed_row("a")).unwrap();
73 let previews = load_local_previews(&store);
74 assert_eq!(previews["a"], LocalPreview::NotSent);
75 assert_eq!(previews["b"], LocalPreview::Draft("also typing".to_owned()));
76 }
77 }
@@ -0,0 +1,77 @@
1use std::collections::HashMap;
2
3use gpui_kit::Context;
4use store::Store;
5
6use crate::app_state::{AppEvent, AppState};
7
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub enum LocalPreview {
10 Draft(String),
11 NotSent,
12}
13
14pub fn load_local_previews(store: &Store) -> HashMap<String, LocalPreview> {
15 let mut previews: HashMap<String, LocalPreview> = store
16 .draft_previews()
17 .unwrap_or_default()
18 .into_iter()
19 .map(|(conversation_id, text)| (conversation_id, LocalPreview::Draft(text)))
20 .collect();
21 for conversation_id in store.failed_outbox_conversations().unwrap_or_default() {
22 previews.insert(conversation_id, LocalPreview::NotSent);
23 }
24 previews
25}
26
27impl AppState {
28 pub fn refresh_local_previews(&mut self, cx: &mut Context<Self>) {
29 let previews = load_local_previews(&self.store);
30 if previews != self.local_previews {
31 self.local_previews = previews;
32 cx.emit(AppEvent::LocalPreviews);
33 }
34 }
35}
36
37#[cfg(test)]
38mod tests {
39 use chrono::Utc;
40 use store::{DraftRecord, OutboxRecord, OutboxState, OutboxTarget};
41
42 use super::*;
43
44 fn failed_row(conversation_id: &str) -> OutboxRecord {
45 OutboxRecord {
46 id: "row".to_owned(),
47 conversation_id: conversation_id.to_owned(),
48 target: OutboxTarget::Flat,
49 thread_root_id: None,
50 payload: "{}".to_owned(),
51 images: Vec::new(),
52 state: OutboxState::Failed,
53 last_error: None,
54 created_at: Utc::now(),
55 }
56 }
57
58 #[test]
59 fn a_failed_send_beats_the_draft_in_the_same_chat() {
60 let store = Store::open_in_memory().unwrap();
61 for (conversation_id, preview) in [("a", "typing"), ("b", "also typing")] {
62 store
63 .save_draft(&DraftRecord {
64 conversation_id: conversation_id.to_owned(),
65 payload: "{}".to_owned(),
66 preview: preview.to_owned(),
67 images: Vec::new(),
68 updated_at: Utc::now(),
69 })
70 .unwrap();
71 }
72 store.put_outbox(&failed_row("a")).unwrap();
73 let previews = load_local_previews(&store);
74 assert_eq!(previews["a"], LocalPreview::NotSent);
75 assert_eq!(previews["b"], LocalPreview::Draft("also typing".to_owned()));
76 }
77}
crates/app/src/main.rs +7 −0
@@ -22,8 +22,11 @@ mod format;
22 22 mod frame_log;
23 23 mod fuzzy;
24 24 mod gifs;
25 mod local_previews;
25 26 mod notice;
26 27 mod notify;
28 mod outbox;
29 mod pending_rows;
27 30 mod people;
28 31 mod reaction_model;
29 32 mod read_state;
@@ -31,9 +34,13 @@ mod remote_image;
31 34 mod render;
32 35 mod rows;
33 36 mod runtime;
37 mod schedule_time;
38 mod scheduled;
39 mod scheduled_rows;
34 40 mod single_instance;
35 41 mod sidebar_model;
36 42 mod stickers;
43 mod stored_outgoing;
37 44 mod task_dialog;
38 45 mod theme;
39 46 mod typing;
@@ -22,8 +22,11 @@ mod format;
22mod frame_log;
22mod frame_log;
23mod fuzzy;
23mod fuzzy;
24mod gifs;
24mod gifs;
25mod local_previews;
25mod notice;
26mod notice;
26mod notify;
27mod notify;
28mod outbox;
29mod pending_rows;
27mod people;
30mod people;
28mod reaction_model;
31mod reaction_model;
29mod read_state;
32mod read_state;
@@ -31,9 +34,13 @@ mod remote_image;
31mod render;
34mod render;
32mod rows;
35mod rows;
33mod runtime;
36mod runtime;
37mod schedule_time;
38mod scheduled;
39mod scheduled_rows;
34mod single_instance;
40mod single_instance;
35mod sidebar_model;
41mod sidebar_model;
36mod stickers;
42mod stickers;
43mod stored_outgoing;
37mod task_dialog;
44mod task_dialog;
38mod theme;
45mod theme;
39mod typing;
46mod typing;
crates/app/src/outbox.rs added +314 −0
@@ -0,0 +1,314 @@
1 use std::collections::HashMap;
2 use std::time::Duration;
3
4 use chrono::{DateTime, Utc};
5 use gpui_kit::Context;
6 use store::{MessageRecord, OutboxRecord, OutboxState, OutboxTarget, plain_text};
7 use uuid::Uuid;
8
9 use crate::app_state::{AppEvent, AppState};
10 use crate::backend::Engine;
11 use crate::notice::short_error;
12 use crate::runtime;
13 use crate::stored_outgoing::{decode, encode};
14 use crate::views::composer::Outgoing;
15
16 const RETRY_BACKOFF: [Duration; 3] = [
17 Duration::from_secs(2),
18 Duration::from_secs(8),
19 Duration::from_secs(30),
20 ];
21 const DUPLICATE_WINDOW_SECONDS: i64 = 5;
22 const RECENT_MESSAGES: usize = 30;
23
24 pub fn new_outbox_id() -> String {
25 Uuid::new_v4().to_string()
26 }
27
28 pub fn outbox_record(
29 id: &str,
30 conversation_id: &str,
31 target: OutboxTarget,
32 thread_root_id: Option<&str>,
33 outgoing: &Outgoing,
34 created_at: DateTime<Utc>,
35 ) -> Option<OutboxRecord> {
36 let stored = encode(outgoing)?;
37 Some(OutboxRecord {
38 id: id.to_owned(),
39 conversation_id: conversation_id.to_owned(),
40 target,
41 thread_root_id: thread_root_id.map(str::to_owned),
42 payload: stored.payload,
43 images: stored.images,
44 state: OutboxState::Sending,
45 last_error: None,
46 created_at,
47 })
48 }
49
50 pub fn outgoing_of(record: &OutboxRecord) -> Option<Outgoing> {
51 decode(&record.payload, &record.images)
52 }
53
54 pub async fn deliver(
55 engine: &Engine,
56 conversation_id: &str,
57 target: OutboxTarget,
58 thread_root_id: Option<&str>,
59 outgoing: &Outgoing,
60 ) -> teams_core::Result<()> {
61 let extras = outgoing.extras();
62 let html = outgoing.html();
63 let mentions = &outgoing.mentions;
64 let record = match (target, &outgoing.reply) {
65 (_, Some(reply)) => {
66 engine
67 .reply_to_with_extras(conversation_id, &reply.message_id, &html, mentions, &extras)
68 .await
69 }
70 (OutboxTarget::Flat, None) => {
71 engine
72 .send_message_with_extras(conversation_id, &html, None, mentions, &extras)
73 .await
74 }
75 (OutboxTarget::Post, None) => {
76 engine
77 .post_to_channel_with_extras(conversation_id, &html, None, mentions, &extras)
78 .await
79 }
80 (OutboxTarget::Thread, None) => {
81 engine
82 .send_message_with_extras(conversation_id, &html, thread_root_id, mentions, &extras)
83 .await
84 }
85 }?;
86 if let Some(preview) = &outgoing.link_preview {
87 let _ = engine
88 .attach_link_preview(conversation_id, &record.message_id, preview)
89 .await;
90 }
91 Ok(())
92 }
93
94 fn is_permanent(error: &teams_core::Error) -> bool {
95 match error {
96 teams_core::Error::Graph(graph::Error::Session(session::Error::Api { status, .. })) => {
97 (400..500).contains(status) && !matches!(status, 408 | 429)
98 }
99 teams_core::Error::Graph(graph::Error::NotAMember)
100 | teams_core::Error::Unsupported(_)
101 | teams_core::Error::UnknownConversation(_) => true,
102 _ => false,
103 }
104 }
105
106 fn comparable(text: &str) -> String {
107 text.chars()
108 .filter(|character| character.is_alphanumeric())
109 .collect()
110 }
111
112 fn is_duplicate(
113 recent: &[MessageRecord],
114 my_user_id: &str,
115 created_at: DateTime<Utc>,
116 text: &str,
117 ) -> bool {
118 let wanted = comparable(text);
119 let since = created_at - chrono::Duration::seconds(DUPLICATE_WINDOW_SECONDS);
120 !wanted.is_empty()
121 && recent.iter().any(|message| {
122 !message.deleted
123 && message.sender_id.as_deref() == Some(my_user_id)
124 && message.created_at >= since
125 && comparable(&plain_text(&message.body_html)) == wanted
126 })
127 }
128
129 async fn already_sent(
130 engine: &Engine,
131 record: &OutboxRecord,
132 outgoing: &Outgoing,
133 ) -> teams_core::Result<bool> {
134 engine.fetch_newer(&record.conversation_id).await?;
135 let Some(me) = engine.me() else {
136 return Ok(false);
137 };
138 let recent = engine
139 .store()
140 .messages(&record.conversation_id, None, RECENT_MESSAGES)?;
141 Ok(is_duplicate(
142 &recent,
143 &me.user_id,
144 record.created_at,
145 &outgoing.text(),
146 ))
147 }
148
149 async fn attempt(
150 engine: &Engine,
151 record: &OutboxRecord,
152 outgoing: &Outgoing,
153 ) -> teams_core::Result<()> {
154 // Graph has no idempotency key: a send cut off by the quit may have gone through.
155 if already_sent(engine, record, outgoing).await? {
156 return Ok(());
157 }
158 deliver(
159 engine,
160 &record.conversation_id,
161 record.target,
162 record.thread_root_id.as_deref(),
163 outgoing,
164 )
165 .await
166 }
167
168 async fn resend(engine: &Engine, record: &OutboxRecord, outgoing: &Outgoing) -> Result<(), String> {
169 let mut failure = String::new();
170 for attempt_number in 0..=RETRY_BACKOFF.len() {
171 if let Some(delay) = attempt_number
172 .checked_sub(1)
173 .map(|index| RETRY_BACKOFF[index])
174 {
175 tokio::time::sleep(delay).await;
176 }
177 match attempt(engine, record, outgoing).await {
178 Ok(()) => return Ok(()),
179 Err(error) if is_permanent(&error) => return Err(short_error(&error)),
180 Err(error) => failure = short_error(&error),
181 }
182 }
183 Err(failure)
184 }
185
186 async fn resend_record(engine: &Engine, record: OutboxRecord) {
187 let store = engine.store();
188 let outcome = match outgoing_of(&record) {
189 Some(outgoing) => resend(engine, &record, &outgoing).await,
190 None => Err("The saved message could not be read".to_owned()),
191 };
192 match outcome {
193 Ok(()) => store.delete_outbox(&record.id).ok(),
194 Err(error) => store.mark_outbox_failed(&record.id, &error).ok(),
195 };
196 }
197
198 impl AppState {
199 pub fn resend_outbox(&mut self, cx: &mut Context<Self>) {
200 if self.mode.demo || self.mode.read_only {
201 return;
202 }
203 let Some(engine) = self.engine.clone() else {
204 return;
205 };
206 let Ok(records) = self.store.sending_outbox() else {
207 return;
208 };
209 let mut by_conversation: Vec<(String, Vec<OutboxRecord>)> = Vec::new();
210 let mut positions: HashMap<String, usize> = HashMap::new();
211 for record in records {
212 let position = *positions
213 .entry(record.conversation_id.clone())
214 .or_insert_with(|| {
215 by_conversation.push((record.conversation_id.clone(), Vec::new()));
216 by_conversation.len() - 1
217 });
218 by_conversation[position].1.push(record);
219 }
220 let (finished, mut finished_conversations) = tokio::sync::mpsc::unbounded_channel();
221 for (conversation_id, records) in by_conversation {
222 let (engine, finished) = (engine.clone(), finished.clone());
223 runtime::handle().spawn(async move {
224 for record in records {
225 resend_record(&engine, record).await;
226 let _ = finished.send(conversation_id.clone());
227 }
228 });
229 }
230 drop(finished);
231 cx.spawn(async move |this, cx| {
232 while let Some(conversation_id) = finished_conversations.recv().await {
233 this.update(cx, |state, cx| state.outbox_changed(conversation_id, cx))
234 .ok();
235 }
236 })
237 .detach();
238 }
239
240 pub fn outbox_changed(&mut self, conversation_id: String, cx: &mut Context<Self>) {
241 self.refresh_local_previews(cx);
242 cx.emit(AppEvent::Outbox(conversation_id));
243 }
244 }
245
246 #[cfg(test)]
247 mod tests {
248 use chrono::TimeZone;
249
250 use super::*;
251
252 fn message(sender: &str, second: u32, html: &str) -> MessageRecord {
253 MessageRecord {
254 sender_id: Some(sender.to_owned()),
255 created_at: Utc.with_ymd_and_hms(2026, 10, 6, 9, 0, second).unwrap(),
256 body_html: html.to_owned(),
257 ..MessageRecord::default()
258 }
259 }
260
261 fn sent_at(second: u32) -> DateTime<Utc> {
262 Utc.with_ymd_and_hms(2026, 10, 6, 9, 0, second).unwrap()
263 }
264
265 #[test]
266 fn an_own_message_with_the_same_text_after_the_send_is_a_duplicate() {
267 let recent = [message("me", 31, "<p>Hello <at>Ada</at>!</p>")];
268 assert!(is_duplicate(&recent, "me", sent_at(30), "Hello @Ada!"));
269 }
270
271 #[test]
272 fn a_message_up_to_five_seconds_before_the_send_still_counts() {
273 let recent = [message("me", 25, "<p>Hi</p>")];
274 assert!(is_duplicate(&recent, "me", sent_at(30), "Hi"));
275 let recent = [message("me", 24, "<p>Hi</p>")];
276 assert!(!is_duplicate(&recent, "me", sent_at(30), "Hi"));
277 }
278
279 #[test]
280 fn other_senders_other_text_and_empty_text_are_no_duplicates() {
281 let recent = [
282 message("other", 31, "<p>Hi</p>"),
283 message("me", 32, "<p>Bye</p>"),
284 ];
285 assert!(!is_duplicate(&recent, "me", sent_at(30), "Hi"));
286 let image_only = [message("me", 31, "<img src=\"x\">")];
287 assert!(!is_duplicate(&image_only, "me", sent_at(30), ""));
288 }
289
290 #[test]
291 fn deleted_messages_are_no_duplicates() {
292 let mut deleted = message("me", 31, "<p>Hi</p>");
293 deleted.deleted = true;
294 assert!(!is_duplicate(&[deleted], "me", sent_at(30), "Hi"));
295 }
296
297 #[test]
298 fn client_errors_fail_at_once_and_server_errors_retry() {
299 let api = |status| {
300 teams_core::Error::Graph(graph::Error::Session(session::Error::api(
301 status,
302 "https://graph.test",
303 serde_json::json!({}),
304 )))
305 };
306 assert!(is_permanent(&api(403)));
307 assert!(is_permanent(&api(400)));
308 assert!(!is_permanent(&api(429)));
309 assert!(!is_permanent(&api(503)));
310 assert!(!is_permanent(&teams_core::Error::Graph(
311 graph::Error::Download("x".into())
312 )));
313 }
314 }
@@ -0,0 +1,314 @@
1use std::collections::HashMap;
2use std::time::Duration;
3
4use chrono::{DateTime, Utc};
5use gpui_kit::Context;
6use store::{MessageRecord, OutboxRecord, OutboxState, OutboxTarget, plain_text};
7use uuid::Uuid;
8
9use crate::app_state::{AppEvent, AppState};
10use crate::backend::Engine;
11use crate::notice::short_error;
12use crate::runtime;
13use crate::stored_outgoing::{decode, encode};
14use crate::views::composer::Outgoing;
15
16const RETRY_BACKOFF: [Duration; 3] = [
17 Duration::from_secs(2),
18 Duration::from_secs(8),
19 Duration::from_secs(30),
20];
21const DUPLICATE_WINDOW_SECONDS: i64 = 5;
22const RECENT_MESSAGES: usize = 30;
23
24pub fn new_outbox_id() -> String {
25 Uuid::new_v4().to_string()
26}
27
28pub fn outbox_record(
29 id: &str,
30 conversation_id: &str,
31 target: OutboxTarget,
32 thread_root_id: Option<&str>,
33 outgoing: &Outgoing,
34 created_at: DateTime<Utc>,
35) -> Option<OutboxRecord> {
36 let stored = encode(outgoing)?;
37 Some(OutboxRecord {
38 id: id.to_owned(),
39 conversation_id: conversation_id.to_owned(),
40 target,
41 thread_root_id: thread_root_id.map(str::to_owned),
42 payload: stored.payload,
43 images: stored.images,
44 state: OutboxState::Sending,
45 last_error: None,
46 created_at,
47 })
48}
49
50pub fn outgoing_of(record: &OutboxRecord) -> Option<Outgoing> {
51 decode(&record.payload, &record.images)
52}
53
54pub async fn deliver(
55 engine: &Engine,
56 conversation_id: &str,
57 target: OutboxTarget,
58 thread_root_id: Option<&str>,
59 outgoing: &Outgoing,
60) -> teams_core::Result<()> {
61 let extras = outgoing.extras();
62 let html = outgoing.html();
63 let mentions = &outgoing.mentions;
64 let record = match (target, &outgoing.reply) {
65 (_, Some(reply)) => {
66 engine
67 .reply_to_with_extras(conversation_id, &reply.message_id, &html, mentions, &extras)
68 .await
69 }
70 (OutboxTarget::Flat, None) => {
71 engine
72 .send_message_with_extras(conversation_id, &html, None, mentions, &extras)
73 .await
74 }
75 (OutboxTarget::Post, None) => {
76 engine
77 .post_to_channel_with_extras(conversation_id, &html, None, mentions, &extras)
78 .await
79 }
80 (OutboxTarget::Thread, None) => {
81 engine
82 .send_message_with_extras(conversation_id, &html, thread_root_id, mentions, &extras)
83 .await
84 }
85 }?;
86 if let Some(preview) = &outgoing.link_preview {
87 let _ = engine
88 .attach_link_preview(conversation_id, &record.message_id, preview)
89 .await;
90 }
91 Ok(())
92}
93
94fn is_permanent(error: &teams_core::Error) -> bool {
95 match error {
96 teams_core::Error::Graph(graph::Error::Session(session::Error::Api { status, .. })) => {
97 (400..500).contains(status) && !matches!(status, 408 | 429)
98 }
99 teams_core::Error::Graph(graph::Error::NotAMember)
100 | teams_core::Error::Unsupported(_)
101 | teams_core::Error::UnknownConversation(_) => true,
102 _ => false,
103 }
104}
105
106fn comparable(text: &str) -> String {
107 text.chars()
108 .filter(|character| character.is_alphanumeric())
109 .collect()
110}
111
112fn is_duplicate(
113 recent: &[MessageRecord],
114 my_user_id: &str,
115 created_at: DateTime<Utc>,
116 text: &str,
117) -> bool {
118 let wanted = comparable(text);
119 let since = created_at - chrono::Duration::seconds(DUPLICATE_WINDOW_SECONDS);
120 !wanted.is_empty()
121 && recent.iter().any(|message| {
122 !message.deleted
123 && message.sender_id.as_deref() == Some(my_user_id)
124 && message.created_at >= since
125 && comparable(&plain_text(&message.body_html)) == wanted
126 })
127}
128
129async fn already_sent(
130 engine: &Engine,
131 record: &OutboxRecord,
132 outgoing: &Outgoing,
133) -> teams_core::Result<bool> {
134 engine.fetch_newer(&record.conversation_id).await?;
135 let Some(me) = engine.me() else {
136 return Ok(false);
137 };
138 let recent = engine
139 .store()
140 .messages(&record.conversation_id, None, RECENT_MESSAGES)?;
141 Ok(is_duplicate(
142 &recent,
143 &me.user_id,
144 record.created_at,
145 &outgoing.text(),
146 ))
147}
148
149async fn attempt(
150 engine: &Engine,
151 record: &OutboxRecord,
152 outgoing: &Outgoing,
153) -> teams_core::Result<()> {
154 // Graph has no idempotency key: a send cut off by the quit may have gone through.
155 if already_sent(engine, record, outgoing).await? {
156 return Ok(());
157 }
158 deliver(
159 engine,
160 &record.conversation_id,
161 record.target,
162 record.thread_root_id.as_deref(),
163 outgoing,
164 )
165 .await
166}
167
168async fn resend(engine: &Engine, record: &OutboxRecord, outgoing: &Outgoing) -> Result<(), String> {
169 let mut failure = String::new();
170 for attempt_number in 0..=RETRY_BACKOFF.len() {
171 if let Some(delay) = attempt_number
172 .checked_sub(1)
173 .map(|index| RETRY_BACKOFF[index])
174 {
175 tokio::time::sleep(delay).await;
176 }
177 match attempt(engine, record, outgoing).await {
178 Ok(()) => return Ok(()),
179 Err(error) if is_permanent(&error) => return Err(short_error(&error)),
180 Err(error) => failure = short_error(&error),
181 }
182 }
183 Err(failure)
184}
185
186async fn resend_record(engine: &Engine, record: OutboxRecord) {
187 let store = engine.store();
188 let outcome = match outgoing_of(&record) {
189 Some(outgoing) => resend(engine, &record, &outgoing).await,
190 None => Err("The saved message could not be read".to_owned()),
191 };
192 match outcome {
193 Ok(()) => store.delete_outbox(&record.id).ok(),
194 Err(error) => store.mark_outbox_failed(&record.id, &error).ok(),
195 };
196}
197
198impl AppState {
199 pub fn resend_outbox(&mut self, cx: &mut Context<Self>) {
200 if self.mode.demo || self.mode.read_only {
201 return;
202 }
203 let Some(engine) = self.engine.clone() else {
204 return;
205 };
206 let Ok(records) = self.store.sending_outbox() else {
207 return;
208 };
209 let mut by_conversation: Vec<(String, Vec<OutboxRecord>)> = Vec::new();
210 let mut positions: HashMap<String, usize> = HashMap::new();
211 for record in records {
212 let position = *positions
213 .entry(record.conversation_id.clone())
214 .or_insert_with(|| {
215 by_conversation.push((record.conversation_id.clone(), Vec::new()));
216 by_conversation.len() - 1
217 });
218 by_conversation[position].1.push(record);
219 }
220 let (finished, mut finished_conversations) = tokio::sync::mpsc::unbounded_channel();
221 for (conversation_id, records) in by_conversation {
222 let (engine, finished) = (engine.clone(), finished.clone());
223 runtime::handle().spawn(async move {
224 for record in records {
225 resend_record(&engine, record).await;
226 let _ = finished.send(conversation_id.clone());
227 }
228 });
229 }
230 drop(finished);
231 cx.spawn(async move |this, cx| {
232 while let Some(conversation_id) = finished_conversations.recv().await {
233 this.update(cx, |state, cx| state.outbox_changed(conversation_id, cx))
234 .ok();
235 }
236 })
237 .detach();
238 }
239
240 pub fn outbox_changed(&mut self, conversation_id: String, cx: &mut Context<Self>) {
241 self.refresh_local_previews(cx);
242 cx.emit(AppEvent::Outbox(conversation_id));
243 }
244}
245
246#[cfg(test)]
247mod tests {
248 use chrono::TimeZone;
249
250 use super::*;
251
252 fn message(sender: &str, second: u32, html: &str) -> MessageRecord {
253 MessageRecord {
254 sender_id: Some(sender.to_owned()),
255 created_at: Utc.with_ymd_and_hms(2026, 10, 6, 9, 0, second).unwrap(),
256 body_html: html.to_owned(),
257 ..MessageRecord::default()
258 }
259 }
260
261 fn sent_at(second: u32) -> DateTime<Utc> {
262 Utc.with_ymd_and_hms(2026, 10, 6, 9, 0, second).unwrap()
263 }
264
265 #[test]
266 fn an_own_message_with_the_same_text_after_the_send_is_a_duplicate() {
267 let recent = [message("me", 31, "<p>Hello <at>Ada</at>!</p>")];
268 assert!(is_duplicate(&recent, "me", sent_at(30), "Hello @Ada!"));
269 }
270
271 #[test]
272 fn a_message_up_to_five_seconds_before_the_send_still_counts() {
273 let recent = [message("me", 25, "<p>Hi</p>")];
274 assert!(is_duplicate(&recent, "me", sent_at(30), "Hi"));
275 let recent = [message("me", 24, "<p>Hi</p>")];
276 assert!(!is_duplicate(&recent, "me", sent_at(30), "Hi"));
277 }
278
279 #[test]
280 fn other_senders_other_text_and_empty_text_are_no_duplicates() {
281 let recent = [
282 message("other", 31, "<p>Hi</p>"),
283 message("me", 32, "<p>Bye</p>"),
284 ];
285 assert!(!is_duplicate(&recent, "me", sent_at(30), "Hi"));
286 let image_only = [message("me", 31, "<img src=\"x\">")];
287 assert!(!is_duplicate(&image_only, "me", sent_at(30), ""));
288 }
289
290 #[test]
291 fn deleted_messages_are_no_duplicates() {
292 let mut deleted = message("me", 31, "<p>Hi</p>");
293 deleted.deleted = true;
294 assert!(!is_duplicate(&[deleted], "me", sent_at(30), "Hi"));
295 }
296
297 #[test]
298 fn client_errors_fail_at_once_and_server_errors_retry() {
299 let api = |status| {
300 teams_core::Error::Graph(graph::Error::Session(session::Error::api(
301 status,
302 "https://graph.test",
303 serde_json::json!({}),
304 )))
305 };
306 assert!(is_permanent(&api(403)));
307 assert!(is_permanent(&api(400)));
308 assert!(!is_permanent(&api(429)));
309 assert!(!is_permanent(&api(503)));
310 assert!(!is_permanent(&teams_core::Error::Graph(
311 graph::Error::Download("x".into())
312 )));
313 }
314}
crates/app/src/pending_rows.rs added +78 −0
@@ -0,0 +1,78 @@
1 use chrono::{DateTime, Local, Utc};
2 use teams_core::FileCard;
3
4 use crate::render::layout_blocks;
5 use crate::rows::{Delivery, LocalImage, MessageRow, Receipt, Series};
6 use crate::views::attachment_tray::OutgoingImage;
7 use crate::views::composer::Outgoing;
8
9 pub fn pending_row(
10 key: String,
11 conversation_id: String,
12 my_user_id: Option<String>,
13 created_at: DateTime<Utc>,
14 outgoing: &Outgoing,
15 delivery: Delivery,
16 ) -> MessageRow {
17 MessageRow {
18 key,
19 conversation_id,
20 author: "You".to_owned(),
21 sender_id: my_user_id,
22 application_id: None,
23 created_at,
24 series: Series::default(),
25 card: false,
26 time: created_at.with_timezone(&Local).format("%H:%M").to_string(),
27 day_header: None,
28 blocks: if outgoing.draft.is_blank() && outgoing.images.is_empty() {
29 Vec::new()
30 } else {
31 layout_blocks(&teams_core::html_to_spans(&outgoing.html()))
32 },
33 edited: false,
34 deleted: false,
35 reactions: Vec::new(),
36 images: outgoing
37 .images
38 .iter()
39 .filter_map(|image| match image {
40 OutgoingImage::Remote(remote) => Some(remote.image_ref()),
41 OutgoingImage::Inline(_) => None,
42 })
43 .collect(),
44 local_images: outgoing
45 .images
46 .iter()
47 .filter_map(|image| match image {
48 OutgoingImage::Inline(inline) => Some(LocalImage {
49 image: inline.image.clone(),
50 size: inline.dimensions,
51 }),
52 OutgoingImage::Remote(_) => None,
53 })
54 .collect(),
55 adaptive_cards: Vec::new(),
56 link_preview: outgoing.link_preview.clone(),
57 files: outgoing
58 .files
59 .iter()
60 .map(|file| FileCard {
61 name: file.name.clone(),
62 kind: file.kind,
63 content_type: None,
64 size: Some(file.size),
65 open_url: file.reference.content_url.clone(),
66 })
67 .collect(),
68 reply_count: None,
69 new_marker: false,
70 reply_faces: Vec::new(),
71 last_reply_time: None,
72 open_thread: None,
73 is_reply: false,
74 delivery,
75 receipt: Receipt::Hidden,
76 own: true,
77 }
78 }
@@ -0,0 +1,78 @@
1use chrono::{DateTime, Local, Utc};
2use teams_core::FileCard;
3
4use crate::render::layout_blocks;
5use crate::rows::{Delivery, LocalImage, MessageRow, Receipt, Series};
6use crate::views::attachment_tray::OutgoingImage;
7use crate::views::composer::Outgoing;
8
9pub fn pending_row(
10 key: String,
11 conversation_id: String,
12 my_user_id: Option<String>,
13 created_at: DateTime<Utc>,
14 outgoing: &Outgoing,
15 delivery: Delivery,
16) -> MessageRow {
17 MessageRow {
18 key,
19 conversation_id,
20 author: "You".to_owned(),
21 sender_id: my_user_id,
22 application_id: None,
23 created_at,
24 series: Series::default(),
25 card: false,
26 time: created_at.with_timezone(&Local).format("%H:%M").to_string(),
27 day_header: None,
28 blocks: if outgoing.draft.is_blank() && outgoing.images.is_empty() {
29 Vec::new()
30 } else {
31 layout_blocks(&teams_core::html_to_spans(&outgoing.html()))
32 },
33 edited: false,
34 deleted: false,
35 reactions: Vec::new(),
36 images: outgoing
37 .images
38 .iter()
39 .filter_map(|image| match image {
40 OutgoingImage::Remote(remote) => Some(remote.image_ref()),
41 OutgoingImage::Inline(_) => None,
42 })
43 .collect(),
44 local_images: outgoing
45 .images
46 .iter()
47 .filter_map(|image| match image {
48 OutgoingImage::Inline(inline) => Some(LocalImage {
49 image: inline.image.clone(),
50 size: inline.dimensions,
51 }),
52 OutgoingImage::Remote(_) => None,
53 })
54 .collect(),
55 adaptive_cards: Vec::new(),
56 link_preview: outgoing.link_preview.clone(),
57 files: outgoing
58 .files
59 .iter()
60 .map(|file| FileCard {
61 name: file.name.clone(),
62 kind: file.kind,
63 content_type: None,
64 size: Some(file.size),
65 open_url: file.reference.content_url.clone(),
66 })
67 .collect(),
68 reply_count: None,
69 new_marker: false,
70 reply_faces: Vec::new(),
71 last_reply_time: None,
72 open_thread: None,
73 is_reply: false,
74 delivery,
75 receipt: Receipt::Hidden,
76 own: true,
77 }
78}
crates/app/src/rows.rs +8 −0
@@ -96,11 +96,19 @@ pub enum Receipt {
96 96 Read,
97 97 }
98 98
99 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
100 pub enum ScheduledState {
101 Waiting,
102 DeliveryFailed,
103 ChangeFailed,
104 }
105
99 106 #[derive(Debug, Clone, PartialEq, Eq)]
100 107 pub enum Delivery {
101 108 Delivered,
102 109 Sending,
103 110 Failed(String),
111 Scheduled(ScheduledState),
104 112 }
105 113
106 114 /// An image of a message that is still being sent, shown from its local bytes.
@@ -96,11 +96,19 @@ pub enum Receipt {
96 Read,
96 Read,
97}
97}
98
98
99#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100pub enum ScheduledState {
101 Waiting,
102 DeliveryFailed,
103 ChangeFailed,
104}
105
99#[derive(Debug, Clone, PartialEq, Eq)]
106#[derive(Debug, Clone, PartialEq, Eq)]
100pub enum Delivery {
107pub enum Delivery {
101 Delivered,
108 Delivered,
102 Sending,
109 Sending,
103 Failed(String),
110 Failed(String),
111 Scheduled(ScheduledState),
104}
112}
105
113
106/// An image of a message that is still being sent, shown from its local bytes.
114/// An image of a message that is still being sent, shown from its local bytes.
crates/app/src/schedule_time.rs added +314 −0
@@ -0,0 +1,314 @@
1 use chrono::{
2 DateTime, Datelike, Duration, Local, NaiveDate, NaiveTime, TimeZone, Timelike, Weekday,
3 };
4
5 const LATER_TODAY_HOURS: i64 = 3;
6 const LATER_TODAY_CUTOFF_HOUR: u32 = 20;
7 const MORNING_HOUR: u32 = 8;
8 const SLOT_MINUTES: u32 = 30;
9 const TIME_STEP_MINUTES: i32 = 15;
10 const MAX_DAYS_AHEAD: i64 = 7;
11 pub const DAY_CHOICES: usize = 7;
12
13 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
14 pub enum PresetKind {
15 LaterToday,
16 TomorrowMorning,
17 MondayMorning,
18 }
19
20 #[derive(Debug, Clone, PartialEq, Eq)]
21 pub struct Preset {
22 pub kind: PresetKind,
23 pub label: &'static str,
24 pub time_label: String,
25 pub at: DateTime<Local>,
26 }
27
28 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
29 pub enum ScheduleError {
30 Past,
31 TooFar,
32 }
33
34 impl ScheduleError {
35 pub fn message(self) -> &'static str {
36 match self {
37 ScheduleError::Past => "That time has passed.",
38 ScheduleError::TooFar => "Teams schedules up to 7 days ahead.",
39 }
40 }
41 }
42
43 pub fn validate(at: DateTime<Local>, now: DateTime<Local>) -> Result<(), ScheduleError> {
44 if at <= now {
45 Err(ScheduleError::Past)
46 } else if at > now + Duration::days(MAX_DAYS_AHEAD) {
47 Err(ScheduleError::TooFar)
48 } else {
49 Ok(())
50 }
51 }
52
53 fn local_at(date: NaiveDate, time: NaiveTime) -> Option<DateTime<Local>> {
54 Local.from_local_datetime(&date.and_time(time)).earliest()
55 }
56
57 fn morning(date: NaiveDate) -> Option<DateTime<Local>> {
58 local_at(date, NaiveTime::from_hms_opt(MORNING_HOUR, 0, 0)?)
59 }
60
61 fn later_today(now: DateTime<Local>) -> Option<DateTime<Local>> {
62 let target = now + Duration::hours(LATER_TODAY_HOURS);
63 let past_slot = !target.minute().is_multiple_of(SLOT_MINUTES)
64 || target.second() != 0
65 || target.nanosecond() != 0;
66 let minutes_to_slot = if past_slot {
67 i64::from(SLOT_MINUTES - target.minute() % SLOT_MINUTES)
68 } else {
69 0
70 };
71 let rounded = (target + Duration::minutes(minutes_to_slot))
72 .with_second(0)?
73 .with_nanosecond(0)?;
74 let today = rounded.date_naive() == now.date_naive();
75 (today && rounded.hour() < LATER_TODAY_CUTOFF_HOUR).then_some(rounded)
76 }
77
78 fn next_monday(today: NaiveDate) -> NaiveDate {
79 let days_ahead = 7 - i64::from(today.weekday().num_days_from_monday());
80 today + Duration::days(days_ahead)
81 }
82
83 pub fn presets(now: DateTime<Local>) -> Vec<Preset> {
84 let today = now.date_naive();
85 let tomorrow = today + Duration::days(1);
86 let mut presets = Vec::new();
87 if let Some(at) = later_today(now) {
88 presets.push(Preset {
89 kind: PresetKind::LaterToday,
90 label: "Later today",
91 time_label: at.format("%H:%M").to_string(),
92 at,
93 });
94 }
95 let weekend_ahead = matches!(tomorrow.weekday(), Weekday::Sat | Weekday::Sun);
96 let monday = if tomorrow.weekday() == Weekday::Mon {
97 None
98 } else {
99 morning(next_monday(today))
100 };
101 let tomorrow_morning = morning(tomorrow).filter(|_| !weekend_ahead);
102 for (kind, label, at) in [
103 (
104 PresetKind::TomorrowMorning,
105 "Tomorrow morning",
106 tomorrow_morning,
107 ),
108 (PresetKind::MondayMorning, "Monday morning", monday),
109 ] {
110 if let Some(at) = at.filter(|at| validate(*at, now).is_ok()) {
111 presets.push(Preset {
112 kind,
113 label,
114 time_label: at.format("%a %H:%M").to_string(),
115 at,
116 });
117 }
118 }
119 presets
120 }
121
122 #[derive(Debug, Clone, PartialEq, Eq)]
123 pub struct DayChoice {
124 pub date: NaiveDate,
125 pub label: String,
126 }
127
128 pub fn day_choices(today: NaiveDate) -> Vec<DayChoice> {
129 (0..DAY_CHOICES as i64)
130 .map(|offset| {
131 let date = today + Duration::days(offset);
132 DayChoice {
133 date,
134 label: date.format("%a %-d %b").to_string(),
135 }
136 })
137 .collect()
138 }
139
140 pub fn parse_time(text: &str) -> Option<NaiveTime> {
141 let (hours, minutes) = text.trim().split_once(':')?;
142 let well_formed = (1..=2).contains(&hours.len())
143 && minutes.len() == 2
144 && hours
145 .chars()
146 .chain(minutes.chars())
147 .all(|digit| digit.is_ascii_digit());
148 if !well_formed {
149 return None;
150 }
151 NaiveTime::from_hms_opt(hours.parse().ok()?, minutes.parse().ok()?, 0)
152 }
153
154 pub fn custom_time(day: NaiveDate, text: &str) -> Option<DateTime<Local>> {
155 local_at(day, parse_time(text)?)
156 }
157
158 pub fn default_custom_time(now: DateTime<Local>) -> NaiveTime {
159 let step = TIME_STEP_MINUTES as u32;
160 let minutes = now.hour() * 60 + now.minute();
161 let next = (minutes / step + 1) * step;
162 NaiveTime::from_hms_opt(next / 60 % 24, next % 60, 0).unwrap_or_default()
163 }
164
165 pub fn step_time(time: NaiveTime, steps: i32) -> NaiveTime {
166 let minutes = (time.hour() * 60 + time.minute()) as i32 + steps * TIME_STEP_MINUTES;
167 let wrapped = minutes.rem_euclid(24 * 60) as u32;
168 NaiveTime::from_hms_opt(wrapped / 60, wrapped % 60, 0).unwrap_or_default()
169 }
170
171 pub fn format_time(time: NaiveTime) -> String {
172 time.format("%H:%M").to_string()
173 }
174
175 pub fn describe(at: DateTime<Local>, now: DateTime<Local>) -> String {
176 let days_ahead = (at.date_naive() - now.date_naive()).num_days();
177 match days_ahead {
178 0 => at.format("today %H:%M").to_string(),
179 1..=6 => at.format("%a %H:%M").to_string(),
180 _ => at.format("%a %-d %b %H:%M").to_string(),
181 }
182 }
183
184 #[cfg(test)]
185 mod tests {
186 use super::*;
187
188 fn at(day: u32, hour: u32, minute: u32) -> DateTime<Local> {
189 Local
190 .with_ymd_and_hms(2026, 10, day, hour, minute, 0)
191 .unwrap()
192 }
193
194 fn kinds(now: DateTime<Local>) -> Vec<PresetKind> {
195 presets(now).iter().map(|preset| preset.kind).collect()
196 }
197
198 #[test]
199 fn later_today_is_three_hours_rounded_up_to_the_half_hour() {
200 let preset = &presets(at(6, 10, 10))[0];
201 assert_eq!(preset.kind, PresetKind::LaterToday);
202 assert_eq!(preset.at, at(6, 13, 30));
203 assert_eq!(preset.time_label, "13:30");
204 assert_eq!(presets(at(6, 10, 31))[0].at, at(6, 14, 0));
205 assert_eq!(presets(at(6, 10, 30))[0].at, at(6, 13, 30));
206 }
207
208 #[test]
209 fn later_today_needs_to_stay_today_and_before_eight_pm() {
210 assert_eq!(presets(at(6, 16, 20))[0].at, at(6, 19, 30));
211 assert_ne!(kinds(at(6, 16, 31))[0], PresetKind::LaterToday);
212 assert_ne!(kinds(at(6, 22, 0))[0], PresetKind::LaterToday);
213 }
214
215 #[test]
216 fn midweek_offers_tomorrow_and_next_monday() {
217 let found = presets(at(8, 9, 0));
218 let labels: Vec<_> = found.iter().map(|preset| preset.label).collect();
219 assert_eq!(
220 labels,
221 ["Later today", "Tomorrow morning", "Monday morning"]
222 );
223 assert_eq!(found[1].time_label, "Fri 08:00");
224 assert_eq!(found[1].at, at(9, 8, 0));
225 assert_eq!(found[2].at, at(12, 8, 0));
226 assert_eq!(found[2].time_label, "Mon 08:00");
227 }
228
229 #[test]
230 fn friday_and_saturday_replace_tomorrow_with_monday() {
231 for day in [9, 10] {
232 let found = presets(at(day, 21, 0));
233 assert_eq!(found.len(), 1);
234 assert_eq!(found[0].kind, PresetKind::MondayMorning);
235 assert_eq!(found[0].at, at(12, 8, 0));
236 }
237 }
238
239 #[test]
240 fn sunday_shows_tomorrow_only_because_monday_would_duplicate_it() {
241 let found = presets(at(11, 21, 0));
242 assert_eq!(found.len(), 1);
243 assert_eq!(found[0].kind, PresetKind::TomorrowMorning);
244 assert_eq!(found[0].time_label, "Mon 08:00");
245 }
246
247 #[test]
248 fn next_monday_is_hidden_while_it_is_more_than_seven_days_away() {
249 assert_eq!(
250 kinds(at(5, 7, 0)),
251 [PresetKind::LaterToday, PresetKind::TomorrowMorning]
252 );
253 assert_eq!(
254 kinds(at(5, 21, 0)),
255 [PresetKind::TomorrowMorning, PresetKind::MondayMorning]
256 );
257 }
258
259 #[test]
260 fn validation_blocks_the_past_and_more_than_seven_days() {
261 let now = at(6, 10, 0);
262 assert_eq!(validate(at(6, 9, 59), now), Err(ScheduleError::Past));
263 assert_eq!(validate(now, now), Err(ScheduleError::Past));
264 assert_eq!(validate(at(6, 10, 1), now), Ok(()));
265 assert_eq!(validate(at(13, 10, 0), now), Ok(()));
266 assert_eq!(validate(at(13, 10, 1), now), Err(ScheduleError::TooFar));
267 assert_eq!(ScheduleError::Past.message(), "That time has passed.");
268 assert_eq!(
269 ScheduleError::TooFar.message(),
270 "Teams schedules up to 7 days ahead."
271 );
272 }
273
274 #[test]
275 fn day_choices_run_from_today_for_seven_days() {
276 let choices = day_choices(at(9, 12, 0).date_naive());
277 assert_eq!(choices.len(), 7);
278 assert_eq!(choices[0].label, "Fri 9 Oct");
279 assert_eq!(choices[6].label, "Thu 15 Oct");
280 }
281
282 #[test]
283 fn typed_times_accept_any_minute_and_reject_garbage() {
284 let day = at(9, 0, 0).date_naive();
285 assert_eq!(custom_time(day, "9:07"), Some(at(9, 9, 7)));
286 assert_eq!(custom_time(day, " 09:45 "), Some(at(9, 9, 45)));
287 assert_eq!(custom_time(day, "23:59"), Some(at(9, 23, 59)));
288 for text in ["", "9", "24:00", "9:60", "9:5", "ab:cd", "9:30pm", "123:00"] {
289 assert_eq!(parse_time(text), None, "{text}");
290 }
291 }
292
293 #[test]
294 fn the_default_custom_time_is_the_next_quarter_hour() {
295 assert_eq!(format_time(default_custom_time(at(9, 10, 0))), "10:15");
296 assert_eq!(format_time(default_custom_time(at(9, 10, 14))), "10:15");
297 assert_eq!(format_time(default_custom_time(at(9, 23, 50))), "00:00");
298 }
299
300 #[test]
301 fn stepping_moves_by_quarter_hours_and_wraps() {
302 let time = NaiveTime::from_hms_opt(23, 55, 0).unwrap();
303 assert_eq!(format_time(step_time(time, 1)), "00:10");
304 assert_eq!(format_time(step_time(time, -2)), "23:25");
305 }
306
307 #[test]
308 fn describing_a_time_names_today_or_the_weekday() {
309 let now = at(9, 10, 0);
310 assert_eq!(describe(at(9, 15, 30), now), "today 15:30");
311 assert_eq!(describe(at(12, 8, 15), now), "Mon 08:15");
312 assert_eq!(describe(at(16, 8, 15), now), "Fri 16 Oct 08:15");
313 }
314 }
@@ -0,0 +1,314 @@
1use chrono::{
2 DateTime, Datelike, Duration, Local, NaiveDate, NaiveTime, TimeZone, Timelike, Weekday,
3};
4
5const LATER_TODAY_HOURS: i64 = 3;
6const LATER_TODAY_CUTOFF_HOUR: u32 = 20;
7const MORNING_HOUR: u32 = 8;
8const SLOT_MINUTES: u32 = 30;
9const TIME_STEP_MINUTES: i32 = 15;
10const MAX_DAYS_AHEAD: i64 = 7;
11pub const DAY_CHOICES: usize = 7;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum PresetKind {
15 LaterToday,
16 TomorrowMorning,
17 MondayMorning,
18}
19
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct Preset {
22 pub kind: PresetKind,
23 pub label: &'static str,
24 pub time_label: String,
25 pub at: DateTime<Local>,
26}
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum ScheduleError {
30 Past,
31 TooFar,
32}
33
34impl ScheduleError {
35 pub fn message(self) -> &'static str {
36 match self {
37 ScheduleError::Past => "That time has passed.",
38 ScheduleError::TooFar => "Teams schedules up to 7 days ahead.",
39 }
40 }
41}
42
43pub fn validate(at: DateTime<Local>, now: DateTime<Local>) -> Result<(), ScheduleError> {
44 if at <= now {
45 Err(ScheduleError::Past)
46 } else if at > now + Duration::days(MAX_DAYS_AHEAD) {
47 Err(ScheduleError::TooFar)
48 } else {
49 Ok(())
50 }
51}
52
53fn local_at(date: NaiveDate, time: NaiveTime) -> Option<DateTime<Local>> {
54 Local.from_local_datetime(&date.and_time(time)).earliest()
55}
56
57fn morning(date: NaiveDate) -> Option<DateTime<Local>> {
58 local_at(date, NaiveTime::from_hms_opt(MORNING_HOUR, 0, 0)?)
59}
60
61fn later_today(now: DateTime<Local>) -> Option<DateTime<Local>> {
62 let target = now + Duration::hours(LATER_TODAY_HOURS);
63 let past_slot = !target.minute().is_multiple_of(SLOT_MINUTES)
64 || target.second() != 0
65 || target.nanosecond() != 0;
66 let minutes_to_slot = if past_slot {
67 i64::from(SLOT_MINUTES - target.minute() % SLOT_MINUTES)
68 } else {
69 0
70 };
71 let rounded = (target + Duration::minutes(minutes_to_slot))
72 .with_second(0)?
73 .with_nanosecond(0)?;
74 let today = rounded.date_naive() == now.date_naive();
75 (today && rounded.hour() < LATER_TODAY_CUTOFF_HOUR).then_some(rounded)
76}
77
78fn next_monday(today: NaiveDate) -> NaiveDate {
79 let days_ahead = 7 - i64::from(today.weekday().num_days_from_monday());
80 today + Duration::days(days_ahead)
81}
82
83pub fn presets(now: DateTime<Local>) -> Vec<Preset> {
84 let today = now.date_naive();
85 let tomorrow = today + Duration::days(1);
86 let mut presets = Vec::new();
87 if let Some(at) = later_today(now) {
88 presets.push(Preset {
89 kind: PresetKind::LaterToday,
90 label: "Later today",
91 time_label: at.format("%H:%M").to_string(),
92 at,
93 });
94 }
95 let weekend_ahead = matches!(tomorrow.weekday(), Weekday::Sat | Weekday::Sun);
96 let monday = if tomorrow.weekday() == Weekday::Mon {
97 None
98 } else {
99 morning(next_monday(today))
100 };
101 let tomorrow_morning = morning(tomorrow).filter(|_| !weekend_ahead);
102 for (kind, label, at) in [
103 (
104 PresetKind::TomorrowMorning,
105 "Tomorrow morning",
106 tomorrow_morning,
107 ),
108 (PresetKind::MondayMorning, "Monday morning", monday),
109 ] {
110 if let Some(at) = at.filter(|at| validate(*at, now).is_ok()) {
111 presets.push(Preset {
112 kind,
113 label,
114 time_label: at.format("%a %H:%M").to_string(),
115 at,
116 });
117 }
118 }
119 presets
120}
121
122#[derive(Debug, Clone, PartialEq, Eq)]
123pub struct DayChoice {
124 pub date: NaiveDate,
125 pub label: String,
126}
127
128pub fn day_choices(today: NaiveDate) -> Vec<DayChoice> {
129 (0..DAY_CHOICES as i64)
130 .map(|offset| {
131 let date = today + Duration::days(offset);
132 DayChoice {
133 date,
134 label: date.format("%a %-d %b").to_string(),
135 }
136 })
137 .collect()
138}
139
140pub fn parse_time(text: &str) -> Option<NaiveTime> {
141 let (hours, minutes) = text.trim().split_once(':')?;
142 let well_formed = (1..=2).contains(&hours.len())
143 && minutes.len() == 2
144 && hours
145 .chars()
146 .chain(minutes.chars())
147 .all(|digit| digit.is_ascii_digit());
148 if !well_formed {
149 return None;
150 }
151 NaiveTime::from_hms_opt(hours.parse().ok()?, minutes.parse().ok()?, 0)
152}
153
154pub fn custom_time(day: NaiveDate, text: &str) -> Option<DateTime<Local>> {
155 local_at(day, parse_time(text)?)
156}
157
158pub fn default_custom_time(now: DateTime<Local>) -> NaiveTime {
159 let step = TIME_STEP_MINUTES as u32;
160 let minutes = now.hour() * 60 + now.minute();
161 let next = (minutes / step + 1) * step;
162 NaiveTime::from_hms_opt(next / 60 % 24, next % 60, 0).unwrap_or_default()
163}
164
165pub fn step_time(time: NaiveTime, steps: i32) -> NaiveTime {
166 let minutes = (time.hour() * 60 + time.minute()) as i32 + steps * TIME_STEP_MINUTES;
167 let wrapped = minutes.rem_euclid(24 * 60) as u32;
168 NaiveTime::from_hms_opt(wrapped / 60, wrapped % 60, 0).unwrap_or_default()
169}
170
171pub fn format_time(time: NaiveTime) -> String {
172 time.format("%H:%M").to_string()
173}
174
175pub fn describe(at: DateTime<Local>, now: DateTime<Local>) -> String {
176 let days_ahead = (at.date_naive() - now.date_naive()).num_days();
177 match days_ahead {
178 0 => at.format("today %H:%M").to_string(),
179 1..=6 => at.format("%a %H:%M").to_string(),
180 _ => at.format("%a %-d %b %H:%M").to_string(),
181 }
182}
183
184#[cfg(test)]
185mod tests {
186 use super::*;
187
188 fn at(day: u32, hour: u32, minute: u32) -> DateTime<Local> {
189 Local
190 .with_ymd_and_hms(2026, 10, day, hour, minute, 0)
191 .unwrap()
192 }
193
194 fn kinds(now: DateTime<Local>) -> Vec<PresetKind> {
195 presets(now).iter().map(|preset| preset.kind).collect()
196 }
197
198 #[test]
199 fn later_today_is_three_hours_rounded_up_to_the_half_hour() {
200 let preset = &presets(at(6, 10, 10))[0];
201 assert_eq!(preset.kind, PresetKind::LaterToday);
202 assert_eq!(preset.at, at(6, 13, 30));
203 assert_eq!(preset.time_label, "13:30");
204 assert_eq!(presets(at(6, 10, 31))[0].at, at(6, 14, 0));
205 assert_eq!(presets(at(6, 10, 30))[0].at, at(6, 13, 30));
206 }
207
208 #[test]
209 fn later_today_needs_to_stay_today_and_before_eight_pm() {
210 assert_eq!(presets(at(6, 16, 20))[0].at, at(6, 19, 30));
211 assert_ne!(kinds(at(6, 16, 31))[0], PresetKind::LaterToday);
212 assert_ne!(kinds(at(6, 22, 0))[0], PresetKind::LaterToday);
213 }
214
215 #[test]
216 fn midweek_offers_tomorrow_and_next_monday() {
217 let found = presets(at(8, 9, 0));
218 let labels: Vec<_> = found.iter().map(|preset| preset.label).collect();
219 assert_eq!(
220 labels,
221 ["Later today", "Tomorrow morning", "Monday morning"]
222 );
223 assert_eq!(found[1].time_label, "Fri 08:00");
224 assert_eq!(found[1].at, at(9, 8, 0));
225 assert_eq!(found[2].at, at(12, 8, 0));
226 assert_eq!(found[2].time_label, "Mon 08:00");
227 }
228
229 #[test]
230 fn friday_and_saturday_replace_tomorrow_with_monday() {
231 for day in [9, 10] {
232 let found = presets(at(day, 21, 0));
233 assert_eq!(found.len(), 1);
234 assert_eq!(found[0].kind, PresetKind::MondayMorning);
235 assert_eq!(found[0].at, at(12, 8, 0));
236 }
237 }
238
239 #[test]
240 fn sunday_shows_tomorrow_only_because_monday_would_duplicate_it() {
241 let found = presets(at(11, 21, 0));
242 assert_eq!(found.len(), 1);
243 assert_eq!(found[0].kind, PresetKind::TomorrowMorning);
244 assert_eq!(found[0].time_label, "Mon 08:00");
245 }
246
247 #[test]
248 fn next_monday_is_hidden_while_it_is_more_than_seven_days_away() {
249 assert_eq!(
250 kinds(at(5, 7, 0)),
251 [PresetKind::LaterToday, PresetKind::TomorrowMorning]
252 );
253 assert_eq!(
254 kinds(at(5, 21, 0)),
255 [PresetKind::TomorrowMorning, PresetKind::MondayMorning]
256 );
257 }
258
259 #[test]
260 fn validation_blocks_the_past_and_more_than_seven_days() {
261 let now = at(6, 10, 0);
262 assert_eq!(validate(at(6, 9, 59), now), Err(ScheduleError::Past));
263 assert_eq!(validate(now, now), Err(ScheduleError::Past));
264 assert_eq!(validate(at(6, 10, 1), now), Ok(()));
265 assert_eq!(validate(at(13, 10, 0), now), Ok(()));
266 assert_eq!(validate(at(13, 10, 1), now), Err(ScheduleError::TooFar));
267 assert_eq!(ScheduleError::Past.message(), "That time has passed.");
268 assert_eq!(
269 ScheduleError::TooFar.message(),
270 "Teams schedules up to 7 days ahead."
271 );
272 }
273
274 #[test]
275 fn day_choices_run_from_today_for_seven_days() {
276 let choices = day_choices(at(9, 12, 0).date_naive());
277 assert_eq!(choices.len(), 7);
278 assert_eq!(choices[0].label, "Fri 9 Oct");
279 assert_eq!(choices[6].label, "Thu 15 Oct");
280 }
281
282 #[test]
283 fn typed_times_accept_any_minute_and_reject_garbage() {
284 let day = at(9, 0, 0).date_naive();
285 assert_eq!(custom_time(day, "9:07"), Some(at(9, 9, 7)));
286 assert_eq!(custom_time(day, " 09:45 "), Some(at(9, 9, 45)));
287 assert_eq!(custom_time(day, "23:59"), Some(at(9, 23, 59)));
288 for text in ["", "9", "24:00", "9:60", "9:5", "ab:cd", "9:30pm", "123:00"] {
289 assert_eq!(parse_time(text), None, "{text}");
290 }
291 }
292
293 #[test]
294 fn the_default_custom_time_is_the_next_quarter_hour() {
295 assert_eq!(format_time(default_custom_time(at(9, 10, 0))), "10:15");
296 assert_eq!(format_time(default_custom_time(at(9, 10, 14))), "10:15");
297 assert_eq!(format_time(default_custom_time(at(9, 23, 50))), "00:00");
298 }
299
300 #[test]
301 fn stepping_moves_by_quarter_hours_and_wraps() {
302 let time = NaiveTime::from_hms_opt(23, 55, 0).unwrap();
303 assert_eq!(format_time(step_time(time, 1)), "00:10");
304 assert_eq!(format_time(step_time(time, -2)), "23:25");
305 }
306
307 #[test]
308 fn describing_a_time_names_today_or_the_weekday() {
309 let now = at(9, 10, 0);
310 assert_eq!(describe(at(9, 15, 30), now), "today 15:30");
311 assert_eq!(describe(at(12, 8, 15), now), "Mon 08:15");
312 assert_eq!(describe(at(16, 8, 15), now), "Fri 16 Oct 08:15");
313 }
314}
crates/app/src/scheduled.rs added +241 −0
@@ -0,0 +1,241 @@
1 use std::collections::HashSet;
2 use std::time::Duration;
3
4 use chrono::{DateTime, Utc};
5 use gpui_kit::Context;
6 use teams_core::ScheduledDraft;
7
8 use crate::app_state::{AppEvent, AppState};
9 use crate::runtime;
10
11 const REFRESH_INTERVAL: Duration = Duration::from_secs(60);
12 const DELIVERY_SETTLE: Duration = Duration::from_secs(3);
13 const THREAD_SUFFIX: &str = ";messageid=";
14
15 pub fn conversation_of(inner_thread_id: &str) -> &str {
16 inner_thread_id
17 .split_once(THREAD_SUFFIX)
18 .map_or(inner_thread_id, |(conversation_id, _)| conversation_id)
19 }
20
21 pub fn thread_root_of(inner_thread_id: &str) -> Option<&str> {
22 inner_thread_id
23 .split_once(THREAD_SUFFIX)
24 .map(|(_, root_id)| root_id)
25 }
26
27 pub fn keep_unconfirmed(
28 mut incoming: Vec<ScheduledDraft>,
29 known: &[ScheduledDraft],
30 ) -> Vec<ScheduledDraft> {
31 let unconfirmed: Vec<ScheduledDraft> = known
32 .iter()
33 .filter(|draft| {
34 draft.id.is_empty()
35 && !incoming
36 .iter()
37 .any(|found| found.client_message_id == draft.client_message_id)
38 })
39 .cloned()
40 .collect();
41 incoming.extend(unconfirmed);
42 incoming
43 }
44
45 fn is_due(draft: &ScheduledDraft, now: DateTime<Utc>) -> bool {
46 draft.delivery_state.is_none() && draft.send_at <= now
47 }
48
49 pub fn pending_drafts(drafts: Vec<ScheduledDraft>, now: DateTime<Utc>) -> Vec<ScheduledDraft> {
50 drafts
51 .into_iter()
52 .filter(|draft| !is_due(draft, now))
53 .collect()
54 }
55
56 pub fn due_conversations(drafts: &[ScheduledDraft], now: DateTime<Utc>) -> Vec<String> {
57 let mut seen = HashSet::new();
58 drafts
59 .iter()
60 .filter(|draft| is_due(draft, now))
61 .map(|draft| conversation_of(&draft.inner_thread_id))
62 .filter(|conversation_id| seen.insert(*conversation_id))
63 .map(str::to_owned)
64 .collect()
65 }
66
67 impl AppState {
68 pub fn refresh_scheduled(&mut self, cx: &mut Context<Self>) {
69 if self.mode.demo {
70 return;
71 }
72 let Some(engine) = self.engine.clone() else {
73 return;
74 };
75 let receiver = runtime::spawn(async move { engine.scheduled_messages().await });
76 cx.spawn(async move |this, cx| {
77 if let Ok(Ok(drafts)) = receiver.await {
78 this.update(cx, |state, cx| state.apply_scheduled(drafts, cx))
79 .ok();
80 }
81 })
82 .detach();
83 }
84
85 pub fn apply_scheduled(&mut self, drafts: Vec<ScheduledDraft>, cx: &mut Context<Self>) {
86 let now = Utc::now();
87 let delivered = due_conversations(&self.scheduled, now);
88 self.scheduled = pending_drafts(keep_unconfirmed(drafts, &self.scheduled), now);
89 self.fetch_delivered(delivered);
90 self.poll_scheduled(cx);
91 cx.emit(AppEvent::Scheduled);
92 cx.notify();
93 }
94
95 pub fn scheduled_upserted(&mut self, draft: ScheduledDraft, cx: &mut Context<Self>) {
96 let mut drafts = std::mem::take(&mut self.scheduled);
97 let unconfirmed = draft.id.is_empty();
98 let same = |known: &ScheduledDraft| {
99 if draft.id.is_empty() || known.id.is_empty() {
100 known.client_message_id == draft.client_message_id
101 } else {
102 known.id == draft.id
103 }
104 };
105 match drafts.iter_mut().find(|known| same(known)) {
106 Some(known) => *known = draft,
107 None => drafts.push(draft),
108 }
109 self.apply_scheduled(drafts, cx);
110 if unconfirmed {
111 self.refresh_scheduled(cx);
112 }
113 }
114
115 pub fn scheduled_removed(&mut self, draft_id: &str, cx: &mut Context<Self>) {
116 let mut drafts = std::mem::take(&mut self.scheduled);
117 drafts.retain(|draft| draft.id != draft_id);
118 self.apply_scheduled(drafts, cx);
119 }
120
121 fn fetch_delivered(&self, conversation_ids: Vec<String>) {
122 let Some(engine) = self.engine.clone().filter(|_| !self.mode.demo) else {
123 return;
124 };
125 for conversation_id in conversation_ids {
126 let engine = engine.clone();
127 runtime::handle().spawn(async move {
128 tokio::time::sleep(DELIVERY_SETTLE).await;
129 let _ = engine.fetch_newer(&conversation_id).await;
130 });
131 }
132 }
133
134 fn poll_scheduled(&mut self, cx: &mut Context<Self>) {
135 if self.scheduled.is_empty() || self.scheduled_polling {
136 return;
137 }
138 self.scheduled_polling = true;
139 cx.spawn(async move |this, cx| {
140 loop {
141 cx.background_executor().timer(REFRESH_INTERVAL).await;
142 let keep_going = this.update(cx, |state, cx| state.tick_scheduled(cx));
143 if !keep_going.unwrap_or(false) {
144 break;
145 }
146 }
147 })
148 .detach();
149 }
150
151 fn tick_scheduled(&mut self, cx: &mut Context<Self>) -> bool {
152 let keep_going = !self.scheduled.is_empty();
153 self.scheduled_polling = keep_going;
154 let current = self.scheduled.clone();
155 self.apply_scheduled(current, cx);
156 self.refresh_scheduled(cx);
157 keep_going
158 }
159 }
160
161 #[cfg(test)]
162 mod tests {
163 use chrono::{Duration, TimeZone};
164
165 use super::*;
166
167 fn now() -> DateTime<Utc> {
168 Utc.with_ymd_and_hms(2026, 10, 9, 10, 0, 0).unwrap()
169 }
170
171 fn draft(id: &str, thread: &str, minutes_ahead: i64, failed: bool) -> ScheduledDraft {
172 ScheduledDraft {
173 id: id.to_owned(),
174 client_message_id: id.to_owned(),
175 inner_thread_id: thread.to_owned(),
176 send_at: now() + Duration::minutes(minutes_ahead),
177 html: String::new(),
178 delivery_state: failed.then(|| "failed".to_owned()),
179 }
180 }
181
182 #[test]
183 fn a_thread_draft_belongs_to_its_channel() {
184 assert_eq!(conversation_of("19:chat@thread.v2"), "19:chat@thread.v2");
185 assert_eq!(
186 conversation_of("19:channel@thread.tacv2;messageid=1791"),
187 "19:channel@thread.tacv2"
188 );
189 }
190
191 #[test]
192 fn a_draft_without_an_id_stays_until_the_server_list_shows_it() {
193 let mut stub = draft("", "chat", 5, false);
194 stub.client_message_id = "client-1".to_owned();
195 let known = [stub.clone()];
196 let other = draft("other", "chat", 9, false);
197 assert_eq!(
198 keep_unconfirmed(vec![other.clone()], &known),
199 [other.clone(), stub]
200 );
201 let mut confirmed = draft("d1", "chat", 5, false);
202 confirmed.client_message_id = "client-1".to_owned();
203 assert_eq!(
204 keep_unconfirmed(vec![confirmed.clone()], &known),
205 [confirmed]
206 );
207 }
208
209 #[test]
210 fn a_thread_draft_names_its_root() {
211 assert_eq!(
212 thread_root_of("19:c@thread.tacv2;messageid=1791"),
213 Some("1791")
214 );
215 assert_eq!(thread_root_of("19:chat@thread.v2"), None);
216 }
217
218 #[test]
219 fn due_drafts_leave_the_list_and_failed_ones_stay() {
220 let drafts = vec![
221 draft("future", "a", 5, false),
222 draft("due", "a", -1, false),
223 draft("failed", "a", -1, true),
224 ];
225 let kept = pending_drafts(drafts, now());
226 let ids: Vec<_> = kept.iter().map(|draft| draft.id.as_str()).collect();
227 assert_eq!(ids, ["future", "failed"]);
228 }
229
230 #[test]
231 fn each_conversation_with_a_due_draft_is_fetched_once() {
232 let drafts = [
233 draft("a", "chat", -1, false),
234 draft("b", "chat", -2, false),
235 draft("c", "chan;messageid=m1", 0, false),
236 draft("d", "other", 9, false),
237 draft("e", "stuck", -1, true),
238 ];
239 assert_eq!(due_conversations(&drafts, now()), ["chat", "chan"]);
240 }
241 }
@@ -0,0 +1,241 @@
1use std::collections::HashSet;
2use std::time::Duration;
3
4use chrono::{DateTime, Utc};
5use gpui_kit::Context;
6use teams_core::ScheduledDraft;
7
8use crate::app_state::{AppEvent, AppState};
9use crate::runtime;
10
11const REFRESH_INTERVAL: Duration = Duration::from_secs(60);
12const DELIVERY_SETTLE: Duration = Duration::from_secs(3);
13const THREAD_SUFFIX: &str = ";messageid=";
14
15pub fn conversation_of(inner_thread_id: &str) -> &str {
16 inner_thread_id
17 .split_once(THREAD_SUFFIX)
18 .map_or(inner_thread_id, |(conversation_id, _)| conversation_id)
19}
20
21pub fn thread_root_of(inner_thread_id: &str) -> Option<&str> {
22 inner_thread_id
23 .split_once(THREAD_SUFFIX)
24 .map(|(_, root_id)| root_id)
25}
26
27pub fn keep_unconfirmed(
28 mut incoming: Vec<ScheduledDraft>,
29 known: &[ScheduledDraft],
30) -> Vec<ScheduledDraft> {
31 let unconfirmed: Vec<ScheduledDraft> = known
32 .iter()
33 .filter(|draft| {
34 draft.id.is_empty()
35 && !incoming
36 .iter()
37 .any(|found| found.client_message_id == draft.client_message_id)
38 })
39 .cloned()
40 .collect();
41 incoming.extend(unconfirmed);
42 incoming
43}
44
45fn is_due(draft: &ScheduledDraft, now: DateTime<Utc>) -> bool {
46 draft.delivery_state.is_none() && draft.send_at <= now
47}
48
49pub fn pending_drafts(drafts: Vec<ScheduledDraft>, now: DateTime<Utc>) -> Vec<ScheduledDraft> {
50 drafts
51 .into_iter()
52 .filter(|draft| !is_due(draft, now))
53 .collect()
54}
55
56pub fn due_conversations(drafts: &[ScheduledDraft], now: DateTime<Utc>) -> Vec<String> {
57 let mut seen = HashSet::new();
58 drafts
59 .iter()
60 .filter(|draft| is_due(draft, now))
61 .map(|draft| conversation_of(&draft.inner_thread_id))
62 .filter(|conversation_id| seen.insert(*conversation_id))
63 .map(str::to_owned)
64 .collect()
65}
66
67impl AppState {
68 pub fn refresh_scheduled(&mut self, cx: &mut Context<Self>) {
69 if self.mode.demo {
70 return;
71 }
72 let Some(engine) = self.engine.clone() else {
73 return;
74 };
75 let receiver = runtime::spawn(async move { engine.scheduled_messages().await });
76 cx.spawn(async move |this, cx| {
77 if let Ok(Ok(drafts)) = receiver.await {
78 this.update(cx, |state, cx| state.apply_scheduled(drafts, cx))
79 .ok();
80 }
81 })
82 .detach();
83 }
84
85 pub fn apply_scheduled(&mut self, drafts: Vec<ScheduledDraft>, cx: &mut Context<Self>) {
86 let now = Utc::now();
87 let delivered = due_conversations(&self.scheduled, now);
88 self.scheduled = pending_drafts(keep_unconfirmed(drafts, &self.scheduled), now);
89 self.fetch_delivered(delivered);
90 self.poll_scheduled(cx);
91 cx.emit(AppEvent::Scheduled);
92 cx.notify();
93 }
94
95 pub fn scheduled_upserted(&mut self, draft: ScheduledDraft, cx: &mut Context<Self>) {
96 let mut drafts = std::mem::take(&mut self.scheduled);
97 let unconfirmed = draft.id.is_empty();
98 let same = |known: &ScheduledDraft| {
99 if draft.id.is_empty() || known.id.is_empty() {
100 known.client_message_id == draft.client_message_id
101 } else {
102 known.id == draft.id
103 }
104 };
105 match drafts.iter_mut().find(|known| same(known)) {
106 Some(known) => *known = draft,
107 None => drafts.push(draft),
108 }
109 self.apply_scheduled(drafts, cx);
110 if unconfirmed {
111 self.refresh_scheduled(cx);
112 }
113 }
114
115 pub fn scheduled_removed(&mut self, draft_id: &str, cx: &mut Context<Self>) {
116 let mut drafts = std::mem::take(&mut self.scheduled);
117 drafts.retain(|draft| draft.id != draft_id);
118 self.apply_scheduled(drafts, cx);
119 }
120
121 fn fetch_delivered(&self, conversation_ids: Vec<String>) {
122 let Some(engine) = self.engine.clone().filter(|_| !self.mode.demo) else {
123 return;
124 };
125 for conversation_id in conversation_ids {
126 let engine = engine.clone();
127 runtime::handle().spawn(async move {
128 tokio::time::sleep(DELIVERY_SETTLE).await;
129 let _ = engine.fetch_newer(&conversation_id).await;
130 });
131 }
132 }
133
134 fn poll_scheduled(&mut self, cx: &mut Context<Self>) {
135 if self.scheduled.is_empty() || self.scheduled_polling {
136 return;
137 }
138 self.scheduled_polling = true;
139 cx.spawn(async move |this, cx| {
140 loop {
141 cx.background_executor().timer(REFRESH_INTERVAL).await;
142 let keep_going = this.update(cx, |state, cx| state.tick_scheduled(cx));
143 if !keep_going.unwrap_or(false) {
144 break;
145 }
146 }
147 })
148 .detach();
149 }
150
151 fn tick_scheduled(&mut self, cx: &mut Context<Self>) -> bool {
152 let keep_going = !self.scheduled.is_empty();
153 self.scheduled_polling = keep_going;
154 let current = self.scheduled.clone();
155 self.apply_scheduled(current, cx);
156 self.refresh_scheduled(cx);
157 keep_going
158 }
159}
160
161#[cfg(test)]
162mod tests {
163 use chrono::{Duration, TimeZone};
164
165 use super::*;
166
167 fn now() -> DateTime<Utc> {
168 Utc.with_ymd_and_hms(2026, 10, 9, 10, 0, 0).unwrap()
169 }
170
171 fn draft(id: &str, thread: &str, minutes_ahead: i64, failed: bool) -> ScheduledDraft {
172 ScheduledDraft {
173 id: id.to_owned(),
174 client_message_id: id.to_owned(),
175 inner_thread_id: thread.to_owned(),
176 send_at: now() + Duration::minutes(minutes_ahead),
177 html: String::new(),
178 delivery_state: failed.then(|| "failed".to_owned()),
179 }
180 }
181
182 #[test]
183 fn a_thread_draft_belongs_to_its_channel() {
184 assert_eq!(conversation_of("19:chat@thread.v2"), "19:chat@thread.v2");
185 assert_eq!(
186 conversation_of("19:channel@thread.tacv2;messageid=1791"),
187 "19:channel@thread.tacv2"
188 );
189 }
190
191 #[test]
192 fn a_draft_without_an_id_stays_until_the_server_list_shows_it() {
193 let mut stub = draft("", "chat", 5, false);
194 stub.client_message_id = "client-1".to_owned();
195 let known = [stub.clone()];
196 let other = draft("other", "chat", 9, false);
197 assert_eq!(
198 keep_unconfirmed(vec![other.clone()], &known),
199 [other.clone(), stub]
200 );
201 let mut confirmed = draft("d1", "chat", 5, false);
202 confirmed.client_message_id = "client-1".to_owned();
203 assert_eq!(
204 keep_unconfirmed(vec![confirmed.clone()], &known),
205 [confirmed]
206 );
207 }
208
209 #[test]
210 fn a_thread_draft_names_its_root() {
211 assert_eq!(
212 thread_root_of("19:c@thread.tacv2;messageid=1791"),
213 Some("1791")
214 );
215 assert_eq!(thread_root_of("19:chat@thread.v2"), None);
216 }
217
218 #[test]
219 fn due_drafts_leave_the_list_and_failed_ones_stay() {
220 let drafts = vec![
221 draft("future", "a", 5, false),
222 draft("due", "a", -1, false),
223 draft("failed", "a", -1, true),
224 ];
225 let kept = pending_drafts(drafts, now());
226 let ids: Vec<_> = kept.iter().map(|draft| draft.id.as_str()).collect();
227 assert_eq!(ids, ["future", "failed"]);
228 }
229
230 #[test]
231 fn each_conversation_with_a_due_draft_is_fetched_once() {
232 let drafts = [
233 draft("a", "chat", -1, false),
234 draft("b", "chat", -2, false),
235 draft("c", "chan;messageid=m1", 0, false),
236 draft("d", "other", 9, false),
237 draft("e", "stuck", -1, true),
238 ];
239 assert_eq!(due_conversations(&drafts, now()), ["chat", "chan"]);
240 }
241}
crates/app/src/scheduled_rows.rs added +170 −0
@@ -0,0 +1,170 @@
1 use chrono::{DateTime, Local, Utc};
2 use teams_core::{Draft, ScheduledDraft, html_to_spans};
3
4 use crate::pending_rows::pending_row;
5 use crate::rows::{Delivery, MessageRow, ScheduledState};
6 use crate::schedule_time::describe;
7 use crate::views::composer::Outgoing;
8
9 pub const SCHEDULED_KEY_PREFIX: &str = "scheduled-";
10
11 pub fn scheduled_key(draft_id: &str) -> String {
12 format!("{SCHEDULED_KEY_PREFIX}{draft_id}")
13 }
14
15 pub fn draft_key(draft: &ScheduledDraft) -> &str {
16 if draft.id.is_empty() {
17 &draft.client_message_id
18 } else {
19 &draft.id
20 }
21 }
22
23 pub fn draft_id_of(key: &str) -> Option<&str> {
24 key.strip_prefix(SCHEDULED_KEY_PREFIX)
25 }
26
27 pub fn scheduled_outgoing(html: &str) -> Outgoing {
28 Outgoing {
29 draft: Draft::from_spans(&html_to_spans(html)).trimmed(),
30 mentions: Vec::new(),
31 reply: None,
32 edit: None,
33 images: Vec::new(),
34 files: Vec::new(),
35 link_preview: None,
36 }
37 }
38
39 pub fn is_visible(draft: &ScheduledDraft, now: DateTime<Utc>) -> bool {
40 draft.delivery_state.is_some() || draft.send_at > now
41 }
42
43 pub fn scheduled_label(send_at: DateTime<Utc>, now: DateTime<Utc>) -> String {
44 describe(send_at.with_timezone(&Local), now.with_timezone(&Local))
45 }
46
47 pub fn scheduled_rows(
48 drafts: &[ScheduledDraft],
49 inner_thread_id: &str,
50 conversation_id: &str,
51 my_user_id: Option<&str>,
52 now: DateTime<Utc>,
53 change_failed: Option<&str>,
54 ) -> Vec<MessageRow> {
55 let mut shown: Vec<&ScheduledDraft> = drafts
56 .iter()
57 .filter(|draft| draft.inner_thread_id == inner_thread_id && is_visible(draft, now))
58 .collect();
59 shown.sort_by_key(|draft| draft.send_at);
60 shown
61 .into_iter()
62 .map(|draft| {
63 let state = if change_failed == Some(draft_key(draft)) {
64 ScheduledState::ChangeFailed
65 } else if draft.delivery_state.is_some() {
66 ScheduledState::DeliveryFailed
67 } else {
68 ScheduledState::Waiting
69 };
70 let mut row = pending_row(
71 scheduled_key(draft_key(draft)),
72 conversation_id.to_owned(),
73 my_user_id.map(str::to_owned),
74 draft.send_at,
75 &scheduled_outgoing(&draft.html),
76 Delivery::Scheduled(state),
77 );
78 row.time = format!("Scheduled {}", scheduled_label(draft.send_at, now));
79 row
80 })
81 .collect()
82 }
83
84 #[cfg(test)]
85 mod tests {
86 use chrono::{Duration, TimeZone};
87
88 use super::*;
89
90 fn now() -> DateTime<Utc> {
91 Utc.with_ymd_and_hms(2026, 10, 9, 10, 0, 0).unwrap()
92 }
93
94 fn draft(id: &str, thread: &str, minutes_ahead: i64, failed: bool) -> ScheduledDraft {
95 ScheduledDraft {
96 id: id.to_owned(),
97 client_message_id: format!("c{id}"),
98 inner_thread_id: thread.to_owned(),
99 send_at: now() + Duration::minutes(minutes_ahead),
100 html: format!("<p>text {id}</p>"),
101 delivery_state: failed.then(|| "failed".to_owned()),
102 }
103 }
104
105 fn rows(drafts: &[ScheduledDraft], thread: &str, failed: Option<&str>) -> Vec<MessageRow> {
106 scheduled_rows(drafts, thread, "chat", Some("me"), now(), failed)
107 }
108
109 #[test]
110 fn only_drafts_of_the_open_thread_show_sorted_by_time() {
111 let drafts = [
112 draft("late", "chat", 120, false),
113 draft("other", "other-chat", 30, false),
114 draft("soon", "chat", 30, false),
115 draft("reply", "chan;messageid=m1", 30, false),
116 ];
117 let keys: Vec<_> = rows(&drafts, "chat", None)
118 .into_iter()
119 .map(|row| row.key)
120 .collect();
121 assert_eq!(keys, ["scheduled-soon", "scheduled-late"]);
122 let replies = rows(&drafts, "chan;messageid=m1", None);
123 assert_eq!(replies.len(), 1);
124 }
125
126 #[test]
127 fn a_passed_time_hides_the_draft_unless_delivery_failed() {
128 let drafts = [
129 draft("gone", "chat", -1, false),
130 draft("stuck", "chat", -1, true),
131 ];
132 let shown = rows(&drafts, "chat", None);
133 assert_eq!(shown.len(), 1);
134 assert_eq!(
135 shown[0].delivery,
136 Delivery::Scheduled(ScheduledState::DeliveryFailed)
137 );
138 }
139
140 #[test]
141 fn a_failed_change_marks_only_its_draft() {
142 let drafts = [draft("a", "chat", 30, false), draft("b", "chat", 60, false)];
143 let shown = rows(&drafts, "chat", Some("b"));
144 assert_eq!(
145 shown[0].delivery,
146 Delivery::Scheduled(ScheduledState::Waiting)
147 );
148 assert_eq!(
149 shown[1].delivery,
150 Delivery::Scheduled(ScheduledState::ChangeFailed)
151 );
152 }
153
154 #[test]
155 fn the_row_is_an_own_bubble_labelled_with_the_send_time() {
156 let shown = rows(&[draft("a", "chat", 30, false)], "chat", None);
157 assert!(shown[0].own);
158 assert!(shown[0].time.starts_with("Scheduled "), "{}", shown[0].time);
159 assert!(!shown[0].blocks.is_empty());
160 assert_eq!(draft_id_of(&shown[0].key), Some("a"));
161 }
162
163 #[test]
164 fn the_html_of_a_draft_comes_back_as_an_editable_draft() {
165 let outgoing = scheduled_outgoing("<p>hello <b>there</b></p>");
166 assert_eq!(outgoing.text(), "hello there");
167 assert!(outgoing.draft.to_html().contains("<b>there</b>"));
168 assert!(outgoing.edit.is_none() && outgoing.mentions.is_empty());
169 }
170 }
@@ -0,0 +1,170 @@
1use chrono::{DateTime, Local, Utc};
2use teams_core::{Draft, ScheduledDraft, html_to_spans};
3
4use crate::pending_rows::pending_row;
5use crate::rows::{Delivery, MessageRow, ScheduledState};
6use crate::schedule_time::describe;
7use crate::views::composer::Outgoing;
8
9pub const SCHEDULED_KEY_PREFIX: &str = "scheduled-";
10
11pub fn scheduled_key(draft_id: &str) -> String {
12 format!("{SCHEDULED_KEY_PREFIX}{draft_id}")
13}
14
15pub fn draft_key(draft: &ScheduledDraft) -> &str {
16 if draft.id.is_empty() {
17 &draft.client_message_id
18 } else {
19 &draft.id
20 }
21}
22
23pub fn draft_id_of(key: &str) -> Option<&str> {
24 key.strip_prefix(SCHEDULED_KEY_PREFIX)
25}
26
27pub fn scheduled_outgoing(html: &str) -> Outgoing {
28 Outgoing {
29 draft: Draft::from_spans(&html_to_spans(html)).trimmed(),
30 mentions: Vec::new(),
31 reply: None,
32 edit: None,
33 images: Vec::new(),
34 files: Vec::new(),
35 link_preview: None,
36 }
37}
38
39pub fn is_visible(draft: &ScheduledDraft, now: DateTime<Utc>) -> bool {
40 draft.delivery_state.is_some() || draft.send_at > now
41}
42
43pub fn scheduled_label(send_at: DateTime<Utc>, now: DateTime<Utc>) -> String {
44 describe(send_at.with_timezone(&Local), now.with_timezone(&Local))
45}
46
47pub fn scheduled_rows(
48 drafts: &[ScheduledDraft],
49 inner_thread_id: &str,
50 conversation_id: &str,
51 my_user_id: Option<&str>,
52 now: DateTime<Utc>,
53 change_failed: Option<&str>,
54) -> Vec<MessageRow> {
55 let mut shown: Vec<&ScheduledDraft> = drafts
56 .iter()
57 .filter(|draft| draft.inner_thread_id == inner_thread_id && is_visible(draft, now))
58 .collect();
59 shown.sort_by_key(|draft| draft.send_at);
60 shown
61 .into_iter()
62 .map(|draft| {
63 let state = if change_failed == Some(draft_key(draft)) {
64 ScheduledState::ChangeFailed
65 } else if draft.delivery_state.is_some() {
66 ScheduledState::DeliveryFailed
67 } else {
68 ScheduledState::Waiting
69 };
70 let mut row = pending_row(
71 scheduled_key(draft_key(draft)),
72 conversation_id.to_owned(),
73 my_user_id.map(str::to_owned),
74 draft.send_at,
75 &scheduled_outgoing(&draft.html),
76 Delivery::Scheduled(state),
77 );
78 row.time = format!("Scheduled {}", scheduled_label(draft.send_at, now));
79 row
80 })
81 .collect()
82}
83
84#[cfg(test)]
85mod tests {
86 use chrono::{Duration, TimeZone};
87
88 use super::*;
89
90 fn now() -> DateTime<Utc> {
91 Utc.with_ymd_and_hms(2026, 10, 9, 10, 0, 0).unwrap()
92 }
93
94 fn draft(id: &str, thread: &str, minutes_ahead: i64, failed: bool) -> ScheduledDraft {
95 ScheduledDraft {
96 id: id.to_owned(),
97 client_message_id: format!("c{id}"),
98 inner_thread_id: thread.to_owned(),
99 send_at: now() + Duration::minutes(minutes_ahead),
100 html: format!("<p>text {id}</p>"),
101 delivery_state: failed.then(|| "failed".to_owned()),
102 }
103 }
104
105 fn rows(drafts: &[ScheduledDraft], thread: &str, failed: Option<&str>) -> Vec<MessageRow> {
106 scheduled_rows(drafts, thread, "chat", Some("me"), now(), failed)
107 }
108
109 #[test]
110 fn only_drafts_of_the_open_thread_show_sorted_by_time() {
111 let drafts = [
112 draft("late", "chat", 120, false),
113 draft("other", "other-chat", 30, false),
114 draft("soon", "chat", 30, false),
115 draft("reply", "chan;messageid=m1", 30, false),
116 ];
117 let keys: Vec<_> = rows(&drafts, "chat", None)
118 .into_iter()
119 .map(|row| row.key)
120 .collect();
121 assert_eq!(keys, ["scheduled-soon", "scheduled-late"]);
122 let replies = rows(&drafts, "chan;messageid=m1", None);
123 assert_eq!(replies.len(), 1);
124 }
125
126 #[test]
127 fn a_passed_time_hides_the_draft_unless_delivery_failed() {
128 let drafts = [
129 draft("gone", "chat", -1, false),
130 draft("stuck", "chat", -1, true),
131 ];
132 let shown = rows(&drafts, "chat", None);
133 assert_eq!(shown.len(), 1);
134 assert_eq!(
135 shown[0].delivery,
136 Delivery::Scheduled(ScheduledState::DeliveryFailed)
137 );
138 }
139
140 #[test]
141 fn a_failed_change_marks_only_its_draft() {
142 let drafts = [draft("a", "chat", 30, false), draft("b", "chat", 60, false)];
143 let shown = rows(&drafts, "chat", Some("b"));
144 assert_eq!(
145 shown[0].delivery,
146 Delivery::Scheduled(ScheduledState::Waiting)
147 );
148 assert_eq!(
149 shown[1].delivery,
150 Delivery::Scheduled(ScheduledState::ChangeFailed)
151 );
152 }
153
154 #[test]
155 fn the_row_is_an_own_bubble_labelled_with_the_send_time() {
156 let shown = rows(&[draft("a", "chat", 30, false)], "chat", None);
157 assert!(shown[0].own);
158 assert!(shown[0].time.starts_with("Scheduled "), "{}", shown[0].time);
159 assert!(!shown[0].blocks.is_empty());
160 assert_eq!(draft_id_of(&shown[0].key), Some("a"));
161 }
162
163 #[test]
164 fn the_html_of_a_draft_comes_back_as_an_editable_draft() {
165 let outgoing = scheduled_outgoing("<p>hello <b>there</b></p>");
166 assert_eq!(outgoing.text(), "hello there");
167 assert!(outgoing.draft.to_html().contains("<b>there</b>"));
168 assert!(outgoing.edit.is_none() && outgoing.mentions.is_empty());
169 }
170}
crates/app/src/stored_outgoing.rs added +244 −0
@@ -0,0 +1,244 @@
1 use std::sync::Arc;
2
3 use gpui_kit::{Image, ImageFormat};
4 use serde::{Deserialize, Serialize};
5 use store::AttachmentImage;
6 use teams_core::{Draft, DraftLine, LinkPreview, MentionInput};
7
8 use crate::remote_image::{RemoteImage, RemoteKind};
9 use crate::views::attachment_tray::{InlineImage, OutgoingFile, OutgoingImage};
10 use crate::views::composer::{Outgoing, ReplyPreview};
11
12 const IMAGE_FORMATS: [ImageFormat; 9] = [
13 ImageFormat::Png,
14 ImageFormat::Jpeg,
15 ImageFormat::Webp,
16 ImageFormat::Gif,
17 ImageFormat::Svg,
18 ImageFormat::Bmp,
19 ImageFormat::Tiff,
20 ImageFormat::Ico,
21 ImageFormat::Pnm,
22 ];
23
24 #[derive(Serialize, Deserialize)]
25 enum StoredObject {
26 Inline,
27 Gif(StoredRemote),
28 Sticker(StoredRemote),
29 }
30
31 #[derive(Serialize, Deserialize)]
32 struct StoredRemote {
33 url: String,
34 title: String,
35 width: u32,
36 height: u32,
37 }
38
39 #[derive(Serialize, Deserialize)]
40 struct StoredPreview {
41 url: String,
42 title: Option<String>,
43 description: Option<String>,
44 image_url: Option<String>,
45 image_width: Option<u32>,
46 image_height: Option<u32>,
47 }
48
49 #[derive(Serialize, Deserialize)]
50 struct Payload {
51 lines: Vec<DraftLine>,
52 mentions: Vec<MentionInput>,
53 reply: Option<ReplyPreview>,
54 files: Vec<OutgoingFile>,
55 objects: Vec<StoredObject>,
56 preview: Option<StoredPreview>,
57 }
58
59 pub struct StoredOutgoing {
60 pub payload: String,
61 pub images: Vec<AttachmentImage>,
62 }
63
64 pub fn encode(outgoing: &Outgoing) -> Option<StoredOutgoing> {
65 let mut images = Vec::new();
66 let mut objects = Vec::new();
67 for object in &outgoing.images {
68 match object {
69 OutgoingImage::Inline(inline) => {
70 images.push(AttachmentImage {
71 name: inline.name.clone(),
72 format: inline.image.format.mime_type().to_owned(),
73 bytes: inline.image.bytes.clone(),
74 width: inline.dimensions.map(|(width, _)| width),
75 height: inline.dimensions.map(|(_, height)| height),
76 });
77 objects.push(StoredObject::Inline);
78 }
79 OutgoingImage::Remote(remote) => {
80 let stored = StoredRemote {
81 url: remote.url.clone(),
82 title: remote.title.clone(),
83 width: remote.width,
84 height: remote.height,
85 };
86 objects.push(match remote.kind {
87 RemoteKind::Gif => StoredObject::Gif(stored),
88 RemoteKind::Sticker => StoredObject::Sticker(stored),
89 });
90 }
91 }
92 }
93 let payload = serde_json::to_string(&Payload {
94 lines: outgoing.draft.to_lines(),
95 mentions: outgoing.mentions.clone(),
96 reply: outgoing.reply.clone(),
97 files: outgoing.files.clone(),
98 objects,
99 preview: outgoing.link_preview.as_ref().map(|preview| StoredPreview {
100 url: preview.url.clone(),
101 title: preview.title.clone(),
102 description: preview.description.clone(),
103 image_url: preview.image_url.clone(),
104 image_width: preview.image_width,
105 image_height: preview.image_height,
106 }),
107 })
108 .ok()?;
109 Some(StoredOutgoing { payload, images })
110 }
111
112 fn inline_image(stored: &AttachmentImage) -> Option<OutgoingImage> {
113 let format = IMAGE_FORMATS
114 .into_iter()
115 .find(|format| format.mime_type() == stored.format)?;
116 Some(OutgoingImage::Inline(InlineImage {
117 name: stored.name.clone(),
118 image: Arc::new(Image::from_bytes(format, stored.bytes.clone())),
119 dimensions: stored.width.zip(stored.height),
120 }))
121 }
122
123 fn remote_image(kind: RemoteKind, stored: StoredRemote) -> OutgoingImage {
124 OutgoingImage::Remote(RemoteImage {
125 kind,
126 url: stored.url,
127 title: stored.title,
128 width: stored.width,
129 height: stored.height,
130 })
131 }
132
133 pub fn decode(payload: &str, images: &[AttachmentImage]) -> Option<Outgoing> {
134 let Payload {
135 lines,
136 mentions,
137 reply,
138 files,
139 objects,
140 preview,
141 } = serde_json::from_str(payload).ok()?;
142 let mut inline = images.iter();
143 let images = objects
144 .into_iter()
145 .filter_map(|object| match object {
146 StoredObject::Inline => inline.next().and_then(inline_image),
147 StoredObject::Gif(stored) => Some(remote_image(RemoteKind::Gif, stored)),
148 StoredObject::Sticker(stored) => Some(remote_image(RemoteKind::Sticker, stored)),
149 })
150 .collect();
151 Some(Outgoing {
152 draft: Draft::from_lines(&lines),
153 mentions,
154 reply,
155 edit: None,
156 images,
157 files,
158 link_preview: preview.map(|preview| LinkPreview {
159 url: preview.url,
160 title: preview.title,
161 description: preview.description,
162 image_url: preview.image_url,
163 image_width: preview.image_width,
164 image_height: preview.image_height,
165 }),
166 })
167 }
168
169 #[cfg(test)]
170 mod tests {
171 use teams_core::{FileKind, FileReference, MarkKind};
172
173 use super::*;
174
175 fn outgoing() -> Outgoing {
176 let mut draft = Draft::plain("hi @Ada Lovelace \u{FFFC}\nsecond");
177 draft.toggle(0..2, MarkKind::Bold);
178 draft.take_edits();
179 Outgoing {
180 draft,
181 mentions: vec![MentionInput::user("user-1", "Ada Lovelace")],
182 reply: Some(ReplyPreview {
183 message_id: "message-1".to_owned(),
184 author: "Grace".to_owned(),
185 excerpt: "earlier".to_owned(),
186 }),
187 edit: None,
188 images: vec![
189 OutgoingImage::Inline(InlineImage {
190 name: "shot.png".to_owned(),
191 image: Arc::new(Image::from_bytes(ImageFormat::Png, vec![1, 2, 3])),
192 dimensions: Some((40, 30)),
193 }),
194 OutgoingImage::Remote(RemoteImage {
195 kind: RemoteKind::Gif,
196 url: "https://example.test/a.gif".to_owned(),
197 title: "wave".to_owned(),
198 width: 100,
199 height: 80,
200 }),
201 ],
202 files: vec![OutgoingFile {
203 name: "plan.pdf".to_owned(),
204 size: 12,
205 kind: FileKind::Pdf,
206 reference: FileReference {
207 attachment_id: "attachment-1".to_owned(),
208 content_url: "https://example.test/plan.pdf".to_owned(),
209 name: "plan.pdf".to_owned(),
210 },
211 uploaded: None,
212 }],
213 link_preview: Some(LinkPreview {
214 url: "https://a.example".to_owned(),
215 title: Some("A".to_owned()),
216 description: None,
217 image_url: None,
218 image_width: None,
219 image_height: None,
220 }),
221 }
222 }
223
224 #[test]
225 fn an_outgoing_message_round_trips_with_formatting_mention_and_image() {
226 let original = outgoing();
227 let stored = encode(&original).unwrap();
228 let restored = decode(&stored.payload, &stored.images).unwrap();
229 assert_eq!(restored.draft.text(), original.draft.text());
230 assert_eq!(restored.draft.to_html(), original.draft.to_html());
231 assert!(restored.draft.to_html().contains("<b>"));
232 assert_eq!(restored.mentions, original.mentions);
233 assert_eq!(restored.reply, original.reply);
234 assert_eq!(restored.images, original.images);
235 assert_eq!(restored.files, original.files);
236 assert_eq!(restored.link_preview, original.link_preview);
237 assert_eq!(restored.edit, None);
238 }
239
240 #[test]
241 fn an_unreadable_payload_decodes_to_nothing() {
242 assert!(decode("not json", &[]).is_none());
243 }
244 }
@@ -0,0 +1,244 @@
1use std::sync::Arc;
2
3use gpui_kit::{Image, ImageFormat};
4use serde::{Deserialize, Serialize};
5use store::AttachmentImage;
6use teams_core::{Draft, DraftLine, LinkPreview, MentionInput};
7
8use crate::remote_image::{RemoteImage, RemoteKind};
9use crate::views::attachment_tray::{InlineImage, OutgoingFile, OutgoingImage};
10use crate::views::composer::{Outgoing, ReplyPreview};
11
12const IMAGE_FORMATS: [ImageFormat; 9] = [
13 ImageFormat::Png,
14 ImageFormat::Jpeg,
15 ImageFormat::Webp,
16 ImageFormat::Gif,
17 ImageFormat::Svg,
18 ImageFormat::Bmp,
19 ImageFormat::Tiff,
20 ImageFormat::Ico,
21 ImageFormat::Pnm,
22];
23
24#[derive(Serialize, Deserialize)]
25enum StoredObject {
26 Inline,
27 Gif(StoredRemote),
28 Sticker(StoredRemote),
29}
30
31#[derive(Serialize, Deserialize)]
32struct StoredRemote {
33 url: String,
34 title: String,
35 width: u32,
36 height: u32,
37}
38
39#[derive(Serialize, Deserialize)]
40struct StoredPreview {
41 url: String,
42 title: Option<String>,
43 description: Option<String>,
44 image_url: Option<String>,
45 image_width: Option<u32>,
46 image_height: Option<u32>,
47}
48
49#[derive(Serialize, Deserialize)]
50struct Payload {
51 lines: Vec<DraftLine>,
52 mentions: Vec<MentionInput>,
53 reply: Option<ReplyPreview>,
54 files: Vec<OutgoingFile>,
55 objects: Vec<StoredObject>,
56 preview: Option<StoredPreview>,
57}
58
59pub struct StoredOutgoing {
60 pub payload: String,
61 pub images: Vec<AttachmentImage>,
62}
63
64pub fn encode(outgoing: &Outgoing) -> Option<StoredOutgoing> {
65 let mut images = Vec::new();
66 let mut objects = Vec::new();
67 for object in &outgoing.images {
68 match object {
69 OutgoingImage::Inline(inline) => {
70 images.push(AttachmentImage {
71 name: inline.name.clone(),
72 format: inline.image.format.mime_type().to_owned(),
73 bytes: inline.image.bytes.clone(),
74 width: inline.dimensions.map(|(width, _)| width),
75 height: inline.dimensions.map(|(_, height)| height),
76 });
77 objects.push(StoredObject::Inline);
78 }
79 OutgoingImage::Remote(remote) => {
80 let stored = StoredRemote {
81 url: remote.url.clone(),
82 title: remote.title.clone(),
83 width: remote.width,
84 height: remote.height,
85 };
86 objects.push(match remote.kind {
87 RemoteKind::Gif => StoredObject::Gif(stored),
88 RemoteKind::Sticker => StoredObject::Sticker(stored),
89 });
90 }
91 }
92 }
93 let payload = serde_json::to_string(&Payload {
94 lines: outgoing.draft.to_lines(),
95 mentions: outgoing.mentions.clone(),
96 reply: outgoing.reply.clone(),
97 files: outgoing.files.clone(),
98 objects,
99 preview: outgoing.link_preview.as_ref().map(|preview| StoredPreview {
100 url: preview.url.clone(),
101 title: preview.title.clone(),
102 description: preview.description.clone(),
103 image_url: preview.image_url.clone(),
104 image_width: preview.image_width,
105 image_height: preview.image_height,
106 }),
107 })
108 .ok()?;
109 Some(StoredOutgoing { payload, images })
110}
111
112fn inline_image(stored: &AttachmentImage) -> Option<OutgoingImage> {
113 let format = IMAGE_FORMATS
114 .into_iter()
115 .find(|format| format.mime_type() == stored.format)?;
116 Some(OutgoingImage::Inline(InlineImage {
117 name: stored.name.clone(),
118 image: Arc::new(Image::from_bytes(format, stored.bytes.clone())),
119 dimensions: stored.width.zip(stored.height),
120 }))
121}
122
123fn remote_image(kind: RemoteKind, stored: StoredRemote) -> OutgoingImage {
124 OutgoingImage::Remote(RemoteImage {
125 kind,
126 url: stored.url,
127 title: stored.title,
128 width: stored.width,
129 height: stored.height,
130 })
131}
132
133pub fn decode(payload: &str, images: &[AttachmentImage]) -> Option<Outgoing> {
134 let Payload {
135 lines,
136 mentions,
137 reply,
138 files,
139 objects,
140 preview,
141 } = serde_json::from_str(payload).ok()?;
142 let mut inline = images.iter();
143 let images = objects
144 .into_iter()
145 .filter_map(|object| match object {
146 StoredObject::Inline => inline.next().and_then(inline_image),
147 StoredObject::Gif(stored) => Some(remote_image(RemoteKind::Gif, stored)),
148 StoredObject::Sticker(stored) => Some(remote_image(RemoteKind::Sticker, stored)),
149 })
150 .collect();
151 Some(Outgoing {
152 draft: Draft::from_lines(&lines),
153 mentions,
154 reply,
155 edit: None,
156 images,
157 files,
158 link_preview: preview.map(|preview| LinkPreview {
159 url: preview.url,
160 title: preview.title,
161 description: preview.description,
162 image_url: preview.image_url,
163 image_width: preview.image_width,
164 image_height: preview.image_height,
165 }),
166 })
167}
168
169#[cfg(test)]
170mod tests {
171 use teams_core::{FileKind, FileReference, MarkKind};
172
173 use super::*;
174
175 fn outgoing() -> Outgoing {
176 let mut draft = Draft::plain("hi @Ada Lovelace \u{FFFC}\nsecond");
177 draft.toggle(0..2, MarkKind::Bold);
178 draft.take_edits();
179 Outgoing {
180 draft,
181 mentions: vec![MentionInput::user("user-1", "Ada Lovelace")],
182 reply: Some(ReplyPreview {
183 message_id: "message-1".to_owned(),
184 author: "Grace".to_owned(),
185 excerpt: "earlier".to_owned(),
186 }),
187 edit: None,
188 images: vec![
189 OutgoingImage::Inline(InlineImage {
190 name: "shot.png".to_owned(),
191 image: Arc::new(Image::from_bytes(ImageFormat::Png, vec![1, 2, 3])),
192 dimensions: Some((40, 30)),
193 }),
194 OutgoingImage::Remote(RemoteImage {
195 kind: RemoteKind::Gif,
196 url: "https://example.test/a.gif".to_owned(),
197 title: "wave".to_owned(),
198 width: 100,
199 height: 80,
200 }),
201 ],
202 files: vec![OutgoingFile {
203 name: "plan.pdf".to_owned(),
204 size: 12,
205 kind: FileKind::Pdf,
206 reference: FileReference {
207 attachment_id: "attachment-1".to_owned(),
208 content_url: "https://example.test/plan.pdf".to_owned(),
209 name: "plan.pdf".to_owned(),
210 },
211 uploaded: None,
212 }],
213 link_preview: Some(LinkPreview {
214 url: "https://a.example".to_owned(),
215 title: Some("A".to_owned()),
216 description: None,
217 image_url: None,
218 image_width: None,
219 image_height: None,
220 }),
221 }
222 }
223
224 #[test]
225 fn an_outgoing_message_round_trips_with_formatting_mention_and_image() {
226 let original = outgoing();
227 let stored = encode(&original).unwrap();
228 let restored = decode(&stored.payload, &stored.images).unwrap();
229 assert_eq!(restored.draft.text(), original.draft.text());
230 assert_eq!(restored.draft.to_html(), original.draft.to_html());
231 assert!(restored.draft.to_html().contains("<b>"));
232 assert_eq!(restored.mentions, original.mentions);
233 assert_eq!(restored.reply, original.reply);
234 assert_eq!(restored.images, original.images);
235 assert_eq!(restored.files, original.files);
236 assert_eq!(restored.link_preview, original.link_preview);
237 assert_eq!(restored.edit, None);
238 }
239
240 #[test]
241 fn an_unreadable_payload_decodes_to_nothing() {
242 assert!(decode("not json", &[]).is_none());
243 }
244}
crates/app/src/views/attachment_tray.rs +2 −1
@@ -7,6 +7,7 @@ use gpui_kit::assets::IconName;
7 7 use gpui_kit::component::{h_flex, v_flex};
8 8 use gpui_kit::prelude::FluentBuilder as _;
9 9 use gpui_kit::*;
10 use serde::{Deserialize, Serialize};
10 11 use teams_core::{FileKind, FileReference, UploadedFile};
11 12
12 13 use super::attachments::file_badge;
@@ -239,7 +240,7 @@ pub enum OutgoingImage {
239 240 Remote(RemoteImage),
240 241 }
241 242
242 #[derive(Debug, Clone, PartialEq, Eq)]
243 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
243 244 pub struct OutgoingFile {
244 245 pub name: String,
245 246 pub size: u64,
@@ -7,6 +7,7 @@ use gpui_kit::assets::IconName;
7use gpui_kit::component::{h_flex, v_flex};
7use gpui_kit::component::{h_flex, v_flex};
8use gpui_kit::prelude::FluentBuilder as _;
8use gpui_kit::prelude::FluentBuilder as _;
9use gpui_kit::*;
9use gpui_kit::*;
10use serde::{Deserialize, Serialize};
10use teams_core::{FileKind, FileReference, UploadedFile};
11use teams_core::{FileKind, FileReference, UploadedFile};
11
12
12use super::attachments::file_badge;
13use super::attachments::file_badge;
@@ -239,7 +240,7 @@ pub enum OutgoingImage {
239 Remote(RemoteImage),
240 Remote(RemoteImage),
240}
241}
241
242
242#[derive(Debug, Clone, PartialEq, Eq)]
243#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
243pub struct OutgoingFile {
244pub struct OutgoingFile {
244 pub name: String,
245 pub name: String,
245 pub size: u64,
246 pub size: u64,
crates/app/src/views/composer.rs +173 −12
@@ -6,6 +6,7 @@ use std::rc::Rc;
6 6 use std::sync::Arc;
7 7 use std::time::{Duration, Instant};
8 8
9 use chrono::{DateTime, Utc};
9 10 use gpui_kit::assets::IconName;
10 11 use gpui_kit::component::{
11 12 ActiveTheme as _,
@@ -22,12 +23,16 @@ use gpui_kit::component::{
22 23 };
23 24 use gpui_kit::prelude::FluentBuilder as _;
24 25 use gpui_kit::*;
26 use serde::{Deserialize, Serialize};
25 27 use teams_core::{
26 28 Draft, DraftLine, Edit, FileReference, FormatState, HostedImage, LineKind, MarkKind,
27 29 LinkPreview, MentionCandidate, MentionInput, MessageExtras, OBJECT_MARK, SizeStep, TypingStyle,
28 30 UploadedFile, changed_span, has_markdown, link_url, map_offset, reverse_edits,
29 31 };
30 32
33 mod drafts;
34 mod schedule;
35
31 36 use super::attachment_tray::{
32 37 AttachmentTray, DoneFile, JobKind, LoadedFile, MAX_ATTACHMENTS, OutgoingFile, OutgoingImage,
33 38 PasteAction, UploadJob, UploadResult, discard_uploaded, inline_preview, names_of, paste_action,
@@ -44,6 +49,7 @@ use crate::app_state::AppState;
44 49 use crate::emoji;
45 50 use crate::remote_image::RemoteImage;
46 51 use crate::runtime;
52 use crate::scheduled_rows::scheduled_label;
47 53 use crate::theme;
48 54 use crate::typing::OutgoingTyping;
49 55
@@ -74,7 +80,8 @@ actions!(
74 80 ToggleSuperscript,
75 81 ToggleSubscript,
76 82 ToggleCode,
77 EditLink
83 EditLink,
84 ScheduleSend
78 85 ]
79 86 );
80 87
@@ -88,6 +95,7 @@ pub fn bind_keys(cx: &mut App) {
88 95 KeyBinding::new("ctrl-=", ToggleSubscript, Some(KEY_CONTEXT)),
89 96 KeyBinding::new("ctrl-shift-c", ToggleCode, Some(KEY_CONTEXT)),
90 97 KeyBinding::new("ctrl-k", EditLink, Some(KEY_CONTEXT)),
98 KeyBinding::new("ctrl-shift-enter", ScheduleSend, Some(KEY_CONTEXT)),
91 99 #[cfg(target_os = "macos")]
92 100 KeyBinding::new("cmd-b", ToggleBold, Some(KEY_CONTEXT)),
93 101 #[cfg(target_os = "macos")]
@@ -99,7 +107,7 @@ pub fn bind_keys(cx: &mut App) {
99 107 ]);
100 108 }
101 109
102 #[derive(Debug, Clone, PartialEq, Eq)]
110 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
103 111 pub struct ReplyPreview {
104 112 pub message_id: String,
105 113 pub author: String,
@@ -110,6 +118,7 @@ pub struct ReplyPreview {
110 118 pub struct EditPreview {
111 119 pub message_id: String,
112 120 pub excerpt: String,
121 pub scheduled: Option<DateTime<Utc>>,
113 122 }
114 123
115 124 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -200,6 +209,10 @@ impl UploadHandle {
200 209
201 210 pub enum ComposerEvent {
202 211 Submit(Box<Outgoing>),
212 Schedule {
213 outgoing: Box<Outgoing>,
214 send_at: DateTime<Utc>,
215 },
203 216 EditLast,
204 217 Typing(bool),
205 218 }
@@ -279,6 +292,10 @@ pub struct Composer {
279 292 uploads: HashMap<u64, UploadHandle>,
280 293 demo_failed: HashSet<u64>,
281 294 carry_images_into: Option<String>,
295 draft_save: Option<Task<()>>,
296 saved_images: Option<drafts::ImageFingerprint>,
297 schedule: Option<schedule::SchedulePopover>,
298 scheduling: Option<String>,
282 299 pending_anchors: HashMap<u64, usize>,
283 300 link: ComposeLink,
284 301 fun_picker: Entity<FunPicker>,
@@ -471,6 +488,10 @@ impl Composer {
471 488 uploads: HashMap::new(),
472 489 demo_failed: HashSet::new(),
473 490 carry_images_into: None,
491 draft_save: None,
492 saved_images: None,
493 schedule: None,
494 scheduling: None,
474 495 pending_anchors: HashMap::new(),
475 496 link: ComposeLink::default(),
476 497 fun_picker,
@@ -491,6 +512,7 @@ impl Composer {
491 512 self.update_emoji(cx);
492 513 self.update_mention(cx);
493 514 self.update_link_preview(cx);
515 self.schedule_draft_save(cx);
494 516 }
495 517 let value = input.read(cx).value();
496 518 if submitted_text(event, &value).is_some()
@@ -695,6 +717,7 @@ impl Composer {
695 717 };
696 718 self.apply_to_input(edits, selection, window, cx);
697 719 self.record(StepKind::Other, cx);
720 self.schedule_draft_save(cx);
698 721 }
699 722
700 723 fn apply_to_input(
@@ -822,6 +845,7 @@ impl Composer {
822 845 self.refresh_style(cx);
823 846 self.update_emoji(cx);
824 847 self.update_mention(cx);
848 self.schedule_draft_save(cx);
825 849 cx.notify();
826 850 }
827 851
@@ -922,6 +946,7 @@ impl Composer {
922 946 self.draft.take_edits();
923 947 self.record(StepKind::Other, cx);
924 948 self.refresh_style(cx);
949 self.schedule_draft_save(cx);
925 950 }
926 951 cx.notify();
927 952 }
@@ -945,6 +970,7 @@ impl Composer {
945 970 self.draft.take_edits();
946 971 self.record(StepKind::Other, cx);
947 972 self.refresh_style(cx);
973 self.schedule_draft_save(cx);
948 974 }
949 975 cx.notify();
950 976 }
@@ -1442,6 +1468,9 @@ impl Composer {
1442 1468 ) {
1443 1469 self.set_placeholder(&format!("Message {name}"), window, cx);
1444 1470 if self.conversation_id.as_deref() != Some(conversation_id) {
1471 self.save_draft_now(cx);
1472 self.draft_save = None;
1473 self.saved_images = None;
1445 1474 let carry = self.carry_images_into.take().as_deref() == Some(conversation_id);
1446 1475 self.conversation_id = Some(conversation_id.to_owned());
1447 1476 self.cancel_uploads();
@@ -1459,6 +1488,10 @@ impl Composer {
1459 1488 }
1460 1489 self.mention_inputs.clear();
1461 1490 self.close_popup();
1491 self.schedule = None;
1492 if !carry {
1493 self.load_stored_draft(conversation_id, window, cx);
1494 }
1462 1495 cx.notify();
1463 1496 }
1464 1497 }
@@ -1477,6 +1510,7 @@ impl Composer {
1477 1510 if self.reply.is_some() {
1478 1511 self.editing = None;
1479 1512 }
1513 self.schedule_draft_save(cx);
1480 1514 cx.notify();
1481 1515 }
1482 1516
@@ -1491,10 +1525,11 @@ impl Composer {
1491 1525 }
1492 1526
1493 1527 fn outgoing(&self, cx: &App) -> Option<Outgoing> {
1528 self.can_send(cx).then(|| self.compose(cx))
1529 }
1530
1531 fn compose(&self, cx: &App) -> Outgoing {
1494 1532 let state = self.input.read(cx);
1495 if !self.can_send(cx) {
1496 return None;
1497 }
1498 1533 let mut draft = self.current_draft(cx);
1499 1534 let image_spans: Vec<(Range<usize>, u64)> = state
1500 1535 .tokens()
@@ -1529,7 +1564,7 @@ impl Composer {
1529 1564 .filter_map(|span| self.mention_inputs.get(span.token().id().as_ref()))
1530 1565 .cloned()
1531 1566 .collect();
1532 Some(Outgoing {
1567 Outgoing {
1533 1568 draft,
1534 1569 mentions,
1535 1570 reply: self.reply.clone(),
@@ -1545,7 +1580,7 @@ impl Composer {
1545 1580 } else {
1546 1581 Vec::new()
1547 1582 },
1548 })
1583 }
1549 1584 }
1550 1585
1551 1586 /// The draft, or the plain input text while a change is still on its way to the draft.
@@ -1992,6 +2027,7 @@ impl Composer {
1992 2027 }
1993 2028 let uploaded = self.tray.remove(id);
1994 2029 self.discard_uploaded(uploaded.into_iter().collect(), cx);
2030 self.schedule_draft_save(cx);
1995 2031 cx.notify();
1996 2032 }
1997 2033
@@ -2003,6 +2039,9 @@ impl Composer {
2003 2039 }
2004 2040
2005 2041 pub fn submit_current(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2042 if self.scheduling.is_some() {
2043 return;
2044 }
2006 2045 let Some(outgoing) = self.outgoing(cx) else {
2007 2046 return;
2008 2047 };
@@ -2011,6 +2050,7 @@ impl Composer {
2011 2050 self.mention_inputs.clear();
2012 2051 if self.editing.is_none() {
2013 2052 self.tray.clear();
2053 self.clear_stored_draft(cx);
2014 2054 }
2015 2055 self.reply = None;
2016 2056 self.editing = None;
@@ -2057,6 +2097,7 @@ impl Composer {
2057 2097 self.editing = outgoing.edit.clone();
2058 2098 self.link.restore(outgoing.link_preview.clone());
2059 2099 self.close_popup();
2100 self.schedule_draft_save(cx);
2060 2101 cx.notify();
2061 2102 }
2062 2103
@@ -2294,7 +2335,10 @@ impl Composer {
2294 2335 .bg(theme::surface())
2295 2336 .border_1()
2296 2337 .border_color(theme::border())
2297 .child(icon(IconName::Pencil, 14., theme::accent_text()))
2338 .child(match edit.scheduled {
2339 Some(_) => symbol("schedule_send", 14., theme::accent_text()).into_any_element(),
2340 None => icon(IconName::Pencil, 14., theme::accent_text()).into_any_element(),
2341 })
2298 2342 .child(
2299 2343 v_flex()
2300 2344 .flex_1()
@@ -2305,7 +2349,13 @@ impl Composer {
2305 2349 .text_size(px(12.))
2306 2350 .font_weight(FontWeight::SEMIBOLD)
2307 2351 .text_color(theme::accent_text())
2308 .child("Editing message"),
2352 .child(match edit.scheduled {
2353 Some(send_at) => format!(
2354 "Editing scheduled message - {}",
2355 scheduled_label(send_at, Utc::now())
2356 ),
2357 None => "Editing message".to_owned(),
2358 }),
2309 2359 )
2310 2360 .child(
2311 2361 div()
@@ -2398,6 +2448,10 @@ impl Render for Composer {
2398 2448 .justify_center()
2399 2449 .rounded(px(8.))
2400 2450 .child(symbol("keyboard_return", 20., white()))
2451 .on_mouse_down(
2452 MouseButton::Right,
2453 cx.listener(|this, _, _, cx| this.open_schedule_menu(cx)),
2454 )
2401 2455 .when(!can_send, |button| button.opacity(0.4))
2402 2456 .when(can_send, |button| {
2403 2457 button
@@ -2554,6 +2608,7 @@ impl Render for Composer {
2554 2608 }
2555 2609 }))
2556 2610 .on_action(cx.listener(|this, _: &EditLink, window, cx| this.edit_link(window, cx)))
2611 .on_action(cx.listener(|this, _: &ScheduleSend, _, cx| this.open_schedule_picker(cx)))
2557 2612 .capture_action(cx.listener(|this, _: &Undo, window, cx| {
2558 2613 if this.link_editor.is_none() {
2559 2614 this.step_history(true, window, cx);
@@ -2578,8 +2633,11 @@ impl Render for Composer {
2578 2633 cx.stop_propagation();
2579 2634 }
2580 2635 }))
2581 .capture_action(cx.listener(|this, _: &MoveUp, _, cx| {
2636 .capture_action(cx.listener(|this, _: &MoveUp, window, cx| {
2582 2637 if this.link_editor.is_some() {
2638 } else if this.schedule.is_some() {
2639 this.move_schedule_highlight(-1, window, cx);
2640 cx.stop_propagation();
2583 2641 } else if this.popup_is_open() {
2584 2642 this.move_highlight(-1, cx);
2585 2643 cx.stop_propagation();
@@ -2588,8 +2646,12 @@ impl Render for Composer {
2588 2646 cx.stop_propagation();
2589 2647 }
2590 2648 }))
2591 .capture_action(cx.listener(|this, _: &MoveDown, _, cx| {
2592 if this.link_editor.is_none() && this.popup_is_open() {
2649 .capture_action(cx.listener(|this, _: &MoveDown, window, cx| {
2650 if this.link_editor.is_some() {
2651 } else if this.schedule.is_some() {
2652 this.move_schedule_highlight(1, window, cx);
2653 cx.stop_propagation();
2654 } else if this.popup_is_open() {
2593 2655 this.move_highlight(1, cx);
2594 2656 cx.stop_propagation();
2595 2657 }
@@ -2598,6 +2660,9 @@ impl Render for Composer {
2598 2660 if this.link_editor.is_some() {
2599 2661 this.apply_link(window, cx);
2600 2662 cx.stop_propagation();
2663 } else if this.schedule.is_some() {
2664 this.activate_schedule_row(window, cx);
2665 cx.stop_propagation();
2601 2666 } else if this.popup_is_open() {
2602 2667 this.accept_popup(window, cx);
2603 2668 cx.stop_propagation();
@@ -2632,6 +2697,11 @@ impl Render for Composer {
2632 2697 }
2633 2698 }))
2634 2699 .capture_action(cx.listener(|this, _: &Escape, window, cx| {
2700 if this.schedule.is_some() {
2701 this.close_schedule(window, cx);
2702 cx.stop_propagation();
2703 return;
2704 }
2635 2705 if this.link_editor.is_some() {
2636 2706 this.close_link_editor(window, cx);
2637 2707 cx.stop_propagation();
@@ -2666,6 +2736,7 @@ impl Render for Composer {
2666 2736 .children(self.render_popup(cx))
2667 2737 .children(self.render_emoji_popup(window, cx))
2668 2738 .children(self.render_toolbar(focused, cx))
2739 .children(self.render_schedule(cx))
2669 2740 .child(
2670 2741 v_flex()
2671 2742 .relative()
@@ -3934,6 +4005,7 @@ mod tests {
3934 4005 edit: Some(EditPreview {
3935 4006 message_id: "m1".into(),
3936 4007 excerpt: "old".into(),
4008 scheduled: None,
3937 4009 }),
3938 4010 images: Vec::new(),
3939 4011 files: Vec::new(),
@@ -3991,6 +4063,95 @@ mod tests {
3991 4063 }
3992 4064 }
3993 4065
4066 #[gpui_kit::test]
4067 fn each_conversation_keeps_its_own_draft(cx: &mut TestAppContext) {
4068 let (handle, composer) = demo_composer(cx);
4069 cx.update_window(handle, |_, window, cx| {
4070 composer.update(cx, |composer, cx| {
4071 composer.set_conversation("chat-a", "A", window, cx);
4072 composer.set_text("**hello** there", window, cx);
4073 composer.set_conversation("chat-b", "B", window, cx);
4074 });
4075 })
4076 .unwrap();
4077 cx.update(|cx| {
4078 let composer = composer.read(cx);
4079 assert!(composer.draft.is_blank());
4080 let stored = composer
4081 .app
4082 .read(cx)
4083 .store
4084 .draft("chat-a")
4085 .unwrap()
4086 .unwrap();
4087 assert_eq!(stored.preview, "hello there");
4088 });
4089 cx.update_window(handle, |_, window, cx| {
4090 composer.update(cx, |composer, cx| {
4091 composer.set_text("other", window, cx);
4092 composer.set_conversation("chat-a", "A", window, cx);
4093 });
4094 })
4095 .unwrap();
4096 cx.update(|cx| {
4097 let composer = composer.read(cx);
4098 assert_eq!(composer.draft.text(), "hello there");
4099 assert!(composer.draft.to_html().contains("<b>"));
4100 assert!(
4101 composer
4102 .app
4103 .read(cx)
4104 .store
4105 .draft("chat-b")
4106 .unwrap()
4107 .is_some()
4108 );
4109 });
4110 }
4111
4112 #[gpui_kit::test]
4113 fn sending_clears_the_stored_draft_and_a_blank_composer_deletes_it(
4114 cx: &mut TestAppContext,
4115 ) {
4116 let (handle, composer) = demo_composer(cx);
4117 cx.update_window(handle, |_, window, cx| {
4118 composer.update(cx, |composer, cx| {
4119 composer.set_conversation("chat-a", "A", window, cx);
4120 composer.set_text("hi", window, cx);
4121 composer.save_draft_now(cx);
4122 });
4123 })
4124 .unwrap();
4125 cx.update(|cx| {
4126 assert!(
4127 composer
4128 .read(cx)
4129 .app
4130 .read(cx)
4131 .store
4132 .draft("chat-a")
4133 .unwrap()
4134 .is_some()
4135 );
4136 });
4137 cx.update_window(handle, |_, window, cx| {
4138 composer.update(cx, |composer, cx| composer.submit_current(window, cx));
4139 })
4140 .unwrap();
4141 cx.update(|cx| {
4142 assert!(
4143 composer
4144 .read(cx)
4145 .app
4146 .read(cx)
4147 .store
4148 .draft("chat-a")
4149 .unwrap()
4150 .is_none()
4151 );
4152 });
4153 }
4154
3994 4155 #[gpui_kit::test]
3995 4156 fn a_draft_target_change_drops_the_files_of_the_old_target_and_keeps_images(
3996 4157 cx: &mut TestAppContext,
@@ -6,6 +6,7 @@ use std::rc::Rc;
6use std::sync::Arc;
6use std::sync::Arc;
7use std::time::{Duration, Instant};
7use std::time::{Duration, Instant};
8
8
9use chrono::{DateTime, Utc};
9use gpui_kit::assets::IconName;
10use gpui_kit::assets::IconName;
10use gpui_kit::component::{
11use gpui_kit::component::{
11 ActiveTheme as _,
12 ActiveTheme as _,
@@ -22,12 +23,16 @@ use gpui_kit::component::{
22};
23};
23use gpui_kit::prelude::FluentBuilder as _;
24use gpui_kit::prelude::FluentBuilder as _;
24use gpui_kit::*;
25use gpui_kit::*;
26use serde::{Deserialize, Serialize};
25use teams_core::{
27use teams_core::{
26 Draft, DraftLine, Edit, FileReference, FormatState, HostedImage, LineKind, MarkKind,
28 Draft, DraftLine, Edit, FileReference, FormatState, HostedImage, LineKind, MarkKind,
27 LinkPreview, MentionCandidate, MentionInput, MessageExtras, OBJECT_MARK, SizeStep, TypingStyle,
29 LinkPreview, MentionCandidate, MentionInput, MessageExtras, OBJECT_MARK, SizeStep, TypingStyle,
28 UploadedFile, changed_span, has_markdown, link_url, map_offset, reverse_edits,
30 UploadedFile, changed_span, has_markdown, link_url, map_offset, reverse_edits,
29};
31};
30
32
33mod drafts;
34mod schedule;
35
31use super::attachment_tray::{
36use super::attachment_tray::{
32 AttachmentTray, DoneFile, JobKind, LoadedFile, MAX_ATTACHMENTS, OutgoingFile, OutgoingImage,
37 AttachmentTray, DoneFile, JobKind, LoadedFile, MAX_ATTACHMENTS, OutgoingFile, OutgoingImage,
33 PasteAction, UploadJob, UploadResult, discard_uploaded, inline_preview, names_of, paste_action,
38 PasteAction, UploadJob, UploadResult, discard_uploaded, inline_preview, names_of, paste_action,
@@ -44,6 +49,7 @@ use crate::app_state::AppState;
44use crate::emoji;
49use crate::emoji;
45use crate::remote_image::RemoteImage;
50use crate::remote_image::RemoteImage;
46use crate::runtime;
51use crate::runtime;
52use crate::scheduled_rows::scheduled_label;
47use crate::theme;
53use crate::theme;
48use crate::typing::OutgoingTyping;
54use crate::typing::OutgoingTyping;
49
55
@@ -74,7 +80,8 @@ actions!(
74 ToggleSuperscript,
80 ToggleSuperscript,
75 ToggleSubscript,
81 ToggleSubscript,
76 ToggleCode,
82 ToggleCode,
77 EditLink
83 EditLink,
84 ScheduleSend
78 ]
85 ]
79);
86);
80
87
@@ -88,6 +95,7 @@ pub fn bind_keys(cx: &mut App) {
88 KeyBinding::new("ctrl-=", ToggleSubscript, Some(KEY_CONTEXT)),
95 KeyBinding::new("ctrl-=", ToggleSubscript, Some(KEY_CONTEXT)),
89 KeyBinding::new("ctrl-shift-c", ToggleCode, Some(KEY_CONTEXT)),
96 KeyBinding::new("ctrl-shift-c", ToggleCode, Some(KEY_CONTEXT)),
90 KeyBinding::new("ctrl-k", EditLink, Some(KEY_CONTEXT)),
97 KeyBinding::new("ctrl-k", EditLink, Some(KEY_CONTEXT)),
98 KeyBinding::new("ctrl-shift-enter", ScheduleSend, Some(KEY_CONTEXT)),
91 #[cfg(target_os = "macos")]
99 #[cfg(target_os = "macos")]
92 KeyBinding::new("cmd-b", ToggleBold, Some(KEY_CONTEXT)),
100 KeyBinding::new("cmd-b", ToggleBold, Some(KEY_CONTEXT)),
93 #[cfg(target_os = "macos")]
101 #[cfg(target_os = "macos")]
@@ -99,7 +107,7 @@ pub fn bind_keys(cx: &mut App) {
99 ]);
107 ]);
100}
108}
101
109
102#[derive(Debug, Clone, PartialEq, Eq)]
110#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
103pub struct ReplyPreview {
111pub struct ReplyPreview {
104 pub message_id: String,
112 pub message_id: String,
105 pub author: String,
113 pub author: String,
@@ -110,6 +118,7 @@ pub struct ReplyPreview {
110pub struct EditPreview {
118pub struct EditPreview {
111 pub message_id: String,
119 pub message_id: String,
112 pub excerpt: String,
120 pub excerpt: String,
121 pub scheduled: Option<DateTime<Utc>>,
113}
122}
114
123
115#[derive(Debug, Clone, PartialEq, Eq)]
124#[derive(Debug, Clone, PartialEq, Eq)]
@@ -200,6 +209,10 @@ impl UploadHandle {
200
209
201pub enum ComposerEvent {
210pub enum ComposerEvent {
202 Submit(Box<Outgoing>),
211 Submit(Box<Outgoing>),
212 Schedule {
213 outgoing: Box<Outgoing>,
214 send_at: DateTime<Utc>,
215 },
203 EditLast,
216 EditLast,
204 Typing(bool),
217 Typing(bool),
205}
218}
@@ -279,6 +292,10 @@ pub struct Composer {
279 uploads: HashMap<u64, UploadHandle>,
292 uploads: HashMap<u64, UploadHandle>,
280 demo_failed: HashSet<u64>,
293 demo_failed: HashSet<u64>,
281 carry_images_into: Option<String>,
294 carry_images_into: Option<String>,
295 draft_save: Option<Task<()>>,
296 saved_images: Option<drafts::ImageFingerprint>,
297 schedule: Option<schedule::SchedulePopover>,
298 scheduling: Option<String>,
282 pending_anchors: HashMap<u64, usize>,
299 pending_anchors: HashMap<u64, usize>,
283 link: ComposeLink,
300 link: ComposeLink,
284 fun_picker: Entity<FunPicker>,
301 fun_picker: Entity<FunPicker>,
@@ -471,6 +488,10 @@ impl Composer {
471 uploads: HashMap::new(),
488 uploads: HashMap::new(),
472 demo_failed: HashSet::new(),
489 demo_failed: HashSet::new(),
473 carry_images_into: None,
490 carry_images_into: None,
491 draft_save: None,
492 saved_images: None,
493 schedule: None,
494 scheduling: None,
474 pending_anchors: HashMap::new(),
495 pending_anchors: HashMap::new(),
475 link: ComposeLink::default(),
496 link: ComposeLink::default(),
476 fun_picker,
497 fun_picker,
@@ -491,6 +512,7 @@ impl Composer {
491 self.update_emoji(cx);
512 self.update_emoji(cx);
492 self.update_mention(cx);
513 self.update_mention(cx);
493 self.update_link_preview(cx);
514 self.update_link_preview(cx);
515 self.schedule_draft_save(cx);
494 }
516 }
495 let value = input.read(cx).value();
517 let value = input.read(cx).value();
496 if submitted_text(event, &value).is_some()
518 if submitted_text(event, &value).is_some()
@@ -695,6 +717,7 @@ impl Composer {
695 };
717 };
696 self.apply_to_input(edits, selection, window, cx);
718 self.apply_to_input(edits, selection, window, cx);
697 self.record(StepKind::Other, cx);
719 self.record(StepKind::Other, cx);
720 self.schedule_draft_save(cx);
698 }
721 }
699
722
700 fn apply_to_input(
723 fn apply_to_input(
@@ -822,6 +845,7 @@ impl Composer {
822 self.refresh_style(cx);
845 self.refresh_style(cx);
823 self.update_emoji(cx);
846 self.update_emoji(cx);
824 self.update_mention(cx);
847 self.update_mention(cx);
848 self.schedule_draft_save(cx);
825 cx.notify();
849 cx.notify();
826 }
850 }
827
851
@@ -922,6 +946,7 @@ impl Composer {
922 self.draft.take_edits();
946 self.draft.take_edits();
923 self.record(StepKind::Other, cx);
947 self.record(StepKind::Other, cx);
924 self.refresh_style(cx);
948 self.refresh_style(cx);
949 self.schedule_draft_save(cx);
925 }
950 }
926 cx.notify();
951 cx.notify();
927 }
952 }
@@ -945,6 +970,7 @@ impl Composer {
945 self.draft.take_edits();
970 self.draft.take_edits();
946 self.record(StepKind::Other, cx);
971 self.record(StepKind::Other, cx);
947 self.refresh_style(cx);
972 self.refresh_style(cx);
973 self.schedule_draft_save(cx);
948 }
974 }
949 cx.notify();
975 cx.notify();
950 }
976 }
@@ -1442,6 +1468,9 @@ impl Composer {
1442 ) {
1468 ) {
1443 self.set_placeholder(&format!("Message {name}"), window, cx);
1469 self.set_placeholder(&format!("Message {name}"), window, cx);
1444 if self.conversation_id.as_deref() != Some(conversation_id) {
1470 if self.conversation_id.as_deref() != Some(conversation_id) {
1471 self.save_draft_now(cx);
1472 self.draft_save = None;
1473 self.saved_images = None;
1445 let carry = self.carry_images_into.take().as_deref() == Some(conversation_id);
1474 let carry = self.carry_images_into.take().as_deref() == Some(conversation_id);
1446 self.conversation_id = Some(conversation_id.to_owned());
1475 self.conversation_id = Some(conversation_id.to_owned());
1447 self.cancel_uploads();
1476 self.cancel_uploads();
@@ -1459,6 +1488,10 @@ impl Composer {
1459 }
1488 }
1460 self.mention_inputs.clear();
1489 self.mention_inputs.clear();
1461 self.close_popup();
1490 self.close_popup();
1491 self.schedule = None;
1492 if !carry {
1493 self.load_stored_draft(conversation_id, window, cx);
1494 }
1462 cx.notify();
1495 cx.notify();
1463 }
1496 }
1464 }
1497 }
@@ -1477,6 +1510,7 @@ impl Composer {
1477 if self.reply.is_some() {
1510 if self.reply.is_some() {
1478 self.editing = None;
1511 self.editing = None;
1479 }
1512 }
1513 self.schedule_draft_save(cx);
1480 cx.notify();
1514 cx.notify();
1481 }
1515 }
1482
1516
@@ -1491,10 +1525,11 @@ impl Composer {
1491 }
1525 }
1492
1526
1493 fn outgoing(&self, cx: &App) -> Option<Outgoing> {
1527 fn outgoing(&self, cx: &App) -> Option<Outgoing> {
1528 self.can_send(cx).then(|| self.compose(cx))
1529 }
1530
1531 fn compose(&self, cx: &App) -> Outgoing {
1494 let state = self.input.read(cx);
1532 let state = self.input.read(cx);
1495 if !self.can_send(cx) {
1496 return None;
1497 }
1498 let mut draft = self.current_draft(cx);
1533 let mut draft = self.current_draft(cx);
1499 let image_spans: Vec<(Range<usize>, u64)> = state
1534 let image_spans: Vec<(Range<usize>, u64)> = state
1500 .tokens()
1535 .tokens()
@@ -1529,7 +1564,7 @@ impl Composer {
1529 .filter_map(|span| self.mention_inputs.get(span.token().id().as_ref()))
1564 .filter_map(|span| self.mention_inputs.get(span.token().id().as_ref()))
1530 .cloned()
1565 .cloned()
1531 .collect();
1566 .collect();
1532 Some(Outgoing {
1567 Outgoing {
1533 draft,
1568 draft,
1534 mentions,
1569 mentions,
1535 reply: self.reply.clone(),
1570 reply: self.reply.clone(),
@@ -1545,7 +1580,7 @@ impl Composer {
1545 } else {
1580 } else {
1546 Vec::new()
1581 Vec::new()
1547 },
1582 },
1548 })
1583 }
1549 }
1584 }
1550
1585
1551 /// The draft, or the plain input text while a change is still on its way to the draft.
1586 /// The draft, or the plain input text while a change is still on its way to the draft.
@@ -1992,6 +2027,7 @@ impl Composer {
1992 }
2027 }
1993 let uploaded = self.tray.remove(id);
2028 let uploaded = self.tray.remove(id);
1994 self.discard_uploaded(uploaded.into_iter().collect(), cx);
2029 self.discard_uploaded(uploaded.into_iter().collect(), cx);
2030 self.schedule_draft_save(cx);
1995 cx.notify();
2031 cx.notify();
1996 }
2032 }
1997
2033
@@ -2003,6 +2039,9 @@ impl Composer {
2003 }
2039 }
2004
2040
2005 pub fn submit_current(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2041 pub fn submit_current(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2042 if self.scheduling.is_some() {
2043 return;
2044 }
2006 let Some(outgoing) = self.outgoing(cx) else {
2045 let Some(outgoing) = self.outgoing(cx) else {
2007 return;
2046 return;
2008 };
2047 };
@@ -2011,6 +2050,7 @@ impl Composer {
2011 self.mention_inputs.clear();
2050 self.mention_inputs.clear();
2012 if self.editing.is_none() {
2051 if self.editing.is_none() {
2013 self.tray.clear();
2052 self.tray.clear();
2053 self.clear_stored_draft(cx);
2014 }
2054 }
2015 self.reply = None;
2055 self.reply = None;
2016 self.editing = None;
2056 self.editing = None;
@@ -2057,6 +2097,7 @@ impl Composer {
2057 self.editing = outgoing.edit.clone();
2097 self.editing = outgoing.edit.clone();
2058 self.link.restore(outgoing.link_preview.clone());
2098 self.link.restore(outgoing.link_preview.clone());
2059 self.close_popup();
2099 self.close_popup();
2100 self.schedule_draft_save(cx);
2060 cx.notify();
2101 cx.notify();
2061 }
2102 }
2062
2103
@@ -2294,7 +2335,10 @@ impl Composer {
2294 .bg(theme::surface())
2335 .bg(theme::surface())
2295 .border_1()
2336 .border_1()
2296 .border_color(theme::border())
2337 .border_color(theme::border())
2297 .child(icon(IconName::Pencil, 14., theme::accent_text()))
2338 .child(match edit.scheduled {
2339 Some(_) => symbol("schedule_send", 14., theme::accent_text()).into_any_element(),
2340 None => icon(IconName::Pencil, 14., theme::accent_text()).into_any_element(),
2341 })
2298 .child(
2342 .child(
2299 v_flex()
2343 v_flex()
2300 .flex_1()
2344 .flex_1()
@@ -2305,7 +2349,13 @@ impl Composer {
2305 .text_size(px(12.))
2349 .text_size(px(12.))
2306 .font_weight(FontWeight::SEMIBOLD)
2350 .font_weight(FontWeight::SEMIBOLD)
2307 .text_color(theme::accent_text())
2351 .text_color(theme::accent_text())
2308 .child("Editing message"),
2352 .child(match edit.scheduled {
2353 Some(send_at) => format!(
2354 "Editing scheduled message - {}",
2355 scheduled_label(send_at, Utc::now())
2356 ),
2357 None => "Editing message".to_owned(),
2358 }),
2309 )
2359 )
2310 .child(
2360 .child(
2311 div()
2361 div()
@@ -2398,6 +2448,10 @@ impl Render for Composer {
2398 .justify_center()
2448 .justify_center()
2399 .rounded(px(8.))
2449 .rounded(px(8.))
2400 .child(symbol("keyboard_return", 20., white()))
2450 .child(symbol("keyboard_return", 20., white()))
2451 .on_mouse_down(
2452 MouseButton::Right,
2453 cx.listener(|this, _, _, cx| this.open_schedule_menu(cx)),
2454 )
2401 .when(!can_send, |button| button.opacity(0.4))
2455 .when(!can_send, |button| button.opacity(0.4))
2402 .when(can_send, |button| {
2456 .when(can_send, |button| {
2403 button
2457 button
@@ -2554,6 +2608,7 @@ impl Render for Composer {
2554 }
2608 }
2555 }))
2609 }))
2556 .on_action(cx.listener(|this, _: &EditLink, window, cx| this.edit_link(window, cx)))
2610 .on_action(cx.listener(|this, _: &EditLink, window, cx| this.edit_link(window, cx)))
2611 .on_action(cx.listener(|this, _: &ScheduleSend, _, cx| this.open_schedule_picker(cx)))
2557 .capture_action(cx.listener(|this, _: &Undo, window, cx| {
2612 .capture_action(cx.listener(|this, _: &Undo, window, cx| {
2558 if this.link_editor.is_none() {
2613 if this.link_editor.is_none() {
2559 this.step_history(true, window, cx);
2614 this.step_history(true, window, cx);
@@ -2578,8 +2633,11 @@ impl Render for Composer {
2578 cx.stop_propagation();
2633 cx.stop_propagation();
2579 }
2634 }
2580 }))
2635 }))
2581 .capture_action(cx.listener(|this, _: &MoveUp, _, cx| {
2636 .capture_action(cx.listener(|this, _: &MoveUp, window, cx| {
2582 if this.link_editor.is_some() {
2637 if this.link_editor.is_some() {
2638 } else if this.schedule.is_some() {
2639 this.move_schedule_highlight(-1, window, cx);
2640 cx.stop_propagation();
2583 } else if this.popup_is_open() {
2641 } else if this.popup_is_open() {
2584 this.move_highlight(-1, cx);
2642 this.move_highlight(-1, cx);
2585 cx.stop_propagation();
2643 cx.stop_propagation();
@@ -2588,8 +2646,12 @@ impl Render for Composer {
2588 cx.stop_propagation();
2646 cx.stop_propagation();
2589 }
2647 }
2590 }))
2648 }))
2591 .capture_action(cx.listener(|this, _: &MoveDown, _, cx| {
2649 .capture_action(cx.listener(|this, _: &MoveDown, window, cx| {
2592 if this.link_editor.is_none() && this.popup_is_open() {
2650 if this.link_editor.is_some() {
2651 } else if this.schedule.is_some() {
2652 this.move_schedule_highlight(1, window, cx);
2653 cx.stop_propagation();
2654 } else if this.popup_is_open() {
2593 this.move_highlight(1, cx);
2655 this.move_highlight(1, cx);
2594 cx.stop_propagation();
2656 cx.stop_propagation();
2595 }
2657 }
@@ -2598,6 +2660,9 @@ impl Render for Composer {
2598 if this.link_editor.is_some() {
2660 if this.link_editor.is_some() {
2599 this.apply_link(window, cx);
2661 this.apply_link(window, cx);
2600 cx.stop_propagation();
2662 cx.stop_propagation();
2663 } else if this.schedule.is_some() {
2664 this.activate_schedule_row(window, cx);
2665 cx.stop_propagation();
2601 } else if this.popup_is_open() {
2666 } else if this.popup_is_open() {
2602 this.accept_popup(window, cx);
2667 this.accept_popup(window, cx);
2603 cx.stop_propagation();
2668 cx.stop_propagation();
@@ -2632,6 +2697,11 @@ impl Render for Composer {
2632 }
2697 }
2633 }))
2698 }))
2634 .capture_action(cx.listener(|this, _: &Escape, window, cx| {
2699 .capture_action(cx.listener(|this, _: &Escape, window, cx| {
2700 if this.schedule.is_some() {
2701 this.close_schedule(window, cx);
2702 cx.stop_propagation();
2703 return;
2704 }
2635 if this.link_editor.is_some() {
2705 if this.link_editor.is_some() {
2636 this.close_link_editor(window, cx);
2706 this.close_link_editor(window, cx);
2637 cx.stop_propagation();
2707 cx.stop_propagation();
@@ -2666,6 +2736,7 @@ impl Render for Composer {
2666 .children(self.render_popup(cx))
2736 .children(self.render_popup(cx))
2667 .children(self.render_emoji_popup(window, cx))
2737 .children(self.render_emoji_popup(window, cx))
2668 .children(self.render_toolbar(focused, cx))
2738 .children(self.render_toolbar(focused, cx))
2739 .children(self.render_schedule(cx))
2669 .child(
2740 .child(
2670 v_flex()
2741 v_flex()
2671 .relative()
2742 .relative()
@@ -3934,6 +4005,7 @@ mod tests {
3934 edit: Some(EditPreview {
4005 edit: Some(EditPreview {
3935 message_id: "m1".into(),
4006 message_id: "m1".into(),
3936 excerpt: "old".into(),
4007 excerpt: "old".into(),
4008 scheduled: None,
3937 }),
4009 }),
3938 images: Vec::new(),
4010 images: Vec::new(),
3939 files: Vec::new(),
4011 files: Vec::new(),
@@ -3991,6 +4063,95 @@ mod tests {
3991 }
4063 }
3992 }
4064 }
3993
4065
4066 #[gpui_kit::test]
4067 fn each_conversation_keeps_its_own_draft(cx: &mut TestAppContext) {
4068 let (handle, composer) = demo_composer(cx);
4069 cx.update_window(handle, |_, window, cx| {
4070 composer.update(cx, |composer, cx| {
4071 composer.set_conversation("chat-a", "A", window, cx);
4072 composer.set_text("**hello** there", window, cx);
4073 composer.set_conversation("chat-b", "B", window, cx);
4074 });
4075 })
4076 .unwrap();
4077 cx.update(|cx| {
4078 let composer = composer.read(cx);
4079 assert!(composer.draft.is_blank());
4080 let stored = composer
4081 .app
4082 .read(cx)
4083 .store
4084 .draft("chat-a")
4085 .unwrap()
4086 .unwrap();
4087 assert_eq!(stored.preview, "hello there");
4088 });
4089 cx.update_window(handle, |_, window, cx| {
4090 composer.update(cx, |composer, cx| {
4091 composer.set_text("other", window, cx);
4092 composer.set_conversation("chat-a", "A", window, cx);
4093 });
4094 })
4095 .unwrap();
4096 cx.update(|cx| {
4097 let composer = composer.read(cx);
4098 assert_eq!(composer.draft.text(), "hello there");
4099 assert!(composer.draft.to_html().contains("<b>"));
4100 assert!(
4101 composer
4102 .app
4103 .read(cx)
4104 .store
4105 .draft("chat-b")
4106 .unwrap()
4107 .is_some()
4108 );
4109 });
4110 }
4111
4112 #[gpui_kit::test]
4113 fn sending_clears_the_stored_draft_and_a_blank_composer_deletes_it(
4114 cx: &mut TestAppContext,
4115 ) {
4116 let (handle, composer) = demo_composer(cx);
4117 cx.update_window(handle, |_, window, cx| {
4118 composer.update(cx, |composer, cx| {
4119 composer.set_conversation("chat-a", "A", window, cx);
4120 composer.set_text("hi", window, cx);
4121 composer.save_draft_now(cx);
4122 });
4123 })
4124 .unwrap();
4125 cx.update(|cx| {
4126 assert!(
4127 composer
4128 .read(cx)
4129 .app
4130 .read(cx)
4131 .store
4132 .draft("chat-a")
4133 .unwrap()
4134 .is_some()
4135 );
4136 });
4137 cx.update_window(handle, |_, window, cx| {
4138 composer.update(cx, |composer, cx| composer.submit_current(window, cx));
4139 })
4140 .unwrap();
4141 cx.update(|cx| {
4142 assert!(
4143 composer
4144 .read(cx)
4145 .app
4146 .read(cx)
4147 .store
4148 .draft("chat-a")
4149 .unwrap()
4150 .is_none()
4151 );
4152 });
4153 }
4154
3994 #[gpui_kit::test]
4155 #[gpui_kit::test]
3995 fn a_draft_target_change_drops_the_files_of_the_old_target_and_keeps_images(
4156 fn a_draft_target_change_drops_the_files_of_the_old_target_and_keeps_images(
3996 cx: &mut TestAppContext,
4157 cx: &mut TestAppContext,
crates/app/src/views/composer/drafts.rs added +133 −0
@@ -0,0 +1,133 @@
1 use std::time::Duration;
2
3 use gpui_kit::component::input::InputContent;
4 use gpui_kit::*;
5 use store::{AttachmentImage, DraftRecord};
6 use teams_core::Draft;
7
8 use super::{Composer, Outgoing};
9 use crate::notice::truncated;
10 use crate::stored_outgoing::{decode, encode};
11
12 const DRAFT_SAVE_DELAY: Duration = Duration::from_millis(500);
13 const DRAFT_PREVIEW_CHARS: usize = 200;
14 const IMAGE_ONLY_PREVIEW: &str = "Image";
15
16 pub(super) type ImageFingerprint = (String, Vec<(String, usize, Option<u32>, Option<u32>)>);
17
18 fn fingerprint(conversation_id: &str, images: &[AttachmentImage]) -> ImageFingerprint {
19 let images = images
20 .iter()
21 .map(|image| {
22 (
23 image.name.clone(),
24 image.bytes.len(),
25 image.width,
26 image.height,
27 )
28 })
29 .collect();
30 (conversation_id.to_owned(), images)
31 }
32
33 fn draft_preview(outgoing: &Outgoing) -> String {
34 let text = outgoing
35 .text()
36 .split_whitespace()
37 .collect::<Vec<_>>()
38 .join(" ");
39 if text.is_empty() {
40 return IMAGE_ONLY_PREVIEW.to_owned();
41 }
42 truncated(&text, DRAFT_PREVIEW_CHARS)
43 }
44
45 impl Composer {
46 pub(super) fn schedule_draft_save(&mut self, cx: &mut Context<Self>) {
47 self.draft_save = Some(cx.spawn(async move |this, cx| {
48 cx.background_executor().timer(DRAFT_SAVE_DELAY).await;
49 this.update(cx, |composer, cx| composer.save_draft_now(cx))
50 .ok();
51 }));
52 }
53
54 fn storable_conversation(&self) -> Option<String> {
55 self.conversation_id
56 .clone()
57 .filter(|conversation_id| !conversation_id.is_empty())
58 .filter(|_| self.editing.is_none())
59 }
60
61 fn storable_draft(&self, cx: &App) -> Option<Outgoing> {
62 let mut outgoing = self.compose(cx);
63 outgoing.files.clear();
64 (!outgoing.draft.is_blank() || !outgoing.images.is_empty()).then_some(outgoing)
65 }
66
67 pub fn save_draft_now(&mut self, cx: &mut Context<Self>) {
68 let Some(conversation_id) = self.storable_conversation() else {
69 return;
70 };
71 let store = self.app.read(cx).store.clone();
72 let stored = self
73 .storable_draft(cx)
74 .and_then(|outgoing| Some((draft_preview(&outgoing), encode(&outgoing)?)));
75 match stored {
76 Some((preview, stored)) => {
77 let current = fingerprint(&conversation_id, &stored.images);
78 let unchanged = self.saved_images.as_ref() == Some(&current);
79 let record = DraftRecord {
80 conversation_id,
81 payload: stored.payload,
82 preview,
83 images: stored.images,
84 updated_at: chrono::Utc::now(),
85 };
86 let saved = if unchanged {
87 store.save_draft_text(&record)
88 } else {
89 store.save_draft(&record)
90 };
91 self.saved_images = saved.is_ok().then_some(current);
92 }
93 None => {
94 self.saved_images = None;
95 store.delete_draft(&conversation_id).ok();
96 }
97 }
98 self.app
99 .update(cx, |state, cx| state.refresh_local_previews(cx));
100 }
101
102 pub(super) fn clear_stored_draft(&mut self, cx: &mut Context<Self>) {
103 self.draft_save = None;
104 self.saved_images = None;
105 let Some(conversation_id) = self.storable_conversation() else {
106 return;
107 };
108 self.app.read(cx).store.delete_draft(&conversation_id).ok();
109 self.app
110 .update(cx, |state, cx| state.refresh_local_previews(cx));
111 }
112
113 pub(super) fn load_stored_draft(
114 &mut self,
115 conversation_id: &str,
116 window: &mut Window,
117 cx: &mut Context<Self>,
118 ) {
119 let stored = Some(conversation_id)
120 .filter(|conversation_id| !conversation_id.is_empty())
121 .and_then(|conversation_id| self.app.read(cx).store.draft(conversation_id).ok())
122 .flatten()
123 .and_then(|record| decode(&record.payload, &record.images));
124 match stored {
125 Some(outgoing) => self.restore(&outgoing, window, cx),
126 None => {
127 self.mention_inputs.clear();
128 self.load_draft(Draft::default(), InputContent::new(""), window, cx);
129 }
130 }
131 self.draft_save = None;
132 }
133 }
@@ -0,0 +1,133 @@
1use std::time::Duration;
2
3use gpui_kit::component::input::InputContent;
4use gpui_kit::*;
5use store::{AttachmentImage, DraftRecord};
6use teams_core::Draft;
7
8use super::{Composer, Outgoing};
9use crate::notice::truncated;
10use crate::stored_outgoing::{decode, encode};
11
12const DRAFT_SAVE_DELAY: Duration = Duration::from_millis(500);
13const DRAFT_PREVIEW_CHARS: usize = 200;
14const IMAGE_ONLY_PREVIEW: &str = "Image";
15
16pub(super) type ImageFingerprint = (String, Vec<(String, usize, Option<u32>, Option<u32>)>);
17
18fn fingerprint(conversation_id: &str, images: &[AttachmentImage]) -> ImageFingerprint {
19 let images = images
20 .iter()
21 .map(|image| {
22 (
23 image.name.clone(),
24 image.bytes.len(),
25 image.width,
26 image.height,
27 )
28 })
29 .collect();
30 (conversation_id.to_owned(), images)
31}
32
33fn draft_preview(outgoing: &Outgoing) -> String {
34 let text = outgoing
35 .text()
36 .split_whitespace()
37 .collect::<Vec<_>>()
38 .join(" ");
39 if text.is_empty() {
40 return IMAGE_ONLY_PREVIEW.to_owned();
41 }
42 truncated(&text, DRAFT_PREVIEW_CHARS)
43}
44
45impl Composer {
46 pub(super) fn schedule_draft_save(&mut self, cx: &mut Context<Self>) {
47 self.draft_save = Some(cx.spawn(async move |this, cx| {
48 cx.background_executor().timer(DRAFT_SAVE_DELAY).await;
49 this.update(cx, |composer, cx| composer.save_draft_now(cx))
50 .ok();
51 }));
52 }
53
54 fn storable_conversation(&self) -> Option<String> {
55 self.conversation_id
56 .clone()
57 .filter(|conversation_id| !conversation_id.is_empty())
58 .filter(|_| self.editing.is_none())
59 }
60
61 fn storable_draft(&self, cx: &App) -> Option<Outgoing> {
62 let mut outgoing = self.compose(cx);
63 outgoing.files.clear();
64 (!outgoing.draft.is_blank() || !outgoing.images.is_empty()).then_some(outgoing)
65 }
66
67 pub fn save_draft_now(&mut self, cx: &mut Context<Self>) {
68 let Some(conversation_id) = self.storable_conversation() else {
69 return;
70 };
71 let store = self.app.read(cx).store.clone();
72 let stored = self
73 .storable_draft(cx)
74 .and_then(|outgoing| Some((draft_preview(&outgoing), encode(&outgoing)?)));
75 match stored {
76 Some((preview, stored)) => {
77 let current = fingerprint(&conversation_id, &stored.images);
78 let unchanged = self.saved_images.as_ref() == Some(&current);
79 let record = DraftRecord {
80 conversation_id,
81 payload: stored.payload,
82 preview,
83 images: stored.images,
84 updated_at: chrono::Utc::now(),
85 };
86 let saved = if unchanged {
87 store.save_draft_text(&record)
88 } else {
89 store.save_draft(&record)
90 };
91 self.saved_images = saved.is_ok().then_some(current);
92 }
93 None => {
94 self.saved_images = None;
95 store.delete_draft(&conversation_id).ok();
96 }
97 }
98 self.app
99 .update(cx, |state, cx| state.refresh_local_previews(cx));
100 }
101
102 pub(super) fn clear_stored_draft(&mut self, cx: &mut Context<Self>) {
103 self.draft_save = None;
104 self.saved_images = None;
105 let Some(conversation_id) = self.storable_conversation() else {
106 return;
107 };
108 self.app.read(cx).store.delete_draft(&conversation_id).ok();
109 self.app
110 .update(cx, |state, cx| state.refresh_local_previews(cx));
111 }
112
113 pub(super) fn load_stored_draft(
114 &mut self,
115 conversation_id: &str,
116 window: &mut Window,
117 cx: &mut Context<Self>,
118 ) {
119 let stored = Some(conversation_id)
120 .filter(|conversation_id| !conversation_id.is_empty())
121 .and_then(|conversation_id| self.app.read(cx).store.draft(conversation_id).ok())
122 .flatten()
123 .and_then(|record| decode(&record.payload, &record.images));
124 match stored {
125 Some(outgoing) => self.restore(&outgoing, window, cx),
126 None => {
127 self.mention_inputs.clear();
128 self.load_draft(Draft::default(), InputContent::new(""), window, cx);
129 }
130 }
131 self.draft_save = None;
132 }
133}
crates/app/src/views/composer/schedule.rs added +485 −0
@@ -0,0 +1,485 @@
1 use chrono::{DateTime, Local, Utc};
2 use gpui_kit::component::input::{Input, InputEvent, InputState};
3 use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
4 use gpui_kit::prelude::FluentBuilder as _;
5 use gpui_kit::*;
6 use teams_core::NOTES_CHAT_ID;
7
8 use super::{Composer, ComposerEvent};
9 use crate::schedule_time::{
10 DayChoice, Preset, PresetKind, ScheduleError, custom_time, day_choices, default_custom_time,
11 format_time, parse_time, presets, step_time, validate,
12 };
13 use crate::theme;
14 use crate::views::widgets::symbol;
15
16 const MENU_WIDTH: f32 = 190.;
17 const PICKER_WIDTH: f32 = 300.;
18 const ROW_HEIGHT: f32 = 32.;
19 const ICON_SIZE: f32 = 18.;
20 const DISABLED_OPACITY: f32 = 0.4;
21 const TIME_FIELD_WIDTH: f32 = 84.;
22 const BAD_TIME: &str = "Enter a time like 14:30.";
23
24 pub(super) enum Stage {
25 Menu,
26 Picker,
27 }
28
29 pub(super) struct CustomForm {
30 day_index: usize,
31 time_field: Entity<InputState>,
32 _edits: Subscription,
33 }
34
35 pub(super) struct SchedulePopover {
36 stage: Stage,
37 presets: Vec<Preset>,
38 highlighted: usize,
39 custom: Option<CustomForm>,
40 }
41
42 impl SchedulePopover {
43 fn custom_index(&self) -> usize {
44 self.presets.len()
45 }
46 }
47
48 fn preset_glyph(kind: PresetKind) -> &'static str {
49 match kind {
50 PresetKind::LaterToday => "schedule",
51 PresetKind::TomorrowMorning => "wb_sunny",
52 PresetKind::MondayMorning => "work",
53 }
54 }
55
56 fn menu_row(id: ElementId, highlighted: bool) -> Stateful<Div> {
57 h_flex()
58 .id(id)
59 .h(px(ROW_HEIGHT))
60 .px(px(10.))
61 .gap(px(10.))
62 .items_center()
63 .rounded(px(6.))
64 .text_size(px(13.))
65 .text_color(theme::text())
66 .cursor_pointer()
67 .when(highlighted, |row| row.bg(theme::row_hover()))
68 .hover(|row| row.bg(theme::row_hover()))
69 }
70
71 impl Composer {
72 pub(super) fn schedule_blocker(&self, cx: &App) -> Option<&'static str> {
73 let state = self.app.read(cx);
74 let conversation_id = self.conversation_id.as_deref().unwrap_or_default();
75 let outgoing = self.compose(cx);
76 if state.mode.read_only && !state.mode.demo {
77 Some("Read-only mode")
78 } else if conversation_id == NOTES_CHAT_ID {
79 Some("Not available in your notes")
80 } else if conversation_id.is_empty() {
81 Some("Not available in a new chat yet")
82 } else if self.editing.is_some() {
83 Some("Can't schedule while editing")
84 } else if !outgoing.mentions.is_empty() {
85 Some("Can't schedule messages with mentions yet")
86 } else if outgoing.has_attachments() || self.has_attachments(cx) {
87 Some("Can't schedule messages with images or files yet")
88 } else if self.reply.is_some() {
89 Some("Can't schedule replies yet")
90 } else if self.current_draft(cx).is_blank() {
91 Some("Nothing to schedule yet")
92 } else {
93 None
94 }
95 }
96
97 pub(super) fn open_schedule_menu(&mut self, cx: &mut Context<Self>) {
98 self.schedule = Some(SchedulePopover {
99 stage: Stage::Menu,
100 presets: Vec::new(),
101 highlighted: 0,
102 custom: None,
103 });
104 cx.notify();
105 }
106
107 pub(super) fn open_schedule_picker(&mut self, cx: &mut Context<Self>) {
108 if self.schedule_blocker(cx).is_some() || self.scheduling.is_some() {
109 self.open_schedule_menu(cx);
110 return;
111 }
112 self.schedule = Some(SchedulePopover {
113 stage: Stage::Picker,
114 presets: presets(Local::now()),
115 highlighted: 0,
116 custom: None,
117 });
118 cx.notify();
119 }
120
121 pub(super) fn close_schedule(&mut self, window: &mut Window, cx: &mut Context<Self>) {
122 if self.schedule.take().is_some() {
123 self.focus(window, cx);
124 cx.notify();
125 }
126 }
127
128 pub(super) fn move_schedule_highlight(
129 &mut self,
130 delta: isize,
131 window: &mut Window,
132 cx: &mut Context<Self>,
133 ) {
134 let Some(popover) = self.schedule.as_mut() else {
135 return;
136 };
137 if !matches!(popover.stage, Stage::Picker) {
138 return;
139 }
140 if popover.custom.is_some() {
141 self.step_custom_time(delta, window, cx);
142 return;
143 }
144 let count = popover.presets.len() + 1;
145 popover.highlighted =
146 (popover.highlighted as isize + delta).rem_euclid(count as isize) as usize;
147 cx.notify();
148 }
149
150 pub(super) fn activate_schedule_row(&mut self, window: &mut Window, cx: &mut Context<Self>) {
151 let Some(popover) = self.schedule.as_ref() else {
152 return;
153 };
154 let highlighted = popover.highlighted;
155 let on_custom_row = highlighted == popover.custom_index();
156 let custom_open = popover.custom.is_some();
157 match popover.stage {
158 Stage::Menu => {
159 if self.schedule_blocker(cx).is_none() {
160 self.open_schedule_picker(cx);
161 }
162 }
163 Stage::Picker if custom_open => self.confirm_custom(window, cx),
164 Stage::Picker if on_custom_row => self.expand_custom(window, cx),
165 Stage::Picker => self.schedule_preset(highlighted, window, cx),
166 }
167 }
168
169 fn schedule_preset(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
170 let Some(preset) = self
171 .schedule
172 .as_ref()
173 .and_then(|popover| popover.presets.get(index))
174 else {
175 return;
176 };
177 let at = preset.at;
178 if validate(at, Local::now()).is_err() {
179 if let Some(popover) = self.schedule.as_mut() {
180 popover.presets = presets(Local::now());
181 popover.highlighted = 0;
182 }
183 cx.notify();
184 return;
185 }
186 self.schedule_at(at, window, cx);
187 }
188
189 fn expand_custom(&mut self, window: &mut Window, cx: &mut Context<Self>) {
190 let time = format_time(default_custom_time(Local::now()));
191 let time_field = cx.new(|cx| {
192 InputState::new(window, cx)
193 .placeholder("HH:MM")
194 .default_value(time)
195 });
196 time_field.update(cx, |field, cx| {
197 field.focus(window, cx);
198 field.select_all(window, cx);
199 });
200 let edits = cx.subscribe(&time_field, |_, _, event: &InputEvent, cx| {
201 if matches!(event, InputEvent::Change) {
202 cx.notify();
203 }
204 });
205 if let Some(popover) = self.schedule.as_mut() {
206 popover.custom = Some(CustomForm {
207 day_index: 0,
208 time_field,
209 _edits: edits,
210 });
211 }
212 cx.notify();
213 }
214
215 fn step_custom_time(&mut self, steps: isize, window: &mut Window, cx: &mut Context<Self>) {
216 let Some(field) = self
217 .schedule
218 .as_ref()
219 .and_then(|popover| popover.custom.as_ref())
220 .map(|custom| custom.time_field.clone())
221 else {
222 return;
223 };
224 let current = parse_time(&field.read(cx).value()).unwrap_or_default();
225 let stepped = format_time(step_time(current, -(steps as i32)));
226 field.update(cx, |field, cx| field.set_value(&stepped, window, cx));
227 }
228
229 fn custom_choice(&self, cx: &App) -> Result<DateTime<Local>, &'static str> {
230 let custom = self
231 .schedule
232 .as_ref()
233 .and_then(|popover| popover.custom.as_ref())
234 .ok_or(BAD_TIME)?;
235 let now = Local::now();
236 let day = day_choices(now.date_naive())
237 .get(custom.day_index)
238 .map(|choice| choice.date)
239 .ok_or(BAD_TIME)?;
240 let at = custom_time(day, &custom.time_field.read(cx).value()).ok_or(BAD_TIME)?;
241 validate(at, now).map_err(ScheduleError::message)?;
242 Ok(at)
243 }
244
245 fn confirm_custom(&mut self, window: &mut Window, cx: &mut Context<Self>) {
246 if let Ok(at) = self.custom_choice(cx) {
247 self.schedule_at(at, window, cx);
248 }
249 }
250
251 fn schedule_at(&mut self, at: DateTime<Local>, window: &mut Window, cx: &mut Context<Self>) {
252 if self.scheduling.is_some() || self.schedule_blocker(cx).is_some() {
253 return;
254 }
255 let outgoing = self.compose(cx);
256 self.scheduling = Some(outgoing.html());
257 self.close_schedule(window, cx);
258 cx.emit(ComposerEvent::Schedule {
259 outgoing: Box::new(outgoing),
260 send_at: at.with_timezone(&Utc),
261 });
262 }
263
264 pub fn finish_schedule(
265 &mut self,
266 conversation_id: &str,
267 window: &mut Window,
268 cx: &mut Context<Self>,
269 ) {
270 let scheduled = self.scheduling.take();
271 if self.conversation_id.as_deref() != Some(conversation_id) {
272 self.app.read(cx).store.delete_draft(conversation_id).ok();
273 self.app
274 .update(cx, |state, cx| state.refresh_local_previews(cx));
275 return;
276 }
277 if scheduled.as_deref() != Some(self.compose(cx).html().as_str()) {
278 return;
279 }
280 self.load_draft(
281 teams_core::Draft::default(),
282 gpui_kit::component::input::InputContent::new(""),
283 window,
284 cx,
285 );
286 self.mention_inputs.clear();
287 self.tray.clear();
288 self.clear_stored_draft(cx);
289 self.reply = None;
290 self.close_popup();
291 cx.notify();
292 }
293
294 pub fn fail_schedule(&mut self, cx: &mut Context<Self>) {
295 self.scheduling = None;
296 cx.notify();
297 }
298
299 pub(super) fn render_schedule(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
300 let popover = self.schedule.as_ref()?;
301 let body = match popover.stage {
302 Stage::Menu => self.render_schedule_menu(cx),
303 Stage::Picker => self.render_schedule_picker(popover, cx),
304 };
305 Some(
306 v_flex()
307 .id("schedule-popover")
308 .absolute()
309 .bottom(relative(1.))
310 .right_0()
311 .mb(px(6.))
312 .w(px(match popover.stage {
313 Stage::Menu => MENU_WIDTH,
314 Stage::Picker => PICKER_WIDTH,
315 }))
316 .p(px(4.))
317 .rounded(px(8.))
318 .border_1()
319 .border_color(theme::border_strong())
320 .bg(theme::surface_raised())
321 .shadow_lg()
322 .occlude()
323 .on_mouse_down_out(
324 cx.listener(|this, _, window, cx| this.close_schedule(window, cx)),
325 )
326 .child(body)
327 .into_any_element(),
328 )
329 }
330
331 fn render_schedule_menu(&self, cx: &mut Context<Self>) -> Div {
332 let blocker = self.schedule_blocker(cx);
333 let row = menu_row("schedule-send-entry".into(), true)
334 .child(symbol("schedule_send", ICON_SIZE, theme::text_soft()))
335 .child("Schedule send");
336 let row = match blocker {
337 Some(reason) => row
338 .opacity(DISABLED_OPACITY)
339 .cursor_default()
340 .tooltip(move |window, cx| Tooltip::new(reason).build(window, cx)),
341 None => row.on_click(cx.listener(|this, _, _, cx| this.open_schedule_picker(cx))),
342 };
343 v_flex().child(row)
344 }
345
346 fn render_schedule_picker(&self, popover: &SchedulePopover, cx: &mut Context<Self>) -> Div {
347 let mut list = v_flex();
348 for (index, preset) in popover.presets.iter().enumerate() {
349 list = list.child(
350 menu_row(
351 ElementId::Name(format!("schedule-preset-{index}").into()),
352 index == popover.highlighted && popover.custom.is_none(),
353 )
354 .child(symbol(
355 preset_glyph(preset.kind),
356 ICON_SIZE,
357 theme::text_soft(),
358 ))
359 .child(div().flex_1().child(preset.label))
360 .child(
361 div()
362 .text_size(px(12.))
363 .text_color(theme::text_faint())
364 .child(preset.time_label.clone()),
365 )
366 .on_click(
367 cx.listener(move |this, _, window, cx| this.schedule_preset(index, window, cx)),
368 ),
369 );
370 }
371 list = list
372 .child(
373 div()
374 .h(px(1.))
375 .mx(px(6.))
376 .my(px(4.))
377 .bg(theme::border_strong()),
378 )
379 .child(
380 menu_row(
381 "schedule-custom".into(),
382 popover.highlighted == popover.custom_index() && popover.custom.is_none(),
383 )
384 .child(symbol("event", ICON_SIZE, theme::text_soft()))
385 .child("Custom...")
386 .on_click(cx.listener(|this, _, window, cx| this.expand_custom(window, cx))),
387 );
388 if let Some(custom) = popover.custom.as_ref() {
389 list = list.child(self.render_custom_form(custom, cx));
390 }
391 list
392 }
393
394 fn render_custom_form(&self, custom: &CustomForm, cx: &mut Context<Self>) -> Div {
395 let choice = self.custom_choice(cx);
396 let days: Vec<DayChoice> = day_choices(Local::now().date_naive());
397 let chips = days.into_iter().enumerate().map(|(index, day)| {
398 let selected = index == custom.day_index;
399 div()
400 .id(ElementId::Name(format!("schedule-day-{index}").into()))
401 .h(px(26.))
402 .px(px(8.))
403 .flex()
404 .items_center()
405 .rounded(px(6.))
406 .border_1()
407 .border_color(if selected {
408 theme::accent()
409 } else {
410 theme::border_strong()
411 })
412 .text_size(px(12.))
413 .cursor_pointer()
414 .when(selected, |chip| {
415 chip.bg(theme::accent()).text_color(theme::on_accent())
416 })
417 .when(!selected, |chip| {
418 chip.text_color(theme::text_soft())
419 .hover(|chip| chip.bg(theme::row_hover()))
420 })
421 .child(day.label)
422 .on_click(cx.listener(move |this, _, _, cx| {
423 if let Some(form) = this
424 .schedule
425 .as_mut()
426 .and_then(|popover| popover.custom.as_mut())
427 {
428 form.day_index = index;
429 }
430 cx.notify();
431 }))
432 });
433 let valid = choice.is_ok();
434 v_flex()
435 .gap(px(8.))
436 .p(px(10.))
437 .child(h_flex().flex_wrap().gap(px(6.)).children(chips))
438 .child(
439 h_flex()
440 .gap(px(10.))
441 .items_center()
442 .child(
443 div()
444 .w(px(TIME_FIELD_WIDTH))
445 .h(px(28.))
446 .rounded(px(6.))
447 .border_1()
448 .border_color(theme::accent())
449 .bg(theme::surface())
450 .child(
451 Input::new(&custom.time_field)
452 .appearance(false)
453 .bordered(false),
454 ),
455 )
456 .child(div().flex_1())
457 .child(
458 div()
459 .id("schedule-confirm")
460 .h(px(30.))
461 .px(px(14.))
462 .flex()
463 .items_center()
464 .rounded(px(6.))
465 .bg(theme::accent())
466 .text_color(theme::on_accent())
467 .text_size(px(13.))
468 .font_weight(FontWeight::SEMIBOLD)
469 .child("Schedule")
470 .when(!valid, |button| button.opacity(DISABLED_OPACITY))
471 .when(valid, |button| {
472 button.cursor_pointer().on_click(cx.listener(
473 |this, _, window, cx| this.confirm_custom(window, cx),
474 ))
475 }),
476 ),
477 )
478 .children(choice.err().map(|message| {
479 div()
480 .text_size(px(12.))
481 .text_color(theme::red_soft())
482 .child(message)
483 }))
484 }
485 }
@@ -0,0 +1,485 @@
1use chrono::{DateTime, Local, Utc};
2use gpui_kit::component::input::{Input, InputEvent, InputState};
3use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
4use gpui_kit::prelude::FluentBuilder as _;
5use gpui_kit::*;
6use teams_core::NOTES_CHAT_ID;
7
8use super::{Composer, ComposerEvent};
9use crate::schedule_time::{
10 DayChoice, Preset, PresetKind, ScheduleError, custom_time, day_choices, default_custom_time,
11 format_time, parse_time, presets, step_time, validate,
12};
13use crate::theme;
14use crate::views::widgets::symbol;
15
16const MENU_WIDTH: f32 = 190.;
17const PICKER_WIDTH: f32 = 300.;
18const ROW_HEIGHT: f32 = 32.;
19const ICON_SIZE: f32 = 18.;
20const DISABLED_OPACITY: f32 = 0.4;
21const TIME_FIELD_WIDTH: f32 = 84.;
22const BAD_TIME: &str = "Enter a time like 14:30.";
23
24pub(super) enum Stage {
25 Menu,
26 Picker,
27}
28
29pub(super) struct CustomForm {
30 day_index: usize,
31 time_field: Entity<InputState>,
32 _edits: Subscription,
33}
34
35pub(super) struct SchedulePopover {
36 stage: Stage,
37 presets: Vec<Preset>,
38 highlighted: usize,
39 custom: Option<CustomForm>,
40}
41
42impl SchedulePopover {
43 fn custom_index(&self) -> usize {
44 self.presets.len()
45 }
46}
47
48fn preset_glyph(kind: PresetKind) -> &'static str {
49 match kind {
50 PresetKind::LaterToday => "schedule",
51 PresetKind::TomorrowMorning => "wb_sunny",
52 PresetKind::MondayMorning => "work",
53 }
54}
55
56fn menu_row(id: ElementId, highlighted: bool) -> Stateful<Div> {
57 h_flex()
58 .id(id)
59 .h(px(ROW_HEIGHT))
60 .px(px(10.))
61 .gap(px(10.))
62 .items_center()
63 .rounded(px(6.))
64 .text_size(px(13.))
65 .text_color(theme::text())
66 .cursor_pointer()
67 .when(highlighted, |row| row.bg(theme::row_hover()))
68 .hover(|row| row.bg(theme::row_hover()))
69}
70
71impl Composer {
72 pub(super) fn schedule_blocker(&self, cx: &App) -> Option<&'static str> {
73 let state = self.app.read(cx);
74 let conversation_id = self.conversation_id.as_deref().unwrap_or_default();
75 let outgoing = self.compose(cx);
76 if state.mode.read_only && !state.mode.demo {
77 Some("Read-only mode")
78 } else if conversation_id == NOTES_CHAT_ID {
79 Some("Not available in your notes")
80 } else if conversation_id.is_empty() {
81 Some("Not available in a new chat yet")
82 } else if self.editing.is_some() {
83 Some("Can't schedule while editing")
84 } else if !outgoing.mentions.is_empty() {
85 Some("Can't schedule messages with mentions yet")
86 } else if outgoing.has_attachments() || self.has_attachments(cx) {
87 Some("Can't schedule messages with images or files yet")
88 } else if self.reply.is_some() {
89 Some("Can't schedule replies yet")
90 } else if self.current_draft(cx).is_blank() {
91 Some("Nothing to schedule yet")
92 } else {
93 None
94 }
95 }
96
97 pub(super) fn open_schedule_menu(&mut self, cx: &mut Context<Self>) {
98 self.schedule = Some(SchedulePopover {
99 stage: Stage::Menu,
100 presets: Vec::new(),
101 highlighted: 0,
102 custom: None,
103 });
104 cx.notify();
105 }
106
107 pub(super) fn open_schedule_picker(&mut self, cx: &mut Context<Self>) {
108 if self.schedule_blocker(cx).is_some() || self.scheduling.is_some() {
109 self.open_schedule_menu(cx);
110 return;
111 }
112 self.schedule = Some(SchedulePopover {
113 stage: Stage::Picker,
114 presets: presets(Local::now()),
115 highlighted: 0,
116 custom: None,
117 });
118 cx.notify();
119 }
120
121 pub(super) fn close_schedule(&mut self, window: &mut Window, cx: &mut Context<Self>) {
122 if self.schedule.take().is_some() {
123 self.focus(window, cx);
124 cx.notify();
125 }
126 }
127
128 pub(super) fn move_schedule_highlight(
129 &mut self,
130 delta: isize,
131 window: &mut Window,
132 cx: &mut Context<Self>,
133 ) {
134 let Some(popover) = self.schedule.as_mut() else {
135 return;
136 };
137 if !matches!(popover.stage, Stage::Picker) {
138 return;
139 }
140 if popover.custom.is_some() {
141 self.step_custom_time(delta, window, cx);
142 return;
143 }
144 let count = popover.presets.len() + 1;
145 popover.highlighted =
146 (popover.highlighted as isize + delta).rem_euclid(count as isize) as usize;
147 cx.notify();
148 }
149
150 pub(super) fn activate_schedule_row(&mut self, window: &mut Window, cx: &mut Context<Self>) {
151 let Some(popover) = self.schedule.as_ref() else {
152 return;
153 };
154 let highlighted = popover.highlighted;
155 let on_custom_row = highlighted == popover.custom_index();
156 let custom_open = popover.custom.is_some();
157 match popover.stage {
158 Stage::Menu => {
159 if self.schedule_blocker(cx).is_none() {
160 self.open_schedule_picker(cx);
161 }
162 }
163 Stage::Picker if custom_open => self.confirm_custom(window, cx),
164 Stage::Picker if on_custom_row => self.expand_custom(window, cx),
165 Stage::Picker => self.schedule_preset(highlighted, window, cx),
166 }
167 }
168
169 fn schedule_preset(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
170 let Some(preset) = self
171 .schedule
172 .as_ref()
173 .and_then(|popover| popover.presets.get(index))
174 else {
175 return;
176 };
177 let at = preset.at;
178 if validate(at, Local::now()).is_err() {
179 if let Some(popover) = self.schedule.as_mut() {
180 popover.presets = presets(Local::now());
181 popover.highlighted = 0;
182 }
183 cx.notify();
184 return;
185 }
186 self.schedule_at(at, window, cx);
187 }
188
189 fn expand_custom(&mut self, window: &mut Window, cx: &mut Context<Self>) {
190 let time = format_time(default_custom_time(Local::now()));
191 let time_field = cx.new(|cx| {
192 InputState::new(window, cx)
193 .placeholder("HH:MM")
194 .default_value(time)
195 });
196 time_field.update(cx, |field, cx| {
197 field.focus(window, cx);
198 field.select_all(window, cx);
199 });
200 let edits = cx.subscribe(&time_field, |_, _, event: &InputEvent, cx| {
201 if matches!(event, InputEvent::Change) {
202 cx.notify();
203 }
204 });
205 if let Some(popover) = self.schedule.as_mut() {
206 popover.custom = Some(CustomForm {
207 day_index: 0,
208 time_field,
209 _edits: edits,
210 });
211 }
212 cx.notify();
213 }
214
215 fn step_custom_time(&mut self, steps: isize, window: &mut Window, cx: &mut Context<Self>) {
216 let Some(field) = self
217 .schedule
218 .as_ref()
219 .and_then(|popover| popover.custom.as_ref())
220 .map(|custom| custom.time_field.clone())
221 else {
222 return;
223 };
224 let current = parse_time(&field.read(cx).value()).unwrap_or_default();
225 let stepped = format_time(step_time(current, -(steps as i32)));
226 field.update(cx, |field, cx| field.set_value(&stepped, window, cx));
227 }
228
229 fn custom_choice(&self, cx: &App) -> Result<DateTime<Local>, &'static str> {
230 let custom = self
231 .schedule
232 .as_ref()
233 .and_then(|popover| popover.custom.as_ref())
234 .ok_or(BAD_TIME)?;
235 let now = Local::now();
236 let day = day_choices(now.date_naive())
237 .get(custom.day_index)
238 .map(|choice| choice.date)
239 .ok_or(BAD_TIME)?;
240 let at = custom_time(day, &custom.time_field.read(cx).value()).ok_or(BAD_TIME)?;
241 validate(at, now).map_err(ScheduleError::message)?;
242 Ok(at)
243 }
244
245 fn confirm_custom(&mut self, window: &mut Window, cx: &mut Context<Self>) {
246 if let Ok(at) = self.custom_choice(cx) {
247 self.schedule_at(at, window, cx);
248 }
249 }
250
251 fn schedule_at(&mut self, at: DateTime<Local>, window: &mut Window, cx: &mut Context<Self>) {
252 if self.scheduling.is_some() || self.schedule_blocker(cx).is_some() {
253 return;
254 }
255 let outgoing = self.compose(cx);
256 self.scheduling = Some(outgoing.html());
257 self.close_schedule(window, cx);
258 cx.emit(ComposerEvent::Schedule {
259 outgoing: Box::new(outgoing),
260 send_at: at.with_timezone(&Utc),
261 });
262 }
263
264 pub fn finish_schedule(
265 &mut self,
266 conversation_id: &str,
267 window: &mut Window,
268 cx: &mut Context<Self>,
269 ) {
270 let scheduled = self.scheduling.take();
271 if self.conversation_id.as_deref() != Some(conversation_id) {
272 self.app.read(cx).store.delete_draft(conversation_id).ok();
273 self.app
274 .update(cx, |state, cx| state.refresh_local_previews(cx));
275 return;
276 }
277 if scheduled.as_deref() != Some(self.compose(cx).html().as_str()) {
278 return;
279 }
280 self.load_draft(
281 teams_core::Draft::default(),
282 gpui_kit::component::input::InputContent::new(""),
283 window,
284 cx,
285 );
286 self.mention_inputs.clear();
287 self.tray.clear();
288 self.clear_stored_draft(cx);
289 self.reply = None;
290 self.close_popup();
291 cx.notify();
292 }
293
294 pub fn fail_schedule(&mut self, cx: &mut Context<Self>) {
295 self.scheduling = None;
296 cx.notify();
297 }
298
299 pub(super) fn render_schedule(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
300 let popover = self.schedule.as_ref()?;
301 let body = match popover.stage {
302 Stage::Menu => self.render_schedule_menu(cx),
303 Stage::Picker => self.render_schedule_picker(popover, cx),
304 };
305 Some(
306 v_flex()
307 .id("schedule-popover")
308 .absolute()
309 .bottom(relative(1.))
310 .right_0()
311 .mb(px(6.))
312 .w(px(match popover.stage {
313 Stage::Menu => MENU_WIDTH,
314 Stage::Picker => PICKER_WIDTH,
315 }))
316 .p(px(4.))
317 .rounded(px(8.))
318 .border_1()
319 .border_color(theme::border_strong())
320 .bg(theme::surface_raised())
321 .shadow_lg()
322 .occlude()
323 .on_mouse_down_out(
324 cx.listener(|this, _, window, cx| this.close_schedule(window, cx)),
325 )
326 .child(body)
327 .into_any_element(),
328 )
329 }
330
331 fn render_schedule_menu(&self, cx: &mut Context<Self>) -> Div {
332 let blocker = self.schedule_blocker(cx);
333 let row = menu_row("schedule-send-entry".into(), true)
334 .child(symbol("schedule_send", ICON_SIZE, theme::text_soft()))
335 .child("Schedule send");
336 let row = match blocker {
337 Some(reason) => row
338 .opacity(DISABLED_OPACITY)
339 .cursor_default()
340 .tooltip(move |window, cx| Tooltip::new(reason).build(window, cx)),
341 None => row.on_click(cx.listener(|this, _, _, cx| this.open_schedule_picker(cx))),
342 };
343 v_flex().child(row)
344 }
345
346 fn render_schedule_picker(&self, popover: &SchedulePopover, cx: &mut Context<Self>) -> Div {
347 let mut list = v_flex();
348 for (index, preset) in popover.presets.iter().enumerate() {
349 list = list.child(
350 menu_row(
351 ElementId::Name(format!("schedule-preset-{index}").into()),
352 index == popover.highlighted && popover.custom.is_none(),
353 )
354 .child(symbol(
355 preset_glyph(preset.kind),
356 ICON_SIZE,
357 theme::text_soft(),
358 ))
359 .child(div().flex_1().child(preset.label))
360 .child(
361 div()
362 .text_size(px(12.))
363 .text_color(theme::text_faint())
364 .child(preset.time_label.clone()),
365 )
366 .on_click(
367 cx.listener(move |this, _, window, cx| this.schedule_preset(index, window, cx)),
368 ),
369 );
370 }
371 list = list
372 .child(
373 div()
374 .h(px(1.))
375 .mx(px(6.))
376 .my(px(4.))
377 .bg(theme::border_strong()),
378 )
379 .child(
380 menu_row(
381 "schedule-custom".into(),
382 popover.highlighted == popover.custom_index() && popover.custom.is_none(),
383 )
384 .child(symbol("event", ICON_SIZE, theme::text_soft()))
385 .child("Custom...")
386 .on_click(cx.listener(|this, _, window, cx| this.expand_custom(window, cx))),
387 );
388 if let Some(custom) = popover.custom.as_ref() {
389 list = list.child(self.render_custom_form(custom, cx));
390 }
391 list
392 }
393
394 fn render_custom_form(&self, custom: &CustomForm, cx: &mut Context<Self>) -> Div {
395 let choice = self.custom_choice(cx);
396 let days: Vec<DayChoice> = day_choices(Local::now().date_naive());
397 let chips = days.into_iter().enumerate().map(|(index, day)| {
398 let selected = index == custom.day_index;
399 div()
400 .id(ElementId::Name(format!("schedule-day-{index}").into()))
401 .h(px(26.))
402 .px(px(8.))
403 .flex()
404 .items_center()
405 .rounded(px(6.))
406 .border_1()
407 .border_color(if selected {
408 theme::accent()
409 } else {
410 theme::border_strong()
411 })
412 .text_size(px(12.))
413 .cursor_pointer()
414 .when(selected, |chip| {
415 chip.bg(theme::accent()).text_color(theme::on_accent())
416 })
417 .when(!selected, |chip| {
418 chip.text_color(theme::text_soft())
419 .hover(|chip| chip.bg(theme::row_hover()))
420 })
421 .child(day.label)
422 .on_click(cx.listener(move |this, _, _, cx| {
423 if let Some(form) = this
424 .schedule
425 .as_mut()
426 .and_then(|popover| popover.custom.as_mut())
427 {
428 form.day_index = index;
429 }
430 cx.notify();
431 }))
432 });
433 let valid = choice.is_ok();
434 v_flex()
435 .gap(px(8.))
436 .p(px(10.))
437 .child(h_flex().flex_wrap().gap(px(6.)).children(chips))
438 .child(
439 h_flex()
440 .gap(px(10.))
441 .items_center()
442 .child(
443 div()
444 .w(px(TIME_FIELD_WIDTH))
445 .h(px(28.))
446 .rounded(px(6.))
447 .border_1()
448 .border_color(theme::accent())
449 .bg(theme::surface())
450 .child(
451 Input::new(&custom.time_field)
452 .appearance(false)
453 .bordered(false),
454 ),
455 )
456 .child(div().flex_1())
457 .child(
458 div()
459 .id("schedule-confirm")
460 .h(px(30.))
461 .px(px(14.))
462 .flex()
463 .items_center()
464 .rounded(px(6.))
465 .bg(theme::accent())
466 .text_color(theme::on_accent())
467 .text_size(px(13.))
468 .font_weight(FontWeight::SEMIBOLD)
469 .child("Schedule")
470 .when(!valid, |button| button.opacity(DISABLED_OPACITY))
471 .when(valid, |button| {
472 button.cursor_pointer().on_click(cx.listener(
473 |this, _, window, cx| this.confirm_custom(window, cx),
474 ))
475 }),
476 ),
477 )
478 .children(choice.err().map(|message| {
479 div()
480 .text_size(px(12.))
481 .text_color(theme::red_soft())
482 .child(message)
483 }))
484 }
485}
crates/app/src/views/conversation.rs +200 −138
@@ -15,16 +15,17 @@ use gpui_kit::component::{
15 15 };
16 16 use gpui_kit::prelude::FluentBuilder as _;
17 17 use gpui_kit::*;
18 use store::MessageRecord;
18 use store::{MessageRecord, OutboxState, OutboxTarget};
19 19 use teams_core::{FileCard, ImageRef, LinkPreview};
20 20
21 mod scheduled;
22
21 23 use super::adaptive_card::ensure_cards_inputs;
22 use super::attachment_tray::OutgoingImage;
23 24 use super::attachments::FileActions;
24 25 use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
25 26 use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
26 27 use super::message_actions::{Action, MessageMenu, QUICK_REACTION_COUNT};
27 use super::message_row::{RowActions, render_message_row, render_skeleton_row};
28 use super::message_row::{DeliveryActions, RowActions, render_message_row, render_skeleton_row};
28 29 use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};
29 30 use super::reaction_picker::{PickHandler, ReactionPicker};
30 31 use super::reaction_pills::{ReactionControls, ReactionPopover};
@@ -35,15 +36,16 @@ use crate::data::{is_one_on_one, others};
35 36 use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
36 37 use crate::emoji;
37 38 use crate::notice::short_error;
39 use crate::outbox::{deliver, new_outbox_id, outbox_record, outgoing_of};
40 use crate::pending_rows::pending_row;
38 41 use crate::people::{local_names, resolve_names};
39 42 use crate::reaction_model::UNKNOWN_REACTOR;
40 43 use crate::read_state::{ReadTrigger, plan_read};
41 use crate::render::layout_blocks;
42 44 use crate::rows::{
43 Delivery, LocalImage, MessageRow, PendingReactions, Receipt, Row, RowContext, Series,
44 StartInfo, api_reaction, apply_pending_reactions, assign_series, changed_indices, diff_keys,
45 flat_rows, has_own_reaction, message_draft, message_text, placeholder_rows, reaction_glyph,
46 reply_excerpt, set_own_reaction, thread_list_rows, thread_rows, trailing_skeleton,
45 Delivery, MessageRow, PendingReactions, Receipt, Row, RowContext, StartInfo, api_reaction,
46 apply_pending_reactions, assign_series, changed_indices, diff_keys, flat_rows,
47 has_own_reaction, message_draft, message_text, placeholder_rows, reaction_glyph, reply_excerpt,
48 set_own_reaction, thread_list_rows, thread_rows, trailing_skeleton,
47 49 };
48 50 use crate::runtime;
49 51 use crate::sidebar_model::{AvatarSpec, Face};
@@ -148,6 +150,8 @@ pub struct ConversationView {
148 150 reaction_details: Option<ReactionDetails>,
149 151 highlighted_message: Option<String>,
150 152 notice: Option<String>,
153 scheduled_failure: Option<scheduled::ScheduledFailure>,
154 scheduled_in_flight: HashSet<String>,
151 155 drag_file_count: usize,
152 156 sync_generation: u64,
153 157 window_active: bool,
@@ -339,6 +343,11 @@ impl ConversationView {
339 343 cx.subscribe_in(&composer, window, Self::on_composer_event),
340 344 cx.subscribe_in(&draft, window, Self::on_draft_event),
341 345 cx.observe_window_activation(window, Self::on_window_activation),
346 cx.on_app_quit(|this, cx| {
347 this.composer
348 .update(cx, |composer, cx| composer.save_draft_now(cx));
349 async {}
350 }),
342 351 cx.observe_keystrokes(|this, event, _, cx| {
343 352 if event.keystroke.key == "escape" {
344 353 this.close_reaction_details(cx);
@@ -369,6 +378,8 @@ impl ConversationView {
369 378 reaction_details: None,
370 379 highlighted_message: None,
371 380 notice: None,
381 scheduled_failure: None,
382 scheduled_in_flight: HashSet::new(),
372 383 drag_file_count: 0,
373 384 sync_generation: 0,
374 385 window_active: window.is_window_active(),
@@ -459,8 +470,19 @@ impl ConversationView {
459 470 self.refresh_reactor_names(cx);
460 471 cx.notify();
461 472 }
462 AppEvent::TaskDialog => {}
473 AppEvent::TaskDialog | AppEvent::LocalPreviews => {}
463 474 AppEvent::Typing => cx.notify(),
475 AppEvent::Scheduled => self.rebuild(false, cx),
476 AppEvent::Outbox(conversation_id) => {
477 let is_current = self
478 .current
479 .as_ref()
480 .is_some_and(|current| current.selection.conversation_id() == conversation_id);
481 if is_current {
482 self.reload_pending(cx);
483 self.rebuild(false, cx);
484 }
485 }
464 486 AppEvent::Sidebar => {
465 487 self.mark_read(ReadTrigger::Incoming, cx);
466 488 self.refresh_reactor_names(cx);
@@ -492,10 +514,21 @@ impl ConversationView {
492 514 ComposerEvent::Submit(outgoing) if self.draft_active => {
493 515 self.send_new_chat((**outgoing).clone(), window, cx)
494 516 }
517 ComposerEvent::Submit(outgoing)
518 if outgoing
519 .edit
520 .as_ref()
521 .is_some_and(|edit| edit.scheduled.is_some()) =>
522 {
523 self.send_scheduled_edit((**outgoing).clone(), window, cx)
524 }
495 525 ComposerEvent::Submit(outgoing) if outgoing.edit.is_some() => {
496 526 self.send_edit((**outgoing).clone(), window, cx)
497 527 }
498 528 ComposerEvent::Submit(outgoing) => self.send((**outgoing).clone(), window, cx),
529 ComposerEvent::Schedule { outgoing, send_at } => {
530 self.schedule((**outgoing).clone(), *send_at, window, cx)
531 }
499 532 ComposerEvent::EditLast => self.edit_last_own(window, cx),
500 533 ComposerEvent::Typing(active) => self.send_typing(*active, cx),
501 534 }
@@ -600,8 +633,11 @@ impl ConversationView {
600 633 sync: SyncProgress::default(),
601 634 });
602 635 self.sync_generation += 1;
603 self.clear_pending();
636 self.reload_pending(cx);
604 637 self.notice = None;
638 self.scheduled_failure = None;
639 self.app
640 .update(cx, |state, cx| state.refresh_scheduled(cx));
605 641 self.rebuild(true, cx);
606 642 self.start_fetch(cx);
607 643 self.mark_read(ReadTrigger::Open, cx);
@@ -841,7 +877,7 @@ impl ConversationView {
841 877 } else {
842 878 row_key
843 879 };
844 self.clear_pending();
880 self.reload_pending(cx);
845 881 self.rebuild(true, cx);
846 882 let index = self
847 883 .rows
@@ -1167,6 +1203,7 @@ impl ConversationView {
1167 1203 .cloned()
1168 1204 .map(|row| Row::Message(Box::new(row))),
1169 1205 );
1206 rows.extend(self.scheduled_rows(context.my_user_id.as_deref(), cx));
1170 1207 let receipts = self.receipts(&records, cx);
1171 1208 for row in rows.iter_mut() {
1172 1209 if let Row::Message(message) = row
@@ -1605,12 +1642,71 @@ impl ConversationView {
1605 1642 self.pending_outgoing.clear();
1606 1643 }
1607 1644
1645 fn outbox_route(&self) -> (OutboxTarget, Option<String>) {
1646 match self.current.as_ref().map(|current| &current.mode) {
1647 Some(ViewMode::Thread(root_id)) => (OutboxTarget::Thread, Some(root_id.clone())),
1648 Some(ViewMode::ThreadList) => (OutboxTarget::Post, None),
1649 _ => (OutboxTarget::Flat, None),
1650 }
1651 }
1652
1653 fn reload_pending(&mut self, cx: &App) {
1654 self.clear_pending();
1655 let state = self.app.read(cx);
1656 if state.mode.demo || state.mode.read_only {
1657 return;
1658 }
1659 let Some(current) = self.current.as_ref() else {
1660 return;
1661 };
1662 let conversation_id = current.selection.conversation_id().to_owned();
1663 let Ok(records) = state.store.outbox_for_conversation(&conversation_id) else {
1664 return;
1665 };
1666 let my_user_id = state.store.meta(META_USER_ID).ok().flatten();
1667 let route = self.outbox_route();
1668 for record in records {
1669 if (record.target, record.thread_root_id.clone()) != route {
1670 continue;
1671 }
1672 let Some(outgoing) = outgoing_of(&record) else {
1673 continue;
1674 };
1675 let delivery = match record.state {
1676 OutboxState::Sending => Delivery::Sending,
1677 OutboxState::Failed => Delivery::Failed(record.last_error.unwrap_or_default()),
1678 };
1679 self.pending.push(pending_row(
1680 record.id.clone(),
1681 conversation_id.clone(),
1682 my_user_id.clone(),
1683 record.created_at,
1684 &outgoing,
1685 delivery,
1686 ));
1687 self.pending_outgoing.insert(record.id, outgoing);
1688 }
1689 }
1690
1691 fn discard_outbox_row(&self, id: &str, cx: &mut Context<Self>) {
1692 self.app.read(cx).store.delete_outbox(id).ok();
1693 self.app
1694 .update(cx, |state, cx| state.refresh_local_previews(cx));
1695 }
1696
1697 fn delete_pending(&mut self, key: &str, cx: &mut Context<Self>) {
1698 self.pending.retain(|row| row.key != key);
1699 self.pending_outgoing.remove(key);
1700 self.discard_outbox_row(key, cx);
1701 self.rebuild(false, cx);
1702 }
1703
1608 1704 fn open_thread(&mut self, root_id: String, cx: &mut Context<Self>) {
1609 1705 self.stop_typing(cx);
1610 1706 if let Some(current) = self.current.as_mut() {
1611 1707 current.mode = ViewMode::Thread(root_id);
1612 1708 }
1613 self.clear_pending();
1709 self.reload_pending(cx);
1614 1710 self.rebuild(true, cx);
1615 1711 }
1616 1712
@@ -1619,13 +1715,23 @@ impl ConversationView {
1619 1715 if let Some(current) = self.current.as_mut() {
1620 1716 current.mode = ViewMode::ThreadList;
1621 1717 }
1622 self.clear_pending();
1718 self.reload_pending(cx);
1623 1719 self.rebuild(true, cx);
1624 1720 }
1625 1721
1626 1722 fn send(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
1723 self.send_as(new_outbox_id(), outgoing, window, cx);
1724 }
1725
1726 fn send_as(
1727 &mut self,
1728 id: String,
1729 outgoing: Outgoing,
1730 window: &mut Window,
1731 cx: &mut Context<Self>,
1732 ) {
1627 1733 let state = self.app.read(cx);
1628 let (mode, engine) = (state.mode, state.engine.clone());
1734 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
1629 1735 let Some(current) = self.current.as_ref() else {
1630 1736 return;
1631 1737 };
@@ -1634,75 +1740,42 @@ impl ConversationView {
1634 1740 return;
1635 1741 }
1636 1742 let Some(engine) = engine else {
1743 self.discard_outbox_row(&id, cx);
1637 1744 self.restore_unsent("Not connected yet: nothing was sent", &outgoing, window, cx);
1638 1745 return;
1639 1746 };
1640 1747 let conversation_id = current.selection.conversation_id().to_owned();
1641 let view_mode = current.mode.clone();
1642 let key = self.push_pending(&outgoing, cx);
1748 let (target, thread_root_id) = self.outbox_route();
1749 let created_at = Utc::now();
1750 self.push_pending(id.clone(), created_at, &outgoing, cx);
1751 if let Some(record) = outbox_record(
1752 &id,
1753 &conversation_id,
1754 target,
1755 thread_root_id.as_deref(),
1756 &outgoing,
1757 created_at,
1758 ) {
1759 store.put_outbox(&record).ok();
1760 }
1643 1761 self.notice = None;
1644 1762 self.rebuild(false, cx);
1645 1763 self.scroller
1646 1764 .update(cx, |scroller, cx| scroller.scroll_to_end(cx));
1647 1765
1648 let sent = outgoing.clone();
1649 1766 let receiver = runtime::spawn(async move {
1650 let extras = sent.extras();
1651 let html = sent.html();
1652 let text = &html;
1653 let Outgoing {
1654 mentions, reply, ..
1655 } = &sent;
1656 let record = match (&view_mode, reply) {
1657 (_, Some(reply)) => {
1658 engine
1659 .reply_to_with_extras(
1660 &conversation_id,
1661 &reply.message_id,
1662 text,
1663 mentions,
1664 &extras,
1665 )
1666 .await
1667 }
1668 (ViewMode::Flat, None) => {
1669 engine
1670 .send_message_with_extras(&conversation_id, text, None, mentions, &extras)
1671 .await
1672 }
1673 (ViewMode::ThreadList, None) => {
1674 engine
1675 .post_to_channel_with_extras(
1676 &conversation_id,
1677 text,
1678 None,
1679 mentions,
1680 &extras,
1681 )
1682 .await
1683 }
1684 (ViewMode::Thread(root_id), None) => {
1685 engine
1686 .send_message_with_extras(
1687 &conversation_id,
1688 text,
1689 Some(root_id),
1690 mentions,
1691 &extras,
1692 )
1693 .await
1694 }
1695 }?;
1696 if let Some(preview) = &sent.link_preview {
1697 let _ = engine
1698 .attach_link_preview(&conversation_id, &record.message_id, preview)
1699 .await;
1700 }
1701 Ok(())
1767 deliver(
1768 &engine,
1769 &conversation_id,
1770 target,
1771 thread_root_id.as_deref(),
1772 &outgoing,
1773 )
1774 .await
1702 1775 });
1703 1776 cx.spawn_in(window, async move |this, cx| {
1704 1777 let result = receiver.await;
1705 this.update(cx, |this, cx| this.finish_send(&key, result, cx))
1778 this.update(cx, |this, cx| this.finish_send(&id, result, cx))
1706 1779 .ok();
1707 1780 })
1708 1781 .detach();
@@ -1721,78 +1794,33 @@ impl ConversationView {
1721 1794 cx.notify();
1722 1795 }
1723 1796
1724 fn push_pending(&mut self, outgoing: &Outgoing, cx: &App) -> String {
1797 fn next_pending_key(&mut self) -> String {
1725 1798 self.pending_counter += 1;
1726 let key = format!("{PENDING_KEY_PREFIX}{}", self.pending_counter);
1799 format!("{PENDING_KEY_PREFIX}{}", self.pending_counter)
1800 }
1801
1802 fn push_pending(
1803 &mut self,
1804 key: String,
1805 created_at: DateTime<Utc>,
1806 outgoing: &Outgoing,
1807 cx: &App,
1808 ) {
1727 1809 let my_user_id = self.row_context(cx).my_user_id;
1728 self.pending_outgoing.insert(key.clone(), outgoing.clone());
1729 1810 let conversation_id = self
1730 1811 .current
1731 1812 .as_ref()
1732 1813 .map(|current| current.selection.conversation_id().to_owned())
1733 1814 .unwrap_or_default();
1734 self.pending.push(MessageRow {
1735 key: key.clone(),
1815 self.pending.push(pending_row(
1816 key.clone(),
1736 1817 conversation_id,
1737 author: "You".to_owned(),
1738 sender_id: my_user_id,
1739 application_id: None,
1740 created_at: Utc::now(),
1741 series: Series::default(),
1742 card: false,
1743 time: chrono::Local::now().format("%H:%M").to_string(),
1744 day_header: None,
1745 blocks: if outgoing.draft.is_blank() && outgoing.images.is_empty() {
1746 Vec::new()
1747 } else {
1748 layout_blocks(&teams_core::html_to_spans(&outgoing.html()))
1749 },
1750 edited: false,
1751 deleted: false,
1752 reactions: Vec::new(),
1753 images: outgoing
1754 .images
1755 .iter()
1756 .filter_map(|image| match image {
1757 OutgoingImage::Remote(remote) => Some(remote.image_ref()),
1758 OutgoingImage::Inline(_) => None,
1759 })
1760 .collect(),
1761 local_images: outgoing
1762 .images
1763 .iter()
1764 .filter_map(|image| match image {
1765 OutgoingImage::Inline(inline) => Some(LocalImage {
1766 image: inline.image.clone(),
1767 size: inline.dimensions,
1768 }),
1769 OutgoingImage::Remote(_) => None,
1770 })
1771 .collect(),
1772 adaptive_cards: Vec::new(),
1773 link_preview: outgoing.link_preview.clone(),
1774 files: outgoing
1775 .files
1776 .iter()
1777 .map(|file| FileCard {
1778 name: file.name.clone(),
1779 kind: file.kind,
1780 content_type: None,
1781 size: Some(file.size),
1782 open_url: file.reference.content_url.clone(),
1783 })
1784 .collect(),
1785 reply_count: None,
1786 new_marker: false,
1787 reply_faces: Vec::new(),
1788 last_reply_time: None,
1789 open_thread: None,
1790 is_reply: false,
1791 delivery: Delivery::Sending,
1792 receipt: Receipt::Hidden,
1793 own: true,
1794 });
1795 key
1818 my_user_id,
1819 created_at,
1820 outgoing,
1821 Delivery::Sending,
1822 ));
1823 self.pending_outgoing.insert(key, outgoing.clone());
1796 1824 }
1797 1825
1798 1826 fn send_new_chat(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
@@ -1844,7 +1872,8 @@ impl ConversationView {
1844 1872 self.pending_outgoing.clear();
1845 1873 self.draft_error = None;
1846 1874 self.notice = None;
1847 let key = self.push_pending(&outgoing, cx);
1875 let key = self.next_pending_key();
1876 self.push_pending(key.clone(), Utc::now(), &outgoing, cx);
1848 1877 self.rebuild(true, cx);
1849 1878 let recipients_for_finish = user_ids.clone();
1850 1879 let receiver = runtime::spawn(async move {
@@ -2170,6 +2199,7 @@ impl ConversationView {
2170 2199 let edit = EditPreview {
2171 2200 message_id: record.message_id.clone(),
2172 2201 excerpt: reply_excerpt(&record),
2202 scheduled: None,
2173 2203 };
2174 2204 let in_chat = matches!(
2175 2205 self.current.as_ref().map(|current| &current.selection),
@@ -2398,7 +2428,7 @@ impl ConversationView {
2398 2428 if self.draft_active {
2399 2429 self.send_new_chat(outgoing, window, cx);
2400 2430 } else {
2401 self.send(outgoing, window, cx);
2431 self.send_as(key.to_owned(), outgoing, window, cx);
2402 2432 }
2403 2433 }
2404 2434
@@ -2413,18 +2443,23 @@ impl ConversationView {
2413 2443 Ok(Err(error)) => Some(short_error(&error)),
2414 2444 Err(error) => Some(short_error(&error)),
2415 2445 };
2446 let store = self.app.read(cx).store.clone();
2416 2447 match failure {
2417 2448 None => {
2449 store.delete_outbox(key).ok();
2418 2450 self.pending.retain(|row| row.key != key);
2419 2451 self.pending_outgoing.remove(key);
2420 2452 }
2421 2453 Some(error) => {
2454 store.mark_outbox_failed(key, &error).ok();
2422 2455 if let Some(row) = self.pending.iter_mut().find(|row| row.key == key) {
2423 2456 row.delivery = Delivery::Failed(error.clone());
2424 2457 self.notice = Some(format!("Not sent: {error}"));
2425 2458 }
2426 2459 }
2427 2460 }
2461 self.app
2462 .update(cx, |state, cx| state.refresh_local_previews(cx));
2428 2463 self.rebuild(false, cx);
2429 2464 }
2430 2465
@@ -2705,6 +2740,18 @@ impl Render for ConversationView {
2705 2740 .ok();
2706 2741 }) as Box<dyn Fn(&mut App)>
2707 2742 });
2743 let scheduled = view.upgrade().and_then(|entity| {
2744 entity
2745 .read(cx)
2746 .scheduled_row_actions(message, &view, window, cx)
2747 });
2748 let delete = matches!(message.delivery, Delivery::Failed(_)).then(|| {
2749 let (view, key) = (view.clone(), message.key.clone());
2750 Box::new(move |cx: &mut App| {
2751 view.update(cx, |this, cx| this.delete_pending(&key, cx))
2752 .ok();
2753 }) as Box<dyn Fn(&mut App)>
2754 });
2708 2755 let senders: Vec<String> = (!message.own && !message.series.has_prev)
2709 2756 .then(|| message.sender_id.clone())
2710 2757 .flatten()
@@ -2739,7 +2786,9 @@ impl Render for ConversationView {
2739 2786 });
2740 2787 });
2741 2788 }
2742 let is_real = !drafting && !message.key.starts_with(PENDING_KEY_PREFIX);
2789 let is_real = !drafting
2790 && !message.key.starts_with(PENDING_KEY_PREFIX)
2791 && scheduled.is_none();
2743 2792 let hovered = is_real.then(|| {
2744 2793 let (view, key) = (view.clone(), message.key.clone());
2745 2794 Rc::new(move |hovered: bool, cx: &mut App| {
@@ -2749,6 +2798,18 @@ impl Render for ConversationView {
2749 2798 .ok();
2750 2799 }) as Rc<dyn Fn(bool, &mut App)>
2751 2800 });
2801 let (delivery, scheduled_menu, hovered) = match scheduled {
2802 Some(actions) => (actions.delivery, actions.menu, Some(actions.hovered)),
2803 None => (
2804 DeliveryActions {
2805 retry,
2806 delete,
2807 send_now: None,
2808 },
2809 None,
2810 hovered,
2811 ),
2812 };
2752 2813 let actionable = is_real && !message.deleted && !message.card;
2753 2814 let (menu, react, reaction_controls) = view
2754 2815 .upgrade()
@@ -2833,10 +2894,11 @@ impl Render for ConversationView {
2833 2894 RowActions {
2834 2895 bot,
2835 2896 open_thread,
2836 retry,
2897 delivery,
2837 2898 reply,
2838 2899 hovered,
2839 2900 menu,
2901 scheduled_menu,
2840 2902 react,
2841 2903 reaction_controls,
2842 2904 files,
@@ -15,16 +15,17 @@ use gpui_kit::component::{
15};
15};
16use gpui_kit::prelude::FluentBuilder as _;
16use gpui_kit::prelude::FluentBuilder as _;
17use gpui_kit::*;
17use gpui_kit::*;
18use store::MessageRecord;
18use store::{MessageRecord, OutboxState, OutboxTarget};
19use teams_core::{FileCard, ImageRef, LinkPreview};
19use teams_core::{FileCard, ImageRef, LinkPreview};
20
20
21mod scheduled;
22
21use super::adaptive_card::ensure_cards_inputs;
23use super::adaptive_card::ensure_cards_inputs;
22use super::attachment_tray::OutgoingImage;
23use super::attachments::FileActions;
24use super::attachments::FileActions;
24use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
25use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
25use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
26use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
26use super::message_actions::{Action, MessageMenu, QUICK_REACTION_COUNT};
27use super::message_actions::{Action, MessageMenu, QUICK_REACTION_COUNT};
27use super::message_row::{RowActions, render_message_row, render_skeleton_row};
28use super::message_row::{DeliveryActions, RowActions, render_message_row, render_skeleton_row};
28use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};
29use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};
29use super::reaction_picker::{PickHandler, ReactionPicker};
30use super::reaction_picker::{PickHandler, ReactionPicker};
30use super::reaction_pills::{ReactionControls, ReactionPopover};
31use super::reaction_pills::{ReactionControls, ReactionPopover};
@@ -35,15 +36,16 @@ use crate::data::{is_one_on_one, others};
35use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
36use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
36use crate::emoji;
37use crate::emoji;
37use crate::notice::short_error;
38use crate::notice::short_error;
39use crate::outbox::{deliver, new_outbox_id, outbox_record, outgoing_of};
40use crate::pending_rows::pending_row;
38use crate::people::{local_names, resolve_names};
41use crate::people::{local_names, resolve_names};
39use crate::reaction_model::UNKNOWN_REACTOR;
42use crate::reaction_model::UNKNOWN_REACTOR;
40use crate::read_state::{ReadTrigger, plan_read};
43use crate::read_state::{ReadTrigger, plan_read};
41use crate::render::layout_blocks;
42use crate::rows::{
44use crate::rows::{
43 Delivery, LocalImage, MessageRow, PendingReactions, Receipt, Row, RowContext, Series,
45 Delivery, MessageRow, PendingReactions, Receipt, Row, RowContext, StartInfo, api_reaction,
44 StartInfo, api_reaction, apply_pending_reactions, assign_series, changed_indices, diff_keys,
46 apply_pending_reactions, assign_series, changed_indices, diff_keys, flat_rows,
45 flat_rows, has_own_reaction, message_draft, message_text, placeholder_rows, reaction_glyph,
47 has_own_reaction, message_draft, message_text, placeholder_rows, reaction_glyph, reply_excerpt,
46 reply_excerpt, set_own_reaction, thread_list_rows, thread_rows, trailing_skeleton,
48 set_own_reaction, thread_list_rows, thread_rows, trailing_skeleton,
47};
49};
48use crate::runtime;
50use crate::runtime;
49use crate::sidebar_model::{AvatarSpec, Face};
51use crate::sidebar_model::{AvatarSpec, Face};
@@ -148,6 +150,8 @@ pub struct ConversationView {
148 reaction_details: Option<ReactionDetails>,
150 reaction_details: Option<ReactionDetails>,
149 highlighted_message: Option<String>,
151 highlighted_message: Option<String>,
150 notice: Option<String>,
152 notice: Option<String>,
153 scheduled_failure: Option<scheduled::ScheduledFailure>,
154 scheduled_in_flight: HashSet<String>,
151 drag_file_count: usize,
155 drag_file_count: usize,
152 sync_generation: u64,
156 sync_generation: u64,
153 window_active: bool,
157 window_active: bool,
@@ -339,6 +343,11 @@ impl ConversationView {
339 cx.subscribe_in(&composer, window, Self::on_composer_event),
343 cx.subscribe_in(&composer, window, Self::on_composer_event),
340 cx.subscribe_in(&draft, window, Self::on_draft_event),
344 cx.subscribe_in(&draft, window, Self::on_draft_event),
341 cx.observe_window_activation(window, Self::on_window_activation),
345 cx.observe_window_activation(window, Self::on_window_activation),
346 cx.on_app_quit(|this, cx| {
347 this.composer
348 .update(cx, |composer, cx| composer.save_draft_now(cx));
349 async {}
350 }),
342 cx.observe_keystrokes(|this, event, _, cx| {
351 cx.observe_keystrokes(|this, event, _, cx| {
343 if event.keystroke.key == "escape" {
352 if event.keystroke.key == "escape" {
344 this.close_reaction_details(cx);
353 this.close_reaction_details(cx);
@@ -369,6 +378,8 @@ impl ConversationView {
369 reaction_details: None,
378 reaction_details: None,
370 highlighted_message: None,
379 highlighted_message: None,
371 notice: None,
380 notice: None,
381 scheduled_failure: None,
382 scheduled_in_flight: HashSet::new(),
372 drag_file_count: 0,
383 drag_file_count: 0,
373 sync_generation: 0,
384 sync_generation: 0,
374 window_active: window.is_window_active(),
385 window_active: window.is_window_active(),
@@ -459,8 +470,19 @@ impl ConversationView {
459 self.refresh_reactor_names(cx);
470 self.refresh_reactor_names(cx);
460 cx.notify();
471 cx.notify();
461 }
472 }
462 AppEvent::TaskDialog => {}
473 AppEvent::TaskDialog | AppEvent::LocalPreviews => {}
463 AppEvent::Typing => cx.notify(),
474 AppEvent::Typing => cx.notify(),
475 AppEvent::Scheduled => self.rebuild(false, cx),
476 AppEvent::Outbox(conversation_id) => {
477 let is_current = self
478 .current
479 .as_ref()
480 .is_some_and(|current| current.selection.conversation_id() == conversation_id);
481 if is_current {
482 self.reload_pending(cx);
483 self.rebuild(false, cx);
484 }
485 }
464 AppEvent::Sidebar => {
486 AppEvent::Sidebar => {
465 self.mark_read(ReadTrigger::Incoming, cx);
487 self.mark_read(ReadTrigger::Incoming, cx);
466 self.refresh_reactor_names(cx);
488 self.refresh_reactor_names(cx);
@@ -492,10 +514,21 @@ impl ConversationView {
492 ComposerEvent::Submit(outgoing) if self.draft_active => {
514 ComposerEvent::Submit(outgoing) if self.draft_active => {
493 self.send_new_chat((**outgoing).clone(), window, cx)
515 self.send_new_chat((**outgoing).clone(), window, cx)
494 }
516 }
517 ComposerEvent::Submit(outgoing)
518 if outgoing
519 .edit
520 .as_ref()
521 .is_some_and(|edit| edit.scheduled.is_some()) =>
522 {
523 self.send_scheduled_edit((**outgoing).clone(), window, cx)
524 }
495 ComposerEvent::Submit(outgoing) if outgoing.edit.is_some() => {
525 ComposerEvent::Submit(outgoing) if outgoing.edit.is_some() => {
496 self.send_edit((**outgoing).clone(), window, cx)
526 self.send_edit((**outgoing).clone(), window, cx)
497 }
527 }
498 ComposerEvent::Submit(outgoing) => self.send((**outgoing).clone(), window, cx),
528 ComposerEvent::Submit(outgoing) => self.send((**outgoing).clone(), window, cx),
529 ComposerEvent::Schedule { outgoing, send_at } => {
530 self.schedule((**outgoing).clone(), *send_at, window, cx)
531 }
499 ComposerEvent::EditLast => self.edit_last_own(window, cx),
532 ComposerEvent::EditLast => self.edit_last_own(window, cx),
500 ComposerEvent::Typing(active) => self.send_typing(*active, cx),
533 ComposerEvent::Typing(active) => self.send_typing(*active, cx),
501 }
534 }
@@ -600,8 +633,11 @@ impl ConversationView {
600 sync: SyncProgress::default(),
633 sync: SyncProgress::default(),
601 });
634 });
602 self.sync_generation += 1;
635 self.sync_generation += 1;
603 self.clear_pending();
636 self.reload_pending(cx);
604 self.notice = None;
637 self.notice = None;
638 self.scheduled_failure = None;
639 self.app
640 .update(cx, |state, cx| state.refresh_scheduled(cx));
605 self.rebuild(true, cx);
641 self.rebuild(true, cx);
606 self.start_fetch(cx);
642 self.start_fetch(cx);
607 self.mark_read(ReadTrigger::Open, cx);
643 self.mark_read(ReadTrigger::Open, cx);
@@ -841,7 +877,7 @@ impl ConversationView {
841 } else {
877 } else {
842 row_key
878 row_key
843 };
879 };
844 self.clear_pending();
880 self.reload_pending(cx);
845 self.rebuild(true, cx);
881 self.rebuild(true, cx);
846 let index = self
882 let index = self
847 .rows
883 .rows
@@ -1167,6 +1203,7 @@ impl ConversationView {
1167 .cloned()
1203 .cloned()
1168 .map(|row| Row::Message(Box::new(row))),
1204 .map(|row| Row::Message(Box::new(row))),
1169 );
1205 );
1206 rows.extend(self.scheduled_rows(context.my_user_id.as_deref(), cx));
1170 let receipts = self.receipts(&records, cx);
1207 let receipts = self.receipts(&records, cx);
1171 for row in rows.iter_mut() {
1208 for row in rows.iter_mut() {
1172 if let Row::Message(message) = row
1209 if let Row::Message(message) = row
@@ -1605,12 +1642,71 @@ impl ConversationView {
1605 self.pending_outgoing.clear();
1642 self.pending_outgoing.clear();
1606 }
1643 }
1607
1644
1645 fn outbox_route(&self) -> (OutboxTarget, Option<String>) {
1646 match self.current.as_ref().map(|current| &current.mode) {
1647 Some(ViewMode::Thread(root_id)) => (OutboxTarget::Thread, Some(root_id.clone())),
1648 Some(ViewMode::ThreadList) => (OutboxTarget::Post, None),
1649 _ => (OutboxTarget::Flat, None),
1650 }
1651 }
1652
1653 fn reload_pending(&mut self, cx: &App) {
1654 self.clear_pending();
1655 let state = self.app.read(cx);
1656 if state.mode.demo || state.mode.read_only {
1657 return;
1658 }
1659 let Some(current) = self.current.as_ref() else {
1660 return;
1661 };
1662 let conversation_id = current.selection.conversation_id().to_owned();
1663 let Ok(records) = state.store.outbox_for_conversation(&conversation_id) else {
1664 return;
1665 };
1666 let my_user_id = state.store.meta(META_USER_ID).ok().flatten();
1667 let route = self.outbox_route();
1668 for record in records {
1669 if (record.target, record.thread_root_id.clone()) != route {
1670 continue;
1671 }
1672 let Some(outgoing) = outgoing_of(&record) else {
1673 continue;
1674 };
1675 let delivery = match record.state {
1676 OutboxState::Sending => Delivery::Sending,
1677 OutboxState::Failed => Delivery::Failed(record.last_error.unwrap_or_default()),
1678 };
1679 self.pending.push(pending_row(
1680 record.id.clone(),
1681 conversation_id.clone(),
1682 my_user_id.clone(),
1683 record.created_at,
1684 &outgoing,
1685 delivery,
1686 ));
1687 self.pending_outgoing.insert(record.id, outgoing);
1688 }
1689 }
1690
1691 fn discard_outbox_row(&self, id: &str, cx: &mut Context<Self>) {
1692 self.app.read(cx).store.delete_outbox(id).ok();
1693 self.app
1694 .update(cx, |state, cx| state.refresh_local_previews(cx));
1695 }
1696
1697 fn delete_pending(&mut self, key: &str, cx: &mut Context<Self>) {
1698 self.pending.retain(|row| row.key != key);
1699 self.pending_outgoing.remove(key);
1700 self.discard_outbox_row(key, cx);
1701 self.rebuild(false, cx);
1702 }
1703
1608 fn open_thread(&mut self, root_id: String, cx: &mut Context<Self>) {
1704 fn open_thread(&mut self, root_id: String, cx: &mut Context<Self>) {
1609 self.stop_typing(cx);
1705 self.stop_typing(cx);
1610 if let Some(current) = self.current.as_mut() {
1706 if let Some(current) = self.current.as_mut() {
1611 current.mode = ViewMode::Thread(root_id);
1707 current.mode = ViewMode::Thread(root_id);
1612 }
1708 }
1613 self.clear_pending();
1709 self.reload_pending(cx);
1614 self.rebuild(true, cx);
1710 self.rebuild(true, cx);
1615 }
1711 }
1616
1712
@@ -1619,13 +1715,23 @@ impl ConversationView {
1619 if let Some(current) = self.current.as_mut() {
1715 if let Some(current) = self.current.as_mut() {
1620 current.mode = ViewMode::ThreadList;
1716 current.mode = ViewMode::ThreadList;
1621 }
1717 }
1622 self.clear_pending();
1718 self.reload_pending(cx);
1623 self.rebuild(true, cx);
1719 self.rebuild(true, cx);
1624 }
1720 }
1625
1721
1626 fn send(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
1722 fn send(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
1723 self.send_as(new_outbox_id(), outgoing, window, cx);
1724 }
1725
1726 fn send_as(
1727 &mut self,
1728 id: String,
1729 outgoing: Outgoing,
1730 window: &mut Window,
1731 cx: &mut Context<Self>,
1732 ) {
1627 let state = self.app.read(cx);
1733 let state = self.app.read(cx);
1628 let (mode, engine) = (state.mode, state.engine.clone());
1734 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
1629 let Some(current) = self.current.as_ref() else {
1735 let Some(current) = self.current.as_ref() else {
1630 return;
1736 return;
1631 };
1737 };
@@ -1634,75 +1740,42 @@ impl ConversationView {
1634 return;
1740 return;
1635 }
1741 }
1636 let Some(engine) = engine else {
1742 let Some(engine) = engine else {
1743 self.discard_outbox_row(&id, cx);
1637 self.restore_unsent("Not connected yet: nothing was sent", &outgoing, window, cx);
1744 self.restore_unsent("Not connected yet: nothing was sent", &outgoing, window, cx);
1638 return;
1745 return;
1639 };
1746 };
1640 let conversation_id = current.selection.conversation_id().to_owned();
1747 let conversation_id = current.selection.conversation_id().to_owned();
1641 let view_mode = current.mode.clone();
1748 let (target, thread_root_id) = self.outbox_route();
1642 let key = self.push_pending(&outgoing, cx);
1749 let created_at = Utc::now();
1750 self.push_pending(id.clone(), created_at, &outgoing, cx);
1751 if let Some(record) = outbox_record(
1752 &id,
1753 &conversation_id,
1754 target,
1755 thread_root_id.as_deref(),
1756 &outgoing,
1757 created_at,
1758 ) {
1759 store.put_outbox(&record).ok();
1760 }
1643 self.notice = None;
1761 self.notice = None;
1644 self.rebuild(false, cx);
1762 self.rebuild(false, cx);
1645 self.scroller
1763 self.scroller
1646 .update(cx, |scroller, cx| scroller.scroll_to_end(cx));
1764 .update(cx, |scroller, cx| scroller.scroll_to_end(cx));
1647
1765
1648 let sent = outgoing.clone();
1649 let receiver = runtime::spawn(async move {
1766 let receiver = runtime::spawn(async move {
1650 let extras = sent.extras();
1767 deliver(
1651 let html = sent.html();
1768 &engine,
1652 let text = &html;
1769 &conversation_id,
1653 let Outgoing {
1770 target,
1654 mentions, reply, ..
1771 thread_root_id.as_deref(),
1655 } = &sent;
1772 &outgoing,
1656 let record = match (&view_mode, reply) {
1773 )
1657 (_, Some(reply)) => {
1774 .await
1658 engine
1659 .reply_to_with_extras(
1660 &conversation_id,
1661 &reply.message_id,
1662 text,
1663 mentions,
1664 &extras,
1665 )
1666 .await
1667 }
1668 (ViewMode::Flat, None) => {
1669 engine
1670 .send_message_with_extras(&conversation_id, text, None, mentions, &extras)
1671 .await
1672 }
1673 (ViewMode::ThreadList, None) => {
1674 engine
1675 .post_to_channel_with_extras(
1676 &conversation_id,
1677 text,
1678 None,
1679 mentions,
1680 &extras,
1681 )
1682 .await
1683 }
1684 (ViewMode::Thread(root_id), None) => {
1685 engine
1686 .send_message_with_extras(
1687 &conversation_id,
1688 text,
1689 Some(root_id),
1690 mentions,
1691 &extras,
1692 )
1693 .await
1694 }
1695 }?;
1696 if let Some(preview) = &sent.link_preview {
1697 let _ = engine
1698 .attach_link_preview(&conversation_id, &record.message_id, preview)
1699 .await;
1700 }
1701 Ok(())
1702 });
1775 });
1703 cx.spawn_in(window, async move |this, cx| {
1776 cx.spawn_in(window, async move |this, cx| {
1704 let result = receiver.await;
1777 let result = receiver.await;
1705 this.update(cx, |this, cx| this.finish_send(&key, result, cx))
1778 this.update(cx, |this, cx| this.finish_send(&id, result, cx))
1706 .ok();
1779 .ok();
1707 })
1780 })
1708 .detach();
1781 .detach();
@@ -1721,78 +1794,33 @@ impl ConversationView {
1721 cx.notify();
1794 cx.notify();
1722 }
1795 }
1723
1796
1724 fn push_pending(&mut self, outgoing: &Outgoing, cx: &App) -> String {
1797 fn next_pending_key(&mut self) -> String {
1725 self.pending_counter += 1;
1798 self.pending_counter += 1;
1726 let key = format!("{PENDING_KEY_PREFIX}{}", self.pending_counter);
1799 format!("{PENDING_KEY_PREFIX}{}", self.pending_counter)
1800 }
1801
1802 fn push_pending(
1803 &mut self,
1804 key: String,
1805 created_at: DateTime<Utc>,
1806 outgoing: &Outgoing,
1807 cx: &App,
1808 ) {
1727 let my_user_id = self.row_context(cx).my_user_id;
1809 let my_user_id = self.row_context(cx).my_user_id;
1728 self.pending_outgoing.insert(key.clone(), outgoing.clone());
1729 let conversation_id = self
1810 let conversation_id = self
1730 .current
1811 .current
1731 .as_ref()
1812 .as_ref()
1732 .map(|current| current.selection.conversation_id().to_owned())
1813 .map(|current| current.selection.conversation_id().to_owned())
1733 .unwrap_or_default();
1814 .unwrap_or_default();
1734 self.pending.push(MessageRow {
1815 self.pending.push(pending_row(
1735 key: key.clone(),
1816 key.clone(),
1736 conversation_id,
1817 conversation_id,
1737 author: "You".to_owned(),
1818 my_user_id,
1738 sender_id: my_user_id,
1819 created_at,
1739 application_id: None,
1820 outgoing,
1740 created_at: Utc::now(),
1821 Delivery::Sending,
1741 series: Series::default(),
1822 ));
1742 card: false,
1823 self.pending_outgoing.insert(key, outgoing.clone());
1743 time: chrono::Local::now().format("%H:%M").to_string(),
1744 day_header: None,
1745 blocks: if outgoing.draft.is_blank() && outgoing.images.is_empty() {
1746 Vec::new()
1747 } else {
1748 layout_blocks(&teams_core::html_to_spans(&outgoing.html()))
1749 },
1750 edited: false,
1751 deleted: false,
1752 reactions: Vec::new(),
1753 images: outgoing
1754 .images
1755 .iter()
1756 .filter_map(|image| match image {
1757 OutgoingImage::Remote(remote) => Some(remote.image_ref()),
1758 OutgoingImage::Inline(_) => None,
1759 })
1760 .collect(),
1761 local_images: outgoing
1762 .images
1763 .iter()
1764 .filter_map(|image| match image {
1765 OutgoingImage::Inline(inline) => Some(LocalImage {
1766 image: inline.image.clone(),
1767 size: inline.dimensions,
1768 }),
1769 OutgoingImage::Remote(_) => None,
1770 })
1771 .collect(),
1772 adaptive_cards: Vec::new(),
1773 link_preview: outgoing.link_preview.clone(),
1774 files: outgoing
1775 .files
1776 .iter()
1777 .map(|file| FileCard {
1778 name: file.name.clone(),
1779 kind: file.kind,
1780 content_type: None,
1781 size: Some(file.size),
1782 open_url: file.reference.content_url.clone(),
1783 })
1784 .collect(),
1785 reply_count: None,
1786 new_marker: false,
1787 reply_faces: Vec::new(),
1788 last_reply_time: None,
1789 open_thread: None,
1790 is_reply: false,
1791 delivery: Delivery::Sending,
1792 receipt: Receipt::Hidden,
1793 own: true,
1794 });
1795 key
1796 }
1824 }
1797
1825
1798 fn send_new_chat(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
1826 fn send_new_chat(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
@@ -1844,7 +1872,8 @@ impl ConversationView {
1844 self.pending_outgoing.clear();
1872 self.pending_outgoing.clear();
1845 self.draft_error = None;
1873 self.draft_error = None;
1846 self.notice = None;
1874 self.notice = None;
1847 let key = self.push_pending(&outgoing, cx);
1875 let key = self.next_pending_key();
1876 self.push_pending(key.clone(), Utc::now(), &outgoing, cx);
1848 self.rebuild(true, cx);
1877 self.rebuild(true, cx);
1849 let recipients_for_finish = user_ids.clone();
1878 let recipients_for_finish = user_ids.clone();
1850 let receiver = runtime::spawn(async move {
1879 let receiver = runtime::spawn(async move {
@@ -2170,6 +2199,7 @@ impl ConversationView {
2170 let edit = EditPreview {
2199 let edit = EditPreview {
2171 message_id: record.message_id.clone(),
2200 message_id: record.message_id.clone(),
2172 excerpt: reply_excerpt(&record),
2201 excerpt: reply_excerpt(&record),
2202 scheduled: None,
2173 };
2203 };
2174 let in_chat = matches!(
2204 let in_chat = matches!(
2175 self.current.as_ref().map(|current| &current.selection),
2205 self.current.as_ref().map(|current| &current.selection),
@@ -2398,7 +2428,7 @@ impl ConversationView {
2398 if self.draft_active {
2428 if self.draft_active {
2399 self.send_new_chat(outgoing, window, cx);
2429 self.send_new_chat(outgoing, window, cx);
2400 } else {
2430 } else {
2401 self.send(outgoing, window, cx);
2431 self.send_as(key.to_owned(), outgoing, window, cx);
2402 }
2432 }
2403 }
2433 }
2404
2434
@@ -2413,18 +2443,23 @@ impl ConversationView {
2413 Ok(Err(error)) => Some(short_error(&error)),
2443 Ok(Err(error)) => Some(short_error(&error)),
2414 Err(error) => Some(short_error(&error)),
2444 Err(error) => Some(short_error(&error)),
2415 };
2445 };
2446 let store = self.app.read(cx).store.clone();
2416 match failure {
2447 match failure {
2417 None => {
2448 None => {
2449 store.delete_outbox(key).ok();
2418 self.pending.retain(|row| row.key != key);
2450 self.pending.retain(|row| row.key != key);
2419 self.pending_outgoing.remove(key);
2451 self.pending_outgoing.remove(key);
2420 }
2452 }
2421 Some(error) => {
2453 Some(error) => {
2454 store.mark_outbox_failed(key, &error).ok();
2422 if let Some(row) = self.pending.iter_mut().find(|row| row.key == key) {
2455 if let Some(row) = self.pending.iter_mut().find(|row| row.key == key) {
2423 row.delivery = Delivery::Failed(error.clone());
2456 row.delivery = Delivery::Failed(error.clone());
2424 self.notice = Some(format!("Not sent: {error}"));
2457 self.notice = Some(format!("Not sent: {error}"));
2425 }
2458 }
2426 }
2459 }
2427 }
2460 }
2461 self.app
2462 .update(cx, |state, cx| state.refresh_local_previews(cx));
2428 self.rebuild(false, cx);
2463 self.rebuild(false, cx);
2429 }
2464 }
2430
2465
@@ -2705,6 +2740,18 @@ impl Render for ConversationView {
2705 .ok();
2740 .ok();
2706 }) as Box<dyn Fn(&mut App)>
2741 }) as Box<dyn Fn(&mut App)>
2707 });
2742 });
2743 let scheduled = view.upgrade().and_then(|entity| {
2744 entity
2745 .read(cx)
2746 .scheduled_row_actions(message, &view, window, cx)
2747 });
2748 let delete = matches!(message.delivery, Delivery::Failed(_)).then(|| {
2749 let (view, key) = (view.clone(), message.key.clone());
2750 Box::new(move |cx: &mut App| {
2751 view.update(cx, |this, cx| this.delete_pending(&key, cx))
2752 .ok();
2753 }) as Box<dyn Fn(&mut App)>
2754 });
2708 let senders: Vec<String> = (!message.own && !message.series.has_prev)
2755 let senders: Vec<String> = (!message.own && !message.series.has_prev)
2709 .then(|| message.sender_id.clone())
2756 .then(|| message.sender_id.clone())
2710 .flatten()
2757 .flatten()
@@ -2739,7 +2786,9 @@ impl Render for ConversationView {
2739 });
2786 });
2740 });
2787 });
2741 }
2788 }
2742 let is_real = !drafting && !message.key.starts_with(PENDING_KEY_PREFIX);
2789 let is_real = !drafting
2790 && !message.key.starts_with(PENDING_KEY_PREFIX)
2791 && scheduled.is_none();
2743 let hovered = is_real.then(|| {
2792 let hovered = is_real.then(|| {
2744 let (view, key) = (view.clone(), message.key.clone());
2793 let (view, key) = (view.clone(), message.key.clone());
2745 Rc::new(move |hovered: bool, cx: &mut App| {
2794 Rc::new(move |hovered: bool, cx: &mut App| {
@@ -2749,6 +2798,18 @@ impl Render for ConversationView {
2749 .ok();
2798 .ok();
2750 }) as Rc<dyn Fn(bool, &mut App)>
2799 }) as Rc<dyn Fn(bool, &mut App)>
2751 });
2800 });
2801 let (delivery, scheduled_menu, hovered) = match scheduled {
2802 Some(actions) => (actions.delivery, actions.menu, Some(actions.hovered)),
2803 None => (
2804 DeliveryActions {
2805 retry,
2806 delete,
2807 send_now: None,
2808 },
2809 None,
2810 hovered,
2811 ),
2812 };
2752 let actionable = is_real && !message.deleted && !message.card;
2813 let actionable = is_real && !message.deleted && !message.card;
2753 let (menu, react, reaction_controls) = view
2814 let (menu, react, reaction_controls) = view
2754 .upgrade()
2815 .upgrade()
@@ -2833,10 +2894,11 @@ impl Render for ConversationView {
2833 RowActions {
2894 RowActions {
2834 bot,
2895 bot,
2835 open_thread,
2896 open_thread,
2836 retry,
2897 delivery,
2837 reply,
2898 reply,
2838 hovered,
2899 hovered,
2839 menu,
2900 menu,
2901 scheduled_menu,
2840 react,
2902 react,
2841 reaction_controls,
2903 reaction_controls,
2842 files,
2904 files,
crates/app/src/views/conversation/scheduled.rs added +461 −0
@@ -0,0 +1,461 @@
1 use std::rc::Rc;
2
3 use chrono::{DateTime, Utc};
4 use gpui_kit::*;
5 use store::OutboxTarget;
6 use teams_core::ScheduledDraft;
7 use uuid::Uuid;
8
9 use super::{ConversationView, HoverSlot, ViewMode};
10 use crate::backend::Engine;
11 use crate::notice::{short_error, truncated};
12 use crate::outbox::{deliver, new_outbox_id, outbox_record};
13 use crate::rows::{MessageRow, Row};
14 use crate::runtime;
15 use crate::scheduled::{conversation_of, thread_root_of};
16 use crate::scheduled_rows::{draft_id_of, draft_key, scheduled_outgoing, scheduled_rows};
17 use crate::views::composer::{EditPreview, Outgoing};
18 use crate::views::message_actions::{Action, HoverChange};
19 use crate::views::message_row::{DeliveryActions, RowAction};
20 use crate::views::scheduled_toolbar::ScheduledMenu;
21 use std::sync::Arc;
22
23 const EXCERPT_CHARS: usize = 140;
24
25 #[derive(Clone)]
26 pub(super) enum ScheduledAction {
27 Update(String),
28 SendNow,
29 Delete,
30 }
31
32 pub(super) struct ScheduledFailure {
33 draft_id: String,
34 action: ScheduledAction,
35 }
36
37 pub(super) struct ScheduledRowActions {
38 pub delivery: DeliveryActions,
39 pub menu: Option<ScheduledMenu>,
40 pub hovered: HoverChange,
41 }
42
43 fn demo_draft(inner_thread_id: &str, html: &str, send_at: DateTime<Utc>) -> ScheduledDraft {
44 ScheduledDraft {
45 id: Uuid::new_v4().to_string(),
46 client_message_id: Uuid::new_v4().to_string(),
47 inner_thread_id: inner_thread_id.to_owned(),
48 send_at,
49 html: html.to_owned(),
50 delivery_state: None,
51 }
52 }
53
54 impl ConversationView {
55 fn scheduled_thread_id(&self) -> Option<String> {
56 let current = self.current.as_ref()?;
57 let conversation_id = current.selection.conversation_id();
58 Some(match &current.mode {
59 ViewMode::Thread(root_id) => format!("{conversation_id};messageid={root_id}"),
60 _ => conversation_id.to_owned(),
61 })
62 }
63
64 pub(super) fn scheduled_rows(&self, my_user_id: Option<&str>, cx: &App) -> Vec<Row> {
65 let (Some(inner_thread_id), Some(conversation_id)) =
66 (self.scheduled_thread_id(), self.conversation_id())
67 else {
68 return Vec::new();
69 };
70 let change_failed = self
71 .scheduled_failure
72 .as_ref()
73 .map(|failure| failure.draft_id.as_str());
74 scheduled_rows(
75 &self.app.read(cx).scheduled,
76 &inner_thread_id,
77 &conversation_id,
78 my_user_id,
79 Utc::now(),
80 change_failed,
81 )
82 .into_iter()
83 .map(|row| Row::Message(Box::new(row)))
84 .collect()
85 }
86
87 fn scheduled_draft(&self, draft_id: &str, cx: &App) -> Option<ScheduledDraft> {
88 self.app
89 .read(cx)
90 .scheduled
91 .iter()
92 .find(|draft| draft_key(draft) == draft_id)
93 .cloned()
94 }
95
96 fn scheduled_engine(&mut self, cx: &mut Context<Self>) -> Option<Arc<Engine>> {
97 let state = self.app.read(cx);
98 let engine = state.engine.clone().filter(|_| !state.mode.read_only);
99 if engine.is_none() {
100 self.notice = Some("Read-only mode: nothing was changed".to_owned());
101 cx.notify();
102 }
103 engine
104 }
105
106 pub(super) fn schedule(
107 &mut self,
108 outgoing: Outgoing,
109 send_at: DateTime<Utc>,
110 window: &mut Window,
111 cx: &mut Context<Self>,
112 ) {
113 let (Some(inner_thread_id), Some(conversation_id)) =
114 (self.scheduled_thread_id(), self.conversation_id())
115 else {
116 return;
117 };
118 let html = outgoing.html();
119 if self.app.read(cx).mode.demo {
120 let draft = demo_draft(&inner_thread_id, &html, send_at);
121 self.app
122 .update(cx, |state, cx| state.scheduled_upserted(draft, cx));
123 self.finish_scheduling(&conversation_id, window, cx);
124 return;
125 }
126 let Some(engine) = self.scheduled_engine(cx) else {
127 self.composer
128 .update(cx, |composer, cx| composer.fail_schedule(cx));
129 return;
130 };
131 let thread_root_id = match self.current.as_ref().map(|current| &current.mode) {
132 Some(ViewMode::Thread(root_id)) => Some(root_id.clone()),
133 _ => None,
134 };
135 let target = conversation_id.clone();
136 let receiver = runtime::spawn(async move {
137 engine
138 .schedule_message(&target, thread_root_id.as_deref(), &html, send_at)
139 .await
140 });
141 cx.spawn_in(window, async move |this, cx| {
142 let result = receiver.await;
143 this.update_in(cx, |this, window, cx| match result {
144 Ok(Ok(draft)) => {
145 this.app
146 .update(cx, |state, cx| state.scheduled_upserted(draft, cx));
147 this.finish_scheduling(&conversation_id, window, cx);
148 }
149 Ok(Err(error)) => this.fail_scheduling(&short_error(&error), cx),
150 Err(error) => this.fail_scheduling(&short_error(&error), cx),
151 })
152 .ok();
153 })
154 .detach();
155 }
156
157 fn finish_scheduling(
158 &mut self,
159 conversation_id: &str,
160 window: &mut Window,
161 cx: &mut Context<Self>,
162 ) {
163 self.notice = None;
164 self.composer.update(cx, |composer, cx| {
165 composer.finish_schedule(conversation_id, window, cx)
166 });
167 self.rebuild(false, cx);
168 self.scroller
169 .update(cx, |scroller, cx| scroller.scroll_to_end(cx));
170 }
171
172 fn fail_scheduling(&mut self, error: &str, cx: &mut Context<Self>) {
173 self.notice = Some(format!("Couldn't schedule: {error}"));
174 self.composer
175 .update(cx, |composer, cx| composer.fail_schedule(cx));
176 cx.notify();
177 }
178
179 pub(super) fn begin_scheduled_edit(
180 &mut self,
181 draft_id: &str,
182 window: &mut Window,
183 cx: &mut Context<Self>,
184 ) {
185 let Some(draft) = self
186 .scheduled_draft(draft_id, cx)
187 .filter(|draft| !draft.id.is_empty())
188 else {
189 return;
190 };
191 let mut outgoing = scheduled_outgoing(&draft.html);
192 let excerpt = outgoing
193 .text()
194 .lines()
195 .map(str::trim)
196 .find(|line| !line.is_empty())
197 .map(|line| truncated(line, EXCERPT_CHARS))
198 .unwrap_or_default();
199 outgoing.edit = Some(EditPreview {
200 message_id: draft.id,
201 excerpt,
202 scheduled: Some(draft.send_at),
203 });
204 self.composer
205 .update(cx, |composer, cx| composer.begin_edit(outgoing, window, cx));
206 }
207
208 pub(super) fn send_scheduled_edit(
209 &mut self,
210 outgoing: Outgoing,
211 window: &mut Window,
212 cx: &mut Context<Self>,
213 ) {
214 let Some(edit) = outgoing.edit.as_ref() else {
215 return;
216 };
217 self.change_scheduled(
218 &edit.message_id.clone(),
219 ScheduledAction::Update(outgoing.html()),
220 window,
221 cx,
222 );
223 }
224
225 pub(super) fn send_scheduled_now(
226 &mut self,
227 draft_id: &str,
228 window: &mut Window,
229 cx: &mut Context<Self>,
230 ) {
231 self.change_scheduled(draft_id, ScheduledAction::SendNow, window, cx);
232 }
233
234 pub(super) fn delete_scheduled(
235 &mut self,
236 draft_id: &str,
237 window: &mut Window,
238 cx: &mut Context<Self>,
239 ) {
240 self.change_scheduled(draft_id, ScheduledAction::Delete, window, cx);
241 }
242
243 pub(super) fn retry_scheduled(&mut self, window: &mut Window, cx: &mut Context<Self>) {
244 if let Some(failure) = self.scheduled_failure.take() {
245 self.change_scheduled(&failure.draft_id, failure.action, window, cx);
246 }
247 }
248
249 fn change_scheduled(
250 &mut self,
251 draft_id: &str,
252 action: ScheduledAction,
253 window: &mut Window,
254 cx: &mut Context<Self>,
255 ) {
256 let Some(draft) = self
257 .scheduled_draft(draft_id, cx)
258 .filter(|draft| !draft.id.is_empty())
259 else {
260 return;
261 };
262 if !self.scheduled_in_flight.insert(draft.id.clone()) {
263 return;
264 }
265 self.scheduled_failure = None;
266 if self.app.read(cx).mode.demo {
267 self.scheduled_in_flight.remove(&draft.id);
268 self.apply_scheduled_change(&draft, &action, cx);
269 return;
270 }
271 let Some(engine) = self.scheduled_engine(cx) else {
272 self.scheduled_in_flight.remove(&draft.id);
273 return;
274 };
275 let (call_draft, call_action) = (draft.clone(), action.clone());
276 let receiver = runtime::spawn(async move {
277 match call_action {
278 ScheduledAction::Update(html) => {
279 engine.update_scheduled(&call_draft, &html).await.map(Some)
280 }
281 ScheduledAction::SendNow | ScheduledAction::Delete => {
282 engine.cancel_scheduled(&call_draft.id).await.map(|_| None)
283 }
284 }
285 });
286 cx.spawn_in(window, async move |this, cx| {
287 let result = receiver.await;
288 this.update_in(cx, |this, _, cx| {
289 this.scheduled_in_flight.remove(&draft.id);
290 match result {
291 Ok(Ok(Some(updated))) => {
292 this.app
293 .update(cx, |state, cx| state.scheduled_upserted(updated, cx));
294 this.rebuild(false, cx);
295 }
296 Ok(Ok(None)) => this.apply_scheduled_change(&draft, &action, cx),
297 _ => {
298 this.scheduled_failure = Some(ScheduledFailure {
299 draft_id: draft.id.clone(),
300 action,
301 });
302 this.rebuild(false, cx);
303 }
304 }
305 })
306 .ok();
307 })
308 .detach();
309 }
310
311 fn apply_scheduled_change(
312 &mut self,
313 draft: &ScheduledDraft,
314 action: &ScheduledAction,
315 cx: &mut Context<Self>,
316 ) {
317 match action {
318 ScheduledAction::Update(html) => {
319 let updated = ScheduledDraft {
320 html: html.clone(),
321 ..draft.clone()
322 };
323 self.app
324 .update(cx, |state, cx| state.scheduled_upserted(updated, cx));
325 }
326 ScheduledAction::Delete => self
327 .app
328 .update(cx, |state, cx| state.scheduled_removed(&draft.id, cx)),
329 ScheduledAction::SendNow => {
330 self.app
331 .update(cx, |state, cx| state.scheduled_removed(&draft.id, cx));
332 self.deliver_now(draft, cx);
333 }
334 }
335 self.rebuild(false, cx);
336 }
337
338 fn deliver_now(&mut self, draft: &ScheduledDraft, cx: &mut Context<Self>) {
339 let state = self.app.read(cx);
340 let (Some(engine), store) = (state.engine.clone(), state.store.clone()) else {
341 return;
342 };
343 if state.mode.demo {
344 return;
345 }
346 let conversation_id = conversation_of(&draft.inner_thread_id).to_owned();
347 let thread_root_id = thread_root_of(&draft.inner_thread_id).map(str::to_owned);
348 let target = match (&thread_root_id, store.channel(&conversation_id)) {
349 (Some(_), _) => OutboxTarget::Thread,
350 (None, Ok(Some(_))) => OutboxTarget::Post,
351 (None, _) => OutboxTarget::Flat,
352 };
353 let outgoing = scheduled_outgoing(&draft.html);
354 let outbox_id = new_outbox_id();
355 if let Some(record) = outbox_record(
356 &outbox_id,
357 &conversation_id,
358 target,
359 thread_root_id.as_deref(),
360 &outgoing,
361 Utc::now(),
362 ) {
363 store.put_outbox(&record).ok();
364 }
365 let app = self.app.clone();
366 app.update(cx, |state, cx| {
367 state.outbox_changed(conversation_id.clone(), cx)
368 });
369 let delivery_target = conversation_id.clone();
370 let receiver = runtime::spawn(async move {
371 deliver(
372 &engine,
373 &delivery_target,
374 target,
375 thread_root_id.as_deref(),
376 &outgoing,
377 )
378 .await
379 });
380 cx.spawn(async move |_, cx| {
381 let failure = match receiver.await {
382 Ok(Ok(())) => None,
383 Ok(Err(error)) => Some(short_error(&error)),
384 Err(error) => Some(short_error(&error)),
385 };
386 match failure {
387 None => store.delete_outbox(&outbox_id).ok(),
388 Some(error) => store.mark_outbox_failed(&outbox_id, &error).ok(),
389 };
390 app.update(cx, |state, cx| state.outbox_changed(conversation_id, cx));
391 })
392 .detach();
393 }
394
395 pub(super) fn scheduled_row_actions(
396 &self,
397 row: &MessageRow,
398 view: &WeakEntity<Self>,
399 window: &Window,
400 cx: &App,
401 ) -> Option<ScheduledRowActions> {
402 let draft_id = draft_id_of(&row.key)?.to_owned();
403 let handle = window.window_handle();
404 let link = |run: fn(&mut Self, &str, &mut Window, &mut Context<Self>)| -> RowAction {
405 let (view, draft_id) = (view.clone(), draft_id.clone());
406 Some(Box::new(move |cx: &mut App| {
407 let (view, draft_id) = (view.clone(), draft_id.clone());
408 handle
409 .update(cx, move |_, window, cx| {
410 view.update(cx, |this, cx| run(this, &draft_id, window, cx))
411 .ok();
412 })
413 .ok();
414 }))
415 };
416 let retry: RowAction = {
417 let view = view.clone();
418 Some(Box::new(move |cx: &mut App| {
419 let view = view.clone();
420 handle
421 .update(cx, move |_, window, cx| {
422 view.update(cx, |this, cx| this.retry_scheduled(window, cx))
423 .ok();
424 })
425 .ok();
426 }))
427 };
428 let action = |run: fn(&mut Self, &str, &mut Window, &mut Context<Self>)| -> Action {
429 let (view, draft_id) = (view.clone(), draft_id.clone());
430 Rc::new(move |window, cx| {
431 view.update(cx, |this, cx| run(this, &draft_id, window, cx))
432 .ok();
433 })
434 };
435 let hover = |slot: HoverSlot| -> HoverChange {
436 let (view, key) = (view.clone(), row.key.clone());
437 Rc::new(move |hovered: bool, cx: &mut App| {
438 view.update(cx, |this, cx| this.set_hover(slot, &key, hovered, cx))
439 .ok();
440 })
441 };
442 let visible = view
443 .upgrade()
444 .is_some_and(|entity| entity.read(cx).toolbar_visible(&row.key));
445 Some(ScheduledRowActions {
446 delivery: DeliveryActions {
447 retry,
448 delete: link(Self::delete_scheduled),
449 send_now: link(Self::send_scheduled_now),
450 },
451 menu: visible.then(|| ScheduledMenu {
452 key: row.key.clone(),
453 edit: action(Self::begin_scheduled_edit),
454 send_now: action(Self::send_scheduled_now),
455 delete: action(Self::delete_scheduled),
456 hover: hover(HoverSlot::Toolbar),
457 }),
458 hovered: hover(HoverSlot::Row),
459 })
460 }
461 }
@@ -0,0 +1,461 @@
1use std::rc::Rc;
2
3use chrono::{DateTime, Utc};
4use gpui_kit::*;
5use store::OutboxTarget;
6use teams_core::ScheduledDraft;
7use uuid::Uuid;
8
9use super::{ConversationView, HoverSlot, ViewMode};
10use crate::backend::Engine;
11use crate::notice::{short_error, truncated};
12use crate::outbox::{deliver, new_outbox_id, outbox_record};
13use crate::rows::{MessageRow, Row};
14use crate::runtime;
15use crate::scheduled::{conversation_of, thread_root_of};
16use crate::scheduled_rows::{draft_id_of, draft_key, scheduled_outgoing, scheduled_rows};
17use crate::views::composer::{EditPreview, Outgoing};
18use crate::views::message_actions::{Action, HoverChange};
19use crate::views::message_row::{DeliveryActions, RowAction};
20use crate::views::scheduled_toolbar::ScheduledMenu;
21use std::sync::Arc;
22
23const EXCERPT_CHARS: usize = 140;
24
25#[derive(Clone)]
26pub(super) enum ScheduledAction {
27 Update(String),
28 SendNow,
29 Delete,
30}
31
32pub(super) struct ScheduledFailure {
33 draft_id: String,
34 action: ScheduledAction,
35}
36
37pub(super) struct ScheduledRowActions {
38 pub delivery: DeliveryActions,
39 pub menu: Option<ScheduledMenu>,
40 pub hovered: HoverChange,
41}
42
43fn demo_draft(inner_thread_id: &str, html: &str, send_at: DateTime<Utc>) -> ScheduledDraft {
44 ScheduledDraft {
45 id: Uuid::new_v4().to_string(),
46 client_message_id: Uuid::new_v4().to_string(),
47 inner_thread_id: inner_thread_id.to_owned(),
48 send_at,
49 html: html.to_owned(),
50 delivery_state: None,
51 }
52}
53
54impl ConversationView {
55 fn scheduled_thread_id(&self) -> Option<String> {
56 let current = self.current.as_ref()?;
57 let conversation_id = current.selection.conversation_id();
58 Some(match &current.mode {
59 ViewMode::Thread(root_id) => format!("{conversation_id};messageid={root_id}"),
60 _ => conversation_id.to_owned(),
61 })
62 }
63
64 pub(super) fn scheduled_rows(&self, my_user_id: Option<&str>, cx: &App) -> Vec<Row> {
65 let (Some(inner_thread_id), Some(conversation_id)) =
66 (self.scheduled_thread_id(), self.conversation_id())
67 else {
68 return Vec::new();
69 };
70 let change_failed = self
71 .scheduled_failure
72 .as_ref()
73 .map(|failure| failure.draft_id.as_str());
74 scheduled_rows(
75 &self.app.read(cx).scheduled,
76 &inner_thread_id,
77 &conversation_id,
78 my_user_id,
79 Utc::now(),
80 change_failed,
81 )
82 .into_iter()
83 .map(|row| Row::Message(Box::new(row)))
84 .collect()
85 }
86
87 fn scheduled_draft(&self, draft_id: &str, cx: &App) -> Option<ScheduledDraft> {
88 self.app
89 .read(cx)
90 .scheduled
91 .iter()
92 .find(|draft| draft_key(draft) == draft_id)
93 .cloned()
94 }
95
96 fn scheduled_engine(&mut self, cx: &mut Context<Self>) -> Option<Arc<Engine>> {
97 let state = self.app.read(cx);
98 let engine = state.engine.clone().filter(|_| !state.mode.read_only);
99 if engine.is_none() {
100 self.notice = Some("Read-only mode: nothing was changed".to_owned());
101 cx.notify();
102 }
103 engine
104 }
105
106 pub(super) fn schedule(
107 &mut self,
108 outgoing: Outgoing,
109 send_at: DateTime<Utc>,
110 window: &mut Window,
111 cx: &mut Context<Self>,
112 ) {
113 let (Some(inner_thread_id), Some(conversation_id)) =
114 (self.scheduled_thread_id(), self.conversation_id())
115 else {
116 return;
117 };
118 let html = outgoing.html();
119 if self.app.read(cx).mode.demo {
120 let draft = demo_draft(&inner_thread_id, &html, send_at);
121 self.app
122 .update(cx, |state, cx| state.scheduled_upserted(draft, cx));
123 self.finish_scheduling(&conversation_id, window, cx);
124 return;
125 }
126 let Some(engine) = self.scheduled_engine(cx) else {
127 self.composer
128 .update(cx, |composer, cx| composer.fail_schedule(cx));
129 return;
130 };
131 let thread_root_id = match self.current.as_ref().map(|current| &current.mode) {
132 Some(ViewMode::Thread(root_id)) => Some(root_id.clone()),
133 _ => None,
134 };
135 let target = conversation_id.clone();
136 let receiver = runtime::spawn(async move {
137 engine
138 .schedule_message(&target, thread_root_id.as_deref(), &html, send_at)
139 .await
140 });
141 cx.spawn_in(window, async move |this, cx| {
142 let result = receiver.await;
143 this.update_in(cx, |this, window, cx| match result {
144 Ok(Ok(draft)) => {
145 this.app
146 .update(cx, |state, cx| state.scheduled_upserted(draft, cx));
147 this.finish_scheduling(&conversation_id, window, cx);
148 }
149 Ok(Err(error)) => this.fail_scheduling(&short_error(&error), cx),
150 Err(error) => this.fail_scheduling(&short_error(&error), cx),
151 })
152 .ok();
153 })
154 .detach();
155 }
156
157 fn finish_scheduling(
158 &mut self,
159 conversation_id: &str,
160 window: &mut Window,
161 cx: &mut Context<Self>,
162 ) {
163 self.notice = None;
164 self.composer.update(cx, |composer, cx| {
165 composer.finish_schedule(conversation_id, window, cx)
166 });
167 self.rebuild(false, cx);
168 self.scroller
169 .update(cx, |scroller, cx| scroller.scroll_to_end(cx));
170 }
171
172 fn fail_scheduling(&mut self, error: &str, cx: &mut Context<Self>) {
173 self.notice = Some(format!("Couldn't schedule: {error}"));
174 self.composer
175 .update(cx, |composer, cx| composer.fail_schedule(cx));
176 cx.notify();
177 }
178
179 pub(super) fn begin_scheduled_edit(
180 &mut self,
181 draft_id: &str,
182 window: &mut Window,
183 cx: &mut Context<Self>,
184 ) {
185 let Some(draft) = self
186 .scheduled_draft(draft_id, cx)
187 .filter(|draft| !draft.id.is_empty())
188 else {
189 return;
190 };
191 let mut outgoing = scheduled_outgoing(&draft.html);
192 let excerpt = outgoing
193 .text()
194 .lines()
195 .map(str::trim)
196 .find(|line| !line.is_empty())
197 .map(|line| truncated(line, EXCERPT_CHARS))
198 .unwrap_or_default();
199 outgoing.edit = Some(EditPreview {
200 message_id: draft.id,
201 excerpt,
202 scheduled: Some(draft.send_at),
203 });
204 self.composer
205 .update(cx, |composer, cx| composer.begin_edit(outgoing, window, cx));
206 }
207
208 pub(super) fn send_scheduled_edit(
209 &mut self,
210 outgoing: Outgoing,
211 window: &mut Window,
212 cx: &mut Context<Self>,
213 ) {
214 let Some(edit) = outgoing.edit.as_ref() else {
215 return;
216 };
217 self.change_scheduled(
218 &edit.message_id.clone(),
219 ScheduledAction::Update(outgoing.html()),
220 window,
221 cx,
222 );
223 }
224
225 pub(super) fn send_scheduled_now(
226 &mut self,
227 draft_id: &str,
228 window: &mut Window,
229 cx: &mut Context<Self>,
230 ) {
231 self.change_scheduled(draft_id, ScheduledAction::SendNow, window, cx);
232 }
233
234 pub(super) fn delete_scheduled(
235 &mut self,
236 draft_id: &str,
237 window: &mut Window,
238 cx: &mut Context<Self>,
239 ) {
240 self.change_scheduled(draft_id, ScheduledAction::Delete, window, cx);
241 }
242
243 pub(super) fn retry_scheduled(&mut self, window: &mut Window, cx: &mut Context<Self>) {
244 if let Some(failure) = self.scheduled_failure.take() {
245 self.change_scheduled(&failure.draft_id, failure.action, window, cx);
246 }
247 }
248
249 fn change_scheduled(
250 &mut self,
251 draft_id: &str,
252 action: ScheduledAction,
253 window: &mut Window,
254 cx: &mut Context<Self>,
255 ) {
256 let Some(draft) = self
257 .scheduled_draft(draft_id, cx)
258 .filter(|draft| !draft.id.is_empty())
259 else {
260 return;
261 };
262 if !self.scheduled_in_flight.insert(draft.id.clone()) {
263 return;
264 }
265 self.scheduled_failure = None;
266 if self.app.read(cx).mode.demo {
267 self.scheduled_in_flight.remove(&draft.id);
268 self.apply_scheduled_change(&draft, &action, cx);
269 return;
270 }
271 let Some(engine) = self.scheduled_engine(cx) else {
272 self.scheduled_in_flight.remove(&draft.id);
273 return;
274 };
275 let (call_draft, call_action) = (draft.clone(), action.clone());
276 let receiver = runtime::spawn(async move {
277 match call_action {
278 ScheduledAction::Update(html) => {
279 engine.update_scheduled(&call_draft, &html).await.map(Some)
280 }
281 ScheduledAction::SendNow | ScheduledAction::Delete => {
282 engine.cancel_scheduled(&call_draft.id).await.map(|_| None)
283 }
284 }
285 });
286 cx.spawn_in(window, async move |this, cx| {
287 let result = receiver.await;
288 this.update_in(cx, |this, _, cx| {
289 this.scheduled_in_flight.remove(&draft.id);
290 match result {
291 Ok(Ok(Some(updated))) => {
292 this.app
293 .update(cx, |state, cx| state.scheduled_upserted(updated, cx));
294 this.rebuild(false, cx);
295 }
296 Ok(Ok(None)) => this.apply_scheduled_change(&draft, &action, cx),
297 _ => {
298 this.scheduled_failure = Some(ScheduledFailure {
299 draft_id: draft.id.clone(),
300 action,
301 });
302 this.rebuild(false, cx);
303 }
304 }
305 })
306 .ok();
307 })
308 .detach();
309 }
310
311 fn apply_scheduled_change(
312 &mut self,
313 draft: &ScheduledDraft,
314 action: &ScheduledAction,
315 cx: &mut Context<Self>,
316 ) {
317 match action {
318 ScheduledAction::Update(html) => {
319 let updated = ScheduledDraft {
320 html: html.clone(),
321 ..draft.clone()
322 };
323 self.app
324 .update(cx, |state, cx| state.scheduled_upserted(updated, cx));
325 }
326 ScheduledAction::Delete => self
327 .app
328 .update(cx, |state, cx| state.scheduled_removed(&draft.id, cx)),
329 ScheduledAction::SendNow => {
330 self.app
331 .update(cx, |state, cx| state.scheduled_removed(&draft.id, cx));
332 self.deliver_now(draft, cx);
333 }
334 }
335 self.rebuild(false, cx);
336 }
337
338 fn deliver_now(&mut self, draft: &ScheduledDraft, cx: &mut Context<Self>) {
339 let state = self.app.read(cx);
340 let (Some(engine), store) = (state.engine.clone(), state.store.clone()) else {
341 return;
342 };
343 if state.mode.demo {
344 return;
345 }
346 let conversation_id = conversation_of(&draft.inner_thread_id).to_owned();
347 let thread_root_id = thread_root_of(&draft.inner_thread_id).map(str::to_owned);
348 let target = match (&thread_root_id, store.channel(&conversation_id)) {
349 (Some(_), _) => OutboxTarget::Thread,
350 (None, Ok(Some(_))) => OutboxTarget::Post,
351 (None, _) => OutboxTarget::Flat,
352 };
353 let outgoing = scheduled_outgoing(&draft.html);
354 let outbox_id = new_outbox_id();
355 if let Some(record) = outbox_record(
356 &outbox_id,
357 &conversation_id,
358 target,
359 thread_root_id.as_deref(),
360 &outgoing,
361 Utc::now(),
362 ) {
363 store.put_outbox(&record).ok();
364 }
365 let app = self.app.clone();
366 app.update(cx, |state, cx| {
367 state.outbox_changed(conversation_id.clone(), cx)
368 });
369 let delivery_target = conversation_id.clone();
370 let receiver = runtime::spawn(async move {
371 deliver(
372 &engine,
373 &delivery_target,
374 target,
375 thread_root_id.as_deref(),
376 &outgoing,
377 )
378 .await
379 });
380 cx.spawn(async move |_, cx| {
381 let failure = match receiver.await {
382 Ok(Ok(())) => None,
383 Ok(Err(error)) => Some(short_error(&error)),
384 Err(error) => Some(short_error(&error)),
385 };
386 match failure {
387 None => store.delete_outbox(&outbox_id).ok(),
388 Some(error) => store.mark_outbox_failed(&outbox_id, &error).ok(),
389 };
390 app.update(cx, |state, cx| state.outbox_changed(conversation_id, cx));
391 })
392 .detach();
393 }
394
395 pub(super) fn scheduled_row_actions(
396 &self,
397 row: &MessageRow,
398 view: &WeakEntity<Self>,
399 window: &Window,
400 cx: &App,
401 ) -> Option<ScheduledRowActions> {
402 let draft_id = draft_id_of(&row.key)?.to_owned();
403 let handle = window.window_handle();
404 let link = |run: fn(&mut Self, &str, &mut Window, &mut Context<Self>)| -> RowAction {
405 let (view, draft_id) = (view.clone(), draft_id.clone());
406 Some(Box::new(move |cx: &mut App| {
407 let (view, draft_id) = (view.clone(), draft_id.clone());
408 handle
409 .update(cx, move |_, window, cx| {
410 view.update(cx, |this, cx| run(this, &draft_id, window, cx))
411 .ok();
412 })
413 .ok();
414 }))
415 };
416 let retry: RowAction = {
417 let view = view.clone();
418 Some(Box::new(move |cx: &mut App| {
419 let view = view.clone();
420 handle
421 .update(cx, move |_, window, cx| {
422 view.update(cx, |this, cx| this.retry_scheduled(window, cx))
423 .ok();
424 })
425 .ok();
426 }))
427 };
428 let action = |run: fn(&mut Self, &str, &mut Window, &mut Context<Self>)| -> Action {
429 let (view, draft_id) = (view.clone(), draft_id.clone());
430 Rc::new(move |window, cx| {
431 view.update(cx, |this, cx| run(this, &draft_id, window, cx))
432 .ok();
433 })
434 };
435 let hover = |slot: HoverSlot| -> HoverChange {
436 let (view, key) = (view.clone(), row.key.clone());
437 Rc::new(move |hovered: bool, cx: &mut App| {
438 view.update(cx, |this, cx| this.set_hover(slot, &key, hovered, cx))
439 .ok();
440 })
441 };
442 let visible = view
443 .upgrade()
444 .is_some_and(|entity| entity.read(cx).toolbar_visible(&row.key));
445 Some(ScheduledRowActions {
446 delivery: DeliveryActions {
447 retry,
448 delete: link(Self::delete_scheduled),
449 send_now: link(Self::send_scheduled_now),
450 },
451 menu: visible.then(|| ScheduledMenu {
452 key: row.key.clone(),
453 edit: action(Self::begin_scheduled_edit),
454 send_now: action(Self::send_scheduled_now),
455 delete: action(Self::delete_scheduled),
456 hover: hover(HoverSlot::Toolbar),
457 }),
458 hovered: hover(HoverSlot::Row),
459 })
460 }
461}
crates/app/src/views/message_actions.rs +1 −1
@@ -44,7 +44,7 @@ fn element_id(prefix: &str, key: &str) -> ElementId {
44 44 ElementId::Name(format!("{prefix}-{key}").into())
45 45 }
46 46
47 fn bar_button(id: ElementId) -> Stateful<Div> {
47 pub(super) fn bar_button(id: ElementId) -> Stateful<Div> {
48 48 div()
49 49 .id(id)
50 50 .size(px(BAR_BUTTON))
@@ -44,7 +44,7 @@ fn element_id(prefix: &str, key: &str) -> ElementId {
44 ElementId::Name(format!("{prefix}-{key}").into())
44 ElementId::Name(format!("{prefix}-{key}").into())
45}
45}
46
46
47fn bar_button(id: ElementId) -> Stateful<Div> {
47pub(super) fn bar_button(id: ElementId) -> Stateful<Div> {
48 div()
48 div()
49 .id(id)
49 .id(id)
50 .size(px(BAR_BUTTON))
50 .size(px(BAR_BUTTON))
crates/app/src/views/message_row.rs +95 −31
@@ -11,11 +11,12 @@ use super::link_preview::link_preview_card;
11 11 use super::message_actions::{HoverChange, MessageMenu, message_toolbar};
12 12 use super::reaction_picker::PickHandler;
13 13 use super::reaction_pills::{ReactionControls, reaction_pills};
14 use super::scheduled_toolbar::{ScheduledMenu, scheduled_toolbar};
14 15 use super::widgets::symbol;
15 16 use crate::card_state::BotIdentity;
16 17 use crate::data::Directory;
17 18 use crate::render::Block;
18 use crate::rows::{Delivery, MessageRow, Receipt, Skeleton, bubble_corners};
19 use crate::rows::{Delivery, MessageRow, Receipt, ScheduledState, Skeleton, bubble_corners};
19 20 use crate::sidebar_model::DELETED_PREVIEW;
20 21 use crate::theme;
21 22
@@ -35,13 +36,20 @@ const FIGURE_SPACE_WIDTH: f32 = 7.4;
35 36 const PULSE_PERIOD: Duration = Duration::from_millis(1600);
36 37 const SKELETON_LINE_HEIGHT: f32 = 20.;
37 38
39 pub struct DeliveryActions {
40 pub retry: RowAction,
41 pub delete: RowAction,
42 pub send_now: RowAction,
43 }
44
38 45 pub struct RowActions {
39 46 pub bot: Option<BotIdentity>,
40 47 pub open_thread: RowAction,
41 pub retry: RowAction,
48 pub delivery: DeliveryActions,
42 49 pub reply: RowAction,
43 50 pub hovered: Option<HoverChange>,
44 51 pub menu: Option<MessageMenu>,
52 pub scheduled_menu: Option<ScheduledMenu>,
45 53 pub react: Option<PickHandler>,
46 54 pub reaction_controls: Option<ReactionControls>,
47 55 pub files: Option<FileActions>,
@@ -110,14 +118,27 @@ fn bubble(
110 118 .child(DELETED_PREVIEW);
111 119 }
112 120 let failed = matches!(row.delivery, Delivery::Failed(_));
121 let scheduled = matches!(row.delivery, Delivery::Scheduled(_));
113 122 element = element
114 .bg(if own && !failed {
115 theme::bubble_own()
116 } else {
117 theme::bubble_other()
123 .when(!scheduled, |bubble| {
124 bubble.bg(if own && !failed {
125 theme::bubble_own()
126 } else {
127 theme::bubble_other()
128 })
118 129 })
119 130 .when(failed, |bubble| {
120 131 bubble.border_1().border_color(theme::red())
132 })
133 .when(scheduled, |bubble| {
134 bubble
135 .border_1()
136 .border_dashed()
137 .border_color(if row.delivery == Delivery::Scheduled(ScheduledState::DeliveryFailed) {
138 theme::red()
139 } else {
140 theme::accent()
141 })
121 142 });
122 143 let has_reactions = !row.reactions.is_empty();
123 144 let mut content = v_flex().gap(px(6.));
@@ -208,6 +229,15 @@ fn bubble(
208 229 .child(deferred(message_toolbar(menu)).with_priority(1)),
209 230 );
210 231 }
232 if let Some(menu) = extras.scheduled_menu {
233 element = element.child(
234 div()
235 .absolute()
236 .top(px(-TOOLBAR_LIFT))
237 .right(px(8.))
238 .child(deferred(scheduled_toolbar(menu)).with_priority(1)),
239 );
240 }
211 241 element
212 242 }
213 243
@@ -215,6 +245,7 @@ fn bubble(
215 245 struct BubbleExtras {
216 246 hover: Option<HoverChange>,
217 247 menu: Option<MessageMenu>,
248 scheduled_menu: Option<ScheduledMenu>,
218 249 react: Option<PickHandler>,
219 250 controls: Option<ReactionControls>,
220 251 files: Option<FileActions>,
@@ -238,6 +269,9 @@ fn bubble_meta(row: &MessageRow, own: bool) -> Div {
238 269 .when(own && row.delivery == Delivery::Sending, |meta| {
239 270 meta.child(symbol("schedule", META_CHECK_SIZE, tint))
240 271 })
272 .when(matches!(row.delivery, Delivery::Scheduled(_)), |meta| {
273 meta.child(symbol("schedule", META_SIZE + 3., tint))
274 })
241 275 .when(
242 276 own && row.delivery == Delivery::Delivered,
243 277 |meta| match row.receipt {
@@ -338,26 +372,54 @@ fn has_text(row: &MessageRow) -> bool {
338 372 && row.adaptive_cards.is_empty())
339 373 }
340 374
341 fn delivery_note(row: &MessageRow, retry: RowAction, index: usize) -> Option<AnyElement> {
375 fn delivery_link(index: usize, name: &str, label: &'static str, action: RowAction) -> Stateful<Div> {
376 div()
377 .id(ElementId::Name(format!("{name}-{index}").into()))
378 .cursor_pointer()
379 .text_color(theme::red_tint())
380 .underline()
381 .child(label)
382 .when_some(action, |link, action| {
383 link.on_click(move |_, _, cx| action(cx))
384 })
385 }
386
387 fn delivery_note(
388 row: &MessageRow,
389 delivery: DeliveryActions,
390 index: usize,
391 ) -> Option<AnyElement> {
392 let DeliveryActions {
393 retry,
394 delete,
395 send_now,
396 } = delivery;
397 let note = |text: &'static str| {
398 h_flex()
399 .gap(px(4.))
400 .text_size(px(11.))
401 .text_color(theme::red_soft())
402 .child(text)
403 };
342 404 match &row.delivery {
343 Delivery::Delivered | Delivery::Sending => None,
405 Delivery::Delivered | Delivery::Sending | Delivery::Scheduled(ScheduledState::Waiting) => {
406 None
407 }
344 408 Delivery::Failed(_) => Some(
345 h_flex()
346 .gap(px(4.))
347 .text_size(px(11.))
348 .text_color(theme::red_soft())
349 .child("Failed to send.")
350 .child(
351 div()
352 .id(ElementId::Name(format!("retry-{index}").into()))
353 .cursor_pointer()
354 .text_color(theme::red_tint())
355 .underline()
356 .child("Retry")
357 .when_some(retry, |link, retry| {
358 link.on_click(move |_, _, cx| retry(cx))
359 }),
360 )
409 note("Failed to send.")
410 .child(delivery_link(index, "retry", "Retry", retry))
411 .child(delivery_link(index, "delete", "Delete", delete))
412 .into_any_element(),
413 ),
414 Delivery::Scheduled(ScheduledState::DeliveryFailed) => Some(
415 note("Couldn't send at the scheduled time.")
416 .child(delivery_link(index, "send-now", "Send now", send_now))
417 .child(delivery_link(index, "delete", "Delete", delete))
418 .into_any_element(),
419 ),
420 Delivery::Scheduled(ScheduledState::ChangeFailed) => Some(
421 note("Couldn't change the scheduled message.")
422 .child(delivery_link(index, "retry", "Retry", retry))
361 423 .into_any_element(),
362 424 ),
363 425 }
@@ -535,7 +597,7 @@ fn others_row(
535 597 index: usize,
536 598 directory: &Directory,
537 599 bot: Option<&BotIdentity>,
538 retry: RowAction,
600 delivery: DeliveryActions,
539 601 extras: BubbleExtras,
540 602 cx: &App,
541 603 ) -> Div {
@@ -557,7 +619,7 @@ fn others_row(
557 619 );
558 620 }
559 621 column = column.child(bubble(row, index, false, directory, extras, cx));
560 if let Some(note) = delivery_note(row, retry, index) {
622 if let Some(note) = delivery_note(row, delivery, index) {
561 623 column = column.child(note);
562 624 }
563 625 let lead = if let Some(bot) = bot.filter(|_| first || row.card) {
@@ -584,7 +646,7 @@ fn own_row(
584 646 row: &MessageRow,
585 647 index: usize,
586 648 directory: &Directory,
587 retry: RowAction,
649 delivery: DeliveryActions,
588 650 extras: BubbleExtras,
589 651 cx: &App,
590 652 ) -> Div {
@@ -594,7 +656,7 @@ fn own_row(
594 656 .max_w(relative(MAX_WIDTH_RATIO))
595 657 .child(bubble(row, index, true, directory, extras, cx)),
596 658 );
597 if let Some(note) = delivery_note(row, retry, index) {
659 if let Some(note) = delivery_note(row, delivery, index) {
598 660 column = column.child(note);
599 661 }
600 662 column
@@ -610,10 +672,11 @@ pub fn render_message_row(
610 672 let RowActions {
611 673 bot,
612 674 open_thread,
613 retry,
675 delivery,
614 676 reply,
615 677 hovered,
616 678 menu,
679 scheduled_menu,
617 680 react,
618 681 reaction_controls,
619 682 files,
@@ -623,6 +686,7 @@ pub fn render_message_row(
623 686 let extras = BubbleExtras {
624 687 hover: hovered,
625 688 menu,
689 scheduled_menu,
626 690 react,
627 691 controls: reaction_controls,
628 692 files,
@@ -645,9 +709,9 @@ pub fn render_message_row(
645 709 let body = if row.card {
646 710 post_card(row, index, directory, extras.files.as_ref(), cx)
647 711 } else if own {
648 own_row(row, index, directory, retry, extras, cx)
712 own_row(row, index, directory, delivery, extras, cx)
649 713 } else {
650 others_row(row, index, directory, bot.as_ref(), retry, extras, cx)
714 others_row(row, index, directory, bot.as_ref(), delivery, extras, cx)
651 715 };
652 716 container
653 717 .child(
@@ -11,11 +11,12 @@ use super::link_preview::link_preview_card;
11use super::message_actions::{HoverChange, MessageMenu, message_toolbar};
11use super::message_actions::{HoverChange, MessageMenu, message_toolbar};
12use super::reaction_picker::PickHandler;
12use super::reaction_picker::PickHandler;
13use super::reaction_pills::{ReactionControls, reaction_pills};
13use super::reaction_pills::{ReactionControls, reaction_pills};
14use super::scheduled_toolbar::{ScheduledMenu, scheduled_toolbar};
14use super::widgets::symbol;
15use super::widgets::symbol;
15use crate::card_state::BotIdentity;
16use crate::card_state::BotIdentity;
16use crate::data::Directory;
17use crate::data::Directory;
17use crate::render::Block;
18use crate::render::Block;
18use crate::rows::{Delivery, MessageRow, Receipt, Skeleton, bubble_corners};
19use crate::rows::{Delivery, MessageRow, Receipt, ScheduledState, Skeleton, bubble_corners};
19use crate::sidebar_model::DELETED_PREVIEW;
20use crate::sidebar_model::DELETED_PREVIEW;
20use crate::theme;
21use crate::theme;
21
22
@@ -35,13 +36,20 @@ const FIGURE_SPACE_WIDTH: f32 = 7.4;
35const PULSE_PERIOD: Duration = Duration::from_millis(1600);
36const PULSE_PERIOD: Duration = Duration::from_millis(1600);
36const SKELETON_LINE_HEIGHT: f32 = 20.;
37const SKELETON_LINE_HEIGHT: f32 = 20.;
37
38
39pub struct DeliveryActions {
40 pub retry: RowAction,
41 pub delete: RowAction,
42 pub send_now: RowAction,
43}
44
38pub struct RowActions {
45pub struct RowActions {
39 pub bot: Option<BotIdentity>,
46 pub bot: Option<BotIdentity>,
40 pub open_thread: RowAction,
47 pub open_thread: RowAction,
41 pub retry: RowAction,
48 pub delivery: DeliveryActions,
42 pub reply: RowAction,
49 pub reply: RowAction,
43 pub hovered: Option<HoverChange>,
50 pub hovered: Option<HoverChange>,
44 pub menu: Option<MessageMenu>,
51 pub menu: Option<MessageMenu>,
52 pub scheduled_menu: Option<ScheduledMenu>,
45 pub react: Option<PickHandler>,
53 pub react: Option<PickHandler>,
46 pub reaction_controls: Option<ReactionControls>,
54 pub reaction_controls: Option<ReactionControls>,
47 pub files: Option<FileActions>,
55 pub files: Option<FileActions>,
@@ -110,14 +118,27 @@ fn bubble(
110 .child(DELETED_PREVIEW);
118 .child(DELETED_PREVIEW);
111 }
119 }
112 let failed = matches!(row.delivery, Delivery::Failed(_));
120 let failed = matches!(row.delivery, Delivery::Failed(_));
121 let scheduled = matches!(row.delivery, Delivery::Scheduled(_));
113 element = element
122 element = element
114 .bg(if own && !failed {
123 .when(!scheduled, |bubble| {
115 theme::bubble_own()
124 bubble.bg(if own && !failed {
116 } else {
125 theme::bubble_own()
117 theme::bubble_other()
126 } else {
127 theme::bubble_other()
128 })
118 })
129 })
119 .when(failed, |bubble| {
130 .when(failed, |bubble| {
120 bubble.border_1().border_color(theme::red())
131 bubble.border_1().border_color(theme::red())
132 })
133 .when(scheduled, |bubble| {
134 bubble
135 .border_1()
136 .border_dashed()
137 .border_color(if row.delivery == Delivery::Scheduled(ScheduledState::DeliveryFailed) {
138 theme::red()
139 } else {
140 theme::accent()
141 })
121 });
142 });
122 let has_reactions = !row.reactions.is_empty();
143 let has_reactions = !row.reactions.is_empty();
123 let mut content = v_flex().gap(px(6.));
144 let mut content = v_flex().gap(px(6.));
@@ -208,6 +229,15 @@ fn bubble(
208 .child(deferred(message_toolbar(menu)).with_priority(1)),
229 .child(deferred(message_toolbar(menu)).with_priority(1)),
209 );
230 );
210 }
231 }
232 if let Some(menu) = extras.scheduled_menu {
233 element = element.child(
234 div()
235 .absolute()
236 .top(px(-TOOLBAR_LIFT))
237 .right(px(8.))
238 .child(deferred(scheduled_toolbar(menu)).with_priority(1)),
239 );
240 }
211 element
241 element
212}
242}
213
243
@@ -215,6 +245,7 @@ fn bubble(
215struct BubbleExtras {
245struct BubbleExtras {
216 hover: Option<HoverChange>,
246 hover: Option<HoverChange>,
217 menu: Option<MessageMenu>,
247 menu: Option<MessageMenu>,
248 scheduled_menu: Option<ScheduledMenu>,
218 react: Option<PickHandler>,
249 react: Option<PickHandler>,
219 controls: Option<ReactionControls>,
250 controls: Option<ReactionControls>,
220 files: Option<FileActions>,
251 files: Option<FileActions>,
@@ -238,6 +269,9 @@ fn bubble_meta(row: &MessageRow, own: bool) -> Div {
238 .when(own && row.delivery == Delivery::Sending, |meta| {
269 .when(own && row.delivery == Delivery::Sending, |meta| {
239 meta.child(symbol("schedule", META_CHECK_SIZE, tint))
270 meta.child(symbol("schedule", META_CHECK_SIZE, tint))
240 })
271 })
272 .when(matches!(row.delivery, Delivery::Scheduled(_)), |meta| {
273 meta.child(symbol("schedule", META_SIZE + 3., tint))
274 })
241 .when(
275 .when(
242 own && row.delivery == Delivery::Delivered,
276 own && row.delivery == Delivery::Delivered,
243 |meta| match row.receipt {
277 |meta| match row.receipt {
@@ -338,26 +372,54 @@ fn has_text(row: &MessageRow) -> bool {
338 && row.adaptive_cards.is_empty())
372 && row.adaptive_cards.is_empty())
339}
373}
340
374
341fn delivery_note(row: &MessageRow, retry: RowAction, index: usize) -> Option<AnyElement> {
375fn delivery_link(index: usize, name: &str, label: &'static str, action: RowAction) -> Stateful<Div> {
376 div()
377 .id(ElementId::Name(format!("{name}-{index}").into()))
378 .cursor_pointer()
379 .text_color(theme::red_tint())
380 .underline()
381 .child(label)
382 .when_some(action, |link, action| {
383 link.on_click(move |_, _, cx| action(cx))
384 })
385}
386
387fn delivery_note(
388 row: &MessageRow,
389 delivery: DeliveryActions,
390 index: usize,
391) -> Option<AnyElement> {
392 let DeliveryActions {
393 retry,
394 delete,
395 send_now,
396 } = delivery;
397 let note = |text: &'static str| {
398 h_flex()
399 .gap(px(4.))
400 .text_size(px(11.))
401 .text_color(theme::red_soft())
402 .child(text)
403 };
342 match &row.delivery {
404 match &row.delivery {
343 Delivery::Delivered | Delivery::Sending => None,
405 Delivery::Delivered | Delivery::Sending | Delivery::Scheduled(ScheduledState::Waiting) => {
406 None
407 }
344 Delivery::Failed(_) => Some(
408 Delivery::Failed(_) => Some(
345 h_flex()
409 note("Failed to send.")
346 .gap(px(4.))
410 .child(delivery_link(index, "retry", "Retry", retry))
347 .text_size(px(11.))
411 .child(delivery_link(index, "delete", "Delete", delete))
348 .text_color(theme::red_soft())
412 .into_any_element(),
349 .child("Failed to send.")
413 ),
350 .child(
414 Delivery::Scheduled(ScheduledState::DeliveryFailed) => Some(
351 div()
415 note("Couldn't send at the scheduled time.")
352 .id(ElementId::Name(format!("retry-{index}").into()))
416 .child(delivery_link(index, "send-now", "Send now", send_now))
353 .cursor_pointer()
417 .child(delivery_link(index, "delete", "Delete", delete))
354 .text_color(theme::red_tint())
418 .into_any_element(),
355 .underline()
419 ),
356 .child("Retry")
420 Delivery::Scheduled(ScheduledState::ChangeFailed) => Some(
357 .when_some(retry, |link, retry| {
421 note("Couldn't change the scheduled message.")
358 link.on_click(move |_, _, cx| retry(cx))
422 .child(delivery_link(index, "retry", "Retry", retry))
359 }),
360 )
361 .into_any_element(),
423 .into_any_element(),
362 ),
424 ),
363 }
425 }
@@ -535,7 +597,7 @@ fn others_row(
535 index: usize,
597 index: usize,
536 directory: &Directory,
598 directory: &Directory,
537 bot: Option<&BotIdentity>,
599 bot: Option<&BotIdentity>,
538 retry: RowAction,
600 delivery: DeliveryActions,
539 extras: BubbleExtras,
601 extras: BubbleExtras,
540 cx: &App,
602 cx: &App,
541) -> Div {
603) -> Div {
@@ -557,7 +619,7 @@ fn others_row(
557 );
619 );
558 }
620 }
559 column = column.child(bubble(row, index, false, directory, extras, cx));
621 column = column.child(bubble(row, index, false, directory, extras, cx));
560 if let Some(note) = delivery_note(row, retry, index) {
622 if let Some(note) = delivery_note(row, delivery, index) {
561 column = column.child(note);
623 column = column.child(note);
562 }
624 }
563 let lead = if let Some(bot) = bot.filter(|_| first || row.card) {
625 let lead = if let Some(bot) = bot.filter(|_| first || row.card) {
@@ -584,7 +646,7 @@ fn own_row(
584 row: &MessageRow,
646 row: &MessageRow,
585 index: usize,
647 index: usize,
586 directory: &Directory,
648 directory: &Directory,
587 retry: RowAction,
649 delivery: DeliveryActions,
588 extras: BubbleExtras,
650 extras: BubbleExtras,
589 cx: &App,
651 cx: &App,
590) -> Div {
652) -> Div {
@@ -594,7 +656,7 @@ fn own_row(
594 .max_w(relative(MAX_WIDTH_RATIO))
656 .max_w(relative(MAX_WIDTH_RATIO))
595 .child(bubble(row, index, true, directory, extras, cx)),
657 .child(bubble(row, index, true, directory, extras, cx)),
596 );
658 );
597 if let Some(note) = delivery_note(row, retry, index) {
659 if let Some(note) = delivery_note(row, delivery, index) {
598 column = column.child(note);
660 column = column.child(note);
599 }
661 }
600 column
662 column
@@ -610,10 +672,11 @@ pub fn render_message_row(
610 let RowActions {
672 let RowActions {
611 bot,
673 bot,
612 open_thread,
674 open_thread,
613 retry,
675 delivery,
614 reply,
676 reply,
615 hovered,
677 hovered,
616 menu,
678 menu,
679 scheduled_menu,
617 react,
680 react,
618 reaction_controls,
681 reaction_controls,
619 files,
682 files,
@@ -623,6 +686,7 @@ pub fn render_message_row(
623 let extras = BubbleExtras {
686 let extras = BubbleExtras {
624 hover: hovered,
687 hover: hovered,
625 menu,
688 menu,
689 scheduled_menu,
626 react,
690 react,
627 controls: reaction_controls,
691 controls: reaction_controls,
628 files,
692 files,
@@ -645,9 +709,9 @@ pub fn render_message_row(
645 let body = if row.card {
709 let body = if row.card {
646 post_card(row, index, directory, extras.files.as_ref(), cx)
710 post_card(row, index, directory, extras.files.as_ref(), cx)
647 } else if own {
711 } else if own {
648 own_row(row, index, directory, retry, extras, cx)
712 own_row(row, index, directory, delivery, extras, cx)
649 } else {
713 } else {
650 others_row(row, index, directory, bot.as_ref(), retry, extras, cx)
714 others_row(row, index, directory, bot.as_ref(), delivery, extras, cx)
651 };
715 };
652 container
716 container
653 .child(
717 .child(
crates/app/src/views/mod.rs +1 −0
@@ -17,6 +17,7 @@ pub mod message_row;
17 17 pub mod new_chat;
18 18 pub mod reaction_picker;
19 19 pub mod reaction_pills;
20 pub mod scheduled_toolbar;
20 21 pub mod shell;
21 22 pub mod sidebar;
22 23 pub mod status_bar;
@@ -17,6 +17,7 @@ pub mod message_row;
17pub mod new_chat;
17pub mod new_chat;
18pub mod reaction_picker;
18pub mod reaction_picker;
19pub mod reaction_pills;
19pub mod reaction_pills;
20pub mod scheduled_toolbar;
20pub mod shell;
21pub mod shell;
21pub mod sidebar;
22pub mod sidebar;
22pub mod status_bar;
23pub mod status_bar;
crates/app/src/views/scheduled_toolbar.rs added +78 −0
@@ -0,0 +1,78 @@
1 use gpui_kit::assets::IconName;
2 use gpui_kit::base::GlobalState;
3 use gpui_kit::component::h_flex;
4 use gpui_kit::*;
5
6 use super::message_actions::{Action, HoverChange, bar_button};
7 use super::widgets::icon;
8 use crate::theme;
9
10 pub struct ScheduledMenu {
11 pub key: String,
12 pub edit: Action,
13 pub send_now: Action,
14 pub delete: Action,
15 pub hover: HoverChange,
16 }
17
18 fn element_id(prefix: &str, key: &str) -> ElementId {
19 ElementId::Name(format!("{prefix}-{key}").into())
20 }
21
22 fn text_button(id: ElementId, label: &'static str) -> Stateful<Div> {
23 bar_button(id)
24 .w_auto()
25 .px(px(8.))
26 .text_size(px(12.5))
27 .text_color(theme::text_soft())
28 .child(label)
29 }
30
31 pub fn scheduled_toolbar(menu: ScheduledMenu) -> AnyElement {
32 let ScheduledMenu {
33 key,
34 edit,
35 send_now,
36 delete,
37 hover,
38 } = menu;
39 h_flex()
40 .id(element_id("scheduled-toolbar", &key))
41 .p(px(2.))
42 .gap(px(2.))
43 .items_center()
44 .rounded(px(8.))
45 .bg(theme::surface())
46 .border_1()
47 .border_color(theme::border_strong())
48 .occlude()
49 .on_hover(move |hovered, _, cx| hover(*hovered, cx))
50 .on_mouse_down(MouseButton::Left, |_, _, cx| {
51 GlobalState::suppress_text_selection(cx)
52 })
53 .child(
54 text_button(element_id("scheduled-edit", &key), "Edit").on_click(
55 move |_, window, cx| {
56 cx.stop_propagation();
57 edit(window, cx);
58 },
59 ),
60 )
61 .child(
62 text_button(element_id("scheduled-send-now", &key), "Send now").on_click(
63 move |_, window, cx| {
64 cx.stop_propagation();
65 send_now(window, cx);
66 },
67 ),
68 )
69 .child(
70 bar_button(element_id("scheduled-delete", &key))
71 .child(icon(IconName::Trash, 16., theme::red_soft()))
72 .on_click(move |_, window, cx| {
73 cx.stop_propagation();
74 delete(window, cx);
75 }),
76 )
77 .into_any_element()
78 }
@@ -0,0 +1,78 @@
1use gpui_kit::assets::IconName;
2use gpui_kit::base::GlobalState;
3use gpui_kit::component::h_flex;
4use gpui_kit::*;
5
6use super::message_actions::{Action, HoverChange, bar_button};
7use super::widgets::icon;
8use crate::theme;
9
10pub struct ScheduledMenu {
11 pub key: String,
12 pub edit: Action,
13 pub send_now: Action,
14 pub delete: Action,
15 pub hover: HoverChange,
16}
17
18fn element_id(prefix: &str, key: &str) -> ElementId {
19 ElementId::Name(format!("{prefix}-{key}").into())
20}
21
22fn text_button(id: ElementId, label: &'static str) -> Stateful<Div> {
23 bar_button(id)
24 .w_auto()
25 .px(px(8.))
26 .text_size(px(12.5))
27 .text_color(theme::text_soft())
28 .child(label)
29}
30
31pub fn scheduled_toolbar(menu: ScheduledMenu) -> AnyElement {
32 let ScheduledMenu {
33 key,
34 edit,
35 send_now,
36 delete,
37 hover,
38 } = menu;
39 h_flex()
40 .id(element_id("scheduled-toolbar", &key))
41 .p(px(2.))
42 .gap(px(2.))
43 .items_center()
44 .rounded(px(8.))
45 .bg(theme::surface())
46 .border_1()
47 .border_color(theme::border_strong())
48 .occlude()
49 .on_hover(move |hovered, _, cx| hover(*hovered, cx))
50 .on_mouse_down(MouseButton::Left, |_, _, cx| {
51 GlobalState::suppress_text_selection(cx)
52 })
53 .child(
54 text_button(element_id("scheduled-edit", &key), "Edit").on_click(
55 move |_, window, cx| {
56 cx.stop_propagation();
57 edit(window, cx);
58 },
59 ),
60 )
61 .child(
62 text_button(element_id("scheduled-send-now", &key), "Send now").on_click(
63 move |_, window, cx| {
64 cx.stop_propagation();
65 send_now(window, cx);
66 },
67 ),
68 )
69 .child(
70 bar_button(element_id("scheduled-delete", &key))
71 .child(icon(IconName::Trash, 16., theme::red_soft()))
72 .on_click(move |_, window, cx| {
73 cx.stop_propagation();
74 delete(window, cx);
75 }),
76 )
77 .into_any_element()
78}
crates/app/src/views/sidebar.rs +61 −18
@@ -16,6 +16,7 @@ use crate::app_state::{AppEvent, AppState, Selection};
16 16 use crate::chat_actions::TITLE_LIMIT;
17 17 use crate::data::{Directory, FolderKind};
18 18 use crate::format;
19 use crate::local_previews::LocalPreview;
19 20 use crate::notice::truncated;
20 21 use crate::sidebar_model::{
21 22 AvatarSpec, ChatItem, DELETED_PREVIEW, EMPTY_FOLDER_HINT, Preview, Section, SectionInput,
@@ -285,6 +286,33 @@ fn preview_icon(text: &str) -> Option<IconName> {
285 286 }
286 287 }
287 288
289 fn local_preview_row(preview: &LocalPreview, color: Hsla) -> Div {
290 let row = h_flex()
291 .flex_1()
292 .min_w_0()
293 .overflow_hidden()
294 .gap(px(4.))
295 .items_center()
296 .text_size(px(12.5))
297 .text_color(color);
298 match preview {
299 LocalPreview::Draft(text) => row
300 .child(
301 div()
302 .flex_none()
303 .text_color(theme::accent_text())
304 .child("Draft:"),
305 )
306 .child(div().truncate().child(text.clone())),
307 LocalPreview::NotSent => row.child(
308 div()
309 .flex_none()
310 .text_color(theme::red_soft())
311 .child("Not sent"),
312 ),
313 }
314 }
315
288 316 impl SidebarView {
289 317 pub fn new(state: Entity<AppState>, cx: &mut Context<Self>) -> Self {
290 318 let subscription = cx.subscribe(&state, |this, state, event: &AppEvent, cx| {
@@ -293,7 +321,11 @@ impl SidebarView {
293 321 }
294 322 if matches!(
295 323 event,
296 AppEvent::Sidebar | AppEvent::Selection | AppEvent::Directory | AppEvent::Typing
324 AppEvent::Sidebar
325 | AppEvent::Selection
326 | AppEvent::Directory
327 | AppEvent::Typing
328 | AppEvent::LocalPreviews
297 329 ) {
298 330 cx.notify();
299 331 }
@@ -513,6 +545,7 @@ impl SidebarView {
513 545 &self,
514 546 item: &ChatItem,
515 547 selected: bool,
548 local_preview: Option<&LocalPreview>,
516 549 directory: &Directory,
517 550 menu: &MenuContext,
518 551 ) -> AnyElement {
@@ -570,20 +603,23 @@ impl SidebarView {
570 603 } else {
571 604 theme::text_muted()
572 605 };
573 let preview = preview_text(&item.preview).map(|(text, italic)| {
574 let glyph = preview_icon(&text);
575 h_flex()
576 .flex_1()
577 .min_w_0()
578 .overflow_hidden()
579 .gap(px(4.))
580 .items_center()
581 .text_size(px(12.5))
582 .when(italic, |preview| preview.italic())
583 .text_color(preview_color)
584 .children(glyph.map(|name| icon(name, 12., preview_color)))
585 .child(div().truncate().child(text))
586 });
606 let preview = match local_preview {
607 Some(local) => Some(local_preview_row(local, preview_color)),
608 None => preview_text(&item.preview).map(|(text, italic)| {
609 let glyph = preview_icon(&text);
610 h_flex()
611 .flex_1()
612 .min_w_0()
613 .overflow_hidden()
614 .gap(px(4.))
615 .items_center()
616 .text_size(px(12.5))
617 .when(italic, |preview| preview.italic())
618 .text_color(preview_color)
619 .children(glyph.map(|name| icon(name, 12., preview_color)))
620 .child(div().truncate().child(text))
621 }),
622 };
587 623 let lines = v_flex()
588 624 .flex_1()
589 625 .min_w_0()
@@ -648,7 +684,7 @@ impl SidebarView {
648 684 }
649 685
650 686 fn chats_body(&self, window_height: f32, cx: &mut Context<Self>) -> AnyElement {
651 let (sections, menu) = {
687 let (sections, menu, local_previews) = {
652 688 let state = self.state.read(cx);
653 689 let now = Utc::now();
654 690 let offset = Local::now().offset().fix();
@@ -672,7 +708,7 @@ impl SidebarView {
672 708 .collect(),
673 709 favorites_id: state.directory.favorites().map(|folder| folder.id.clone()),
674 710 };
675 (sections, menu)
711 (sections, menu, state.local_previews.clone())
676 712 };
677 713
678 714 let top = -f32::from(self.chats_scroll.offset().y);
@@ -718,7 +754,14 @@ impl SidebarView {
718 754 list = with_spacer(list, &mut skipped_height);
719 755 let is_selected = selected == Some(Selection::Chat(item.id.clone()));
720 756 let directory = &directory_state.read(cx).directory;
721 list = list.child(self.chat_row(item, is_selected, directory, &menu));
757 let local_preview = local_previews.get(&item.id).filter(|_| !is_selected);
758 list = list.child(self.chat_row(
759 item,
760 is_selected,
761 local_preview,
762 directory,
763 &menu,
764 ));
722 765 } else {
723 766 skipped_height += ROW_HEIGHT;
724 767 }
@@ -16,6 +16,7 @@ use crate::app_state::{AppEvent, AppState, Selection};
16use crate::chat_actions::TITLE_LIMIT;
16use crate::chat_actions::TITLE_LIMIT;
17use crate::data::{Directory, FolderKind};
17use crate::data::{Directory, FolderKind};
18use crate::format;
18use crate::format;
19use crate::local_previews::LocalPreview;
19use crate::notice::truncated;
20use crate::notice::truncated;
20use crate::sidebar_model::{
21use crate::sidebar_model::{
21 AvatarSpec, ChatItem, DELETED_PREVIEW, EMPTY_FOLDER_HINT, Preview, Section, SectionInput,
22 AvatarSpec, ChatItem, DELETED_PREVIEW, EMPTY_FOLDER_HINT, Preview, Section, SectionInput,
@@ -285,6 +286,33 @@ fn preview_icon(text: &str) -> Option<IconName> {
285 }
286 }
286}
287}
287
288
289fn local_preview_row(preview: &LocalPreview, color: Hsla) -> Div {
290 let row = h_flex()
291 .flex_1()
292 .min_w_0()
293 .overflow_hidden()
294 .gap(px(4.))
295 .items_center()
296 .text_size(px(12.5))
297 .text_color(color);
298 match preview {
299 LocalPreview::Draft(text) => row
300 .child(
301 div()
302 .flex_none()
303 .text_color(theme::accent_text())
304 .child("Draft:"),
305 )
306 .child(div().truncate().child(text.clone())),
307 LocalPreview::NotSent => row.child(
308 div()
309 .flex_none()
310 .text_color(theme::red_soft())
311 .child("Not sent"),
312 ),
313 }
314}
315
288impl SidebarView {
316impl SidebarView {
289 pub fn new(state: Entity<AppState>, cx: &mut Context<Self>) -> Self {
317 pub fn new(state: Entity<AppState>, cx: &mut Context<Self>) -> Self {
290 let subscription = cx.subscribe(&state, |this, state, event: &AppEvent, cx| {
318 let subscription = cx.subscribe(&state, |this, state, event: &AppEvent, cx| {
@@ -293,7 +321,11 @@ impl SidebarView {
293 }
321 }
294 if matches!(
322 if matches!(
295 event,
323 event,
296 AppEvent::Sidebar | AppEvent::Selection | AppEvent::Directory | AppEvent::Typing
324 AppEvent::Sidebar
325 | AppEvent::Selection
326 | AppEvent::Directory
327 | AppEvent::Typing
328 | AppEvent::LocalPreviews
297 ) {
329 ) {
298 cx.notify();
330 cx.notify();
299 }
331 }
@@ -513,6 +545,7 @@ impl SidebarView {
513 &self,
545 &self,
514 item: &ChatItem,
546 item: &ChatItem,
515 selected: bool,
547 selected: bool,
548 local_preview: Option<&LocalPreview>,
516 directory: &Directory,
549 directory: &Directory,
517 menu: &MenuContext,
550 menu: &MenuContext,
518 ) -> AnyElement {
551 ) -> AnyElement {
@@ -570,20 +603,23 @@ impl SidebarView {
570 } else {
603 } else {
571 theme::text_muted()
604 theme::text_muted()
572 };
605 };
573 let preview = preview_text(&item.preview).map(|(text, italic)| {
606 let preview = match local_preview {
574 let glyph = preview_icon(&text);
607 Some(local) => Some(local_preview_row(local, preview_color)),
575 h_flex()
608 None => preview_text(&item.preview).map(|(text, italic)| {
576 .flex_1()
609 let glyph = preview_icon(&text);
577 .min_w_0()
610 h_flex()
578 .overflow_hidden()
611 .flex_1()
579 .gap(px(4.))
612 .min_w_0()
580 .items_center()
613 .overflow_hidden()
581 .text_size(px(12.5))
614 .gap(px(4.))
582 .when(italic, |preview| preview.italic())
615 .items_center()
583 .text_color(preview_color)
616 .text_size(px(12.5))
584 .children(glyph.map(|name| icon(name, 12., preview_color)))
617 .when(italic, |preview| preview.italic())
585 .child(div().truncate().child(text))
618 .text_color(preview_color)
586 });
619 .children(glyph.map(|name| icon(name, 12., preview_color)))
620 .child(div().truncate().child(text))
621 }),
622 };
587 let lines = v_flex()
623 let lines = v_flex()
588 .flex_1()
624 .flex_1()
589 .min_w_0()
625 .min_w_0()
@@ -648,7 +684,7 @@ impl SidebarView {
648 }
684 }
649
685
650 fn chats_body(&self, window_height: f32, cx: &mut Context<Self>) -> AnyElement {
686 fn chats_body(&self, window_height: f32, cx: &mut Context<Self>) -> AnyElement {
651 let (sections, menu) = {
687 let (sections, menu, local_previews) = {
652 let state = self.state.read(cx);
688 let state = self.state.read(cx);
653 let now = Utc::now();
689 let now = Utc::now();
654 let offset = Local::now().offset().fix();
690 let offset = Local::now().offset().fix();
@@ -672,7 +708,7 @@ impl SidebarView {
672 .collect(),
708 .collect(),
673 favorites_id: state.directory.favorites().map(|folder| folder.id.clone()),
709 favorites_id: state.directory.favorites().map(|folder| folder.id.clone()),
674 };
710 };
675 (sections, menu)
711 (sections, menu, state.local_previews.clone())
676 };
712 };
677
713
678 let top = -f32::from(self.chats_scroll.offset().y);
714 let top = -f32::from(self.chats_scroll.offset().y);
@@ -718,7 +754,14 @@ impl SidebarView {
718 list = with_spacer(list, &mut skipped_height);
754 list = with_spacer(list, &mut skipped_height);
719 let is_selected = selected == Some(Selection::Chat(item.id.clone()));
755 let is_selected = selected == Some(Selection::Chat(item.id.clone()));
720 let directory = &directory_state.read(cx).directory;
756 let directory = &directory_state.read(cx).directory;
721 list = list.child(self.chat_row(item, is_selected, directory, &menu));
757 let local_preview = local_previews.get(&item.id).filter(|_| !is_selected);
758 list = list.child(self.chat_row(
759 item,
760 is_selected,
761 local_preview,
762 directory,
763 &menu,
764 ));
722 } else {
765 } else {
723 skipped_height += ROW_HEIGHT;
766 skipped_height += ROW_HEIGHT;
724 }
767 }
crates/chatsvc/Cargo.toml +1 −0
@@ -15,6 +15,7 @@ serde_json.workspace = true
15 15 session.workspace = true
16 16 thiserror.workspace = true
17 17 tokio.workspace = true
18 uuid.workspace = true
18 19
19 20 [dev-dependencies]
20 21 tokio = { workspace = true }
@@ -15,6 +15,7 @@ serde_json.workspace = true
15session.workspace = true
15session.workspace = true
16thiserror.workspace = true
16thiserror.workspace = true
17tokio.workspace = true
17tokio.workspace = true
18uuid.workspace = true
18
19
19[dev-dependencies]
20[dev-dependencies]
20tokio = { workspace = true }
21tokio = { workspace = true }
crates/chatsvc/src/drafts.rs added +257 −0
@@ -0,0 +1,257 @@
1 use std::time::Duration;
2
3 use chrono::{DateTime, Duration as ChronoDuration, Utc};
4 use serde_json::{Value, json};
5 use session::{ApiResponse, Method, Request, Session};
6
7 use crate::error::Result;
8 use crate::messages::{
9 DEFAULT_RETRY_DELAY, MessageTransport, SessionMessageTransport, encode, ensure_success,
10 };
11 use crate::pins::DEFAULT_REGION;
12
13 const SCHEDULED_DRAFT: &str = "ScheduledDraft";
14 const NOT_FOUND_RETRIES: u32 = 3;
15 const BACKOFF_FACTOR: u32 = 3;
16 const CLIENT_MESSAGE_ID_LENGTH: usize = 19;
17 const LIST_PAGE_SIZE: u32 = 200;
18 const LIST_WINDOW_DAYS: i64 = 8;
19
20 #[derive(Debug, Clone, PartialEq, Eq)]
21 pub struct ScheduledDraft {
22 pub id: String,
23 pub client_message_id: String,
24 pub inner_thread_id: String,
25 pub send_at: DateTime<Utc>,
26 pub html: String,
27 pub delivery_state: Option<String>,
28 }
29
30 pub struct ScheduledDrafts<T: MessageTransport = SessionMessageTransport> {
31 transport: T,
32 base_url: String,
33 retry_delay: Duration,
34 }
35
36 impl ScheduledDrafts<SessionMessageTransport> {
37 pub fn new(session: &Session) -> Self {
38 Self::with_region(session, DEFAULT_REGION)
39 }
40
41 pub fn with_region(session: &Session, region: &str) -> Self {
42 ScheduledDrafts::with_transport(SessionMessageTransport::new(session), region)
43 }
44 }
45
46 impl<T: MessageTransport> ScheduledDrafts<T> {
47 pub fn with_transport(transport: T, region: &str) -> Self {
48 ScheduledDrafts {
49 transport,
50 base_url: format!(
51 "https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/drafts"
52 ),
53 retry_delay: DEFAULT_RETRY_DELAY,
54 }
55 }
56
57 pub fn with_retry_delay(mut self, retry_delay: Duration) -> Self {
58 self.retry_delay = retry_delay;
59 self
60 }
61
62 pub fn draft_url(&self, draft_id: &str) -> String {
63 format!("{}/{}", self.base_url, encode(draft_id))
64 }
65
66 pub async fn create(
67 &self,
68 inner_thread_id: &str,
69 html: &str,
70 send_at: DateTime<Utc>,
71 display_name: &str,
72 ) -> Result<ScheduledDraft> {
73 let client_message_id = new_client_message_id();
74 let body = draft_body(
75 inner_thread_id,
76 html,
77 send_at,
78 display_name,
79 &client_message_id,
80 None,
81 );
82 let answer = self
83 .send_retrying_not_found(Method::Post, &self.base_url, &body)
84 .await?;
85 ensure_success(&answer)?;
86 // The POST answers without the draft id, so it is looked up by clientmessageid.
87 let mut delay = self.retry_delay;
88 for attempt in 0..=NOT_FOUND_RETRIES {
89 if attempt > 0 {
90 tokio::time::sleep(delay).await;
91 delay *= BACKOFF_FACTOR;
92 }
93 if let Some(draft) = self.find(&client_message_id).await? {
94 return Ok(draft);
95 }
96 }
97 Ok(ScheduledDraft {
98 id: String::new(),
99 client_message_id,
100 inner_thread_id: inner_thread_id.to_owned(),
101 send_at,
102 html: html.to_owned(),
103 delivery_state: None,
104 })
105 }
106
107 pub async fn list(&self) -> Result<Vec<ScheduledDraft>> {
108 self.list_at(Utc::now()).await
109 }
110
111 pub async fn list_at(&self, now: DateTime<Utc>) -> Result<Vec<ScheduledDraft>> {
112 let start_time = (now - ChronoDuration::days(LIST_WINDOW_DAYS)).timestamp_millis();
113 let url = format!(
114 "{}?view=msnp24Equivalent&pageSize={LIST_PAGE_SIZE}&startTime={start_time}",
115 self.base_url
116 );
117 let answer = self.transport.send(Request::get(&url)).await?;
118 if answer.status == 404 {
119 return Ok(Vec::new());
120 }
121 ensure_success(&answer)?;
122 Ok(parse_drafts(&answer.body))
123 }
124
125 pub async fn update(
126 &self,
127 draft: &ScheduledDraft,
128 html: &str,
129 display_name: &str,
130 ) -> Result<ScheduledDraft> {
131 let body = draft_body(
132 &draft.inner_thread_id,
133 html,
134 draft.send_at,
135 display_name,
136 &draft.client_message_id,
137 Some(&draft.id),
138 );
139 let answer = self
140 .send_retrying_not_found(Method::Put, &self.draft_url(&draft.id), &body)
141 .await?;
142 ensure_success(&answer)?;
143 Ok(ScheduledDraft {
144 html: html.to_owned(),
145 ..draft.clone()
146 })
147 }
148
149 pub async fn cancel(&self, draft_id: &str) -> Result<()> {
150 let answer = self
151 .transport
152 .send(Request::delete(self.draft_url(draft_id)))
153 .await?;
154 ensure_success(&answer)
155 }
156
157 async fn find(&self, client_message_id: &str) -> Result<Option<ScheduledDraft>> {
158 Ok(self
159 .list()
160 .await?
161 .into_iter()
162 .find(|draft| draft.client_message_id == client_message_id))
163 }
164
165 async fn send_retrying_not_found(
166 &self,
167 method: Method,
168 url: &str,
169 body: &Value,
170 ) -> Result<ApiResponse> {
171 let mut delay = self.retry_delay;
172 let mut answer = self
173 .transport
174 .send(Request::with_body(method, url, body.clone()))
175 .await?;
176 for _ in 0..NOT_FOUND_RETRIES {
177 if answer.status != 404 {
178 break;
179 }
180 tokio::time::sleep(delay).await;
181 delay *= BACKOFF_FACTOR;
182 answer = self
183 .transport
184 .send(Request::with_body(method, url, body.clone()))
185 .await?;
186 }
187 Ok(answer)
188 }
189 }
190
191 fn draft_body(
192 inner_thread_id: &str,
193 html: &str,
194 send_at: DateTime<Utc>,
195 display_name: &str,
196 client_message_id: &str,
197 draft_id: Option<&str>,
198 ) -> Value {
199 let mut message = json!({
200 "content": html,
201 "messagetype": "RichText/Html",
202 "contenttype": "text",
203 "clientmessageid": client_message_id,
204 "imdisplayname": display_name,
205 "properties": {},
206 });
207 if let Some(draft_id) = draft_id {
208 message["id"] = json!(draft_id);
209 }
210 json!({
211 "draftDetails": {"sendAt": send_at.timestamp_millis().to_string()},
212 "draftType": SCHEDULED_DRAFT,
213 "innerThreadId": inner_thread_id,
214 "message": message,
215 })
216 }
217
218 fn new_client_message_id() -> String {
219 let random = uuid::Uuid::new_v4().as_u128();
220 let first = (random >> 96) as u32;
221 let second = (random >> 64) as u32;
222 let mut id = format!("{first}{second}");
223 id.truncate(CLIENT_MESSAGE_ID_LENGTH);
224 id
225 }
226
227 fn parse_drafts(body: &Value) -> Vec<ScheduledDraft> {
228 body.get("drafts")
229 .and_then(Value::as_array)
230 .into_iter()
231 .flatten()
232 .filter_map(parse_draft)
233 .collect()
234 }
235
236 fn parse_draft(draft: &Value) -> Option<ScheduledDraft> {
237 if draft["draftType"].as_str()? != SCHEDULED_DRAFT {
238 return None;
239 }
240 let properties = &draft["properties"];
241 let html = draft["content"].as_str().filter(|html| !html.is_empty())?;
242 if !properties["deletetime"].is_null() {
243 return None;
244 }
245 let send_at_millis: i64 = draft["draftDetails"]["sendAt"]
246 .as_str()
247 .and_then(|text| text.parse().ok())
248 .or_else(|| draft["draftDetails"]["sendAt"].as_i64())?;
249 Some(ScheduledDraft {
250 id: draft["id"].as_str()?.to_owned(),
251 client_message_id: draft["clientmessageid"].as_str()?.to_owned(),
252 inner_thread_id: draft["innerThreadId"].as_str()?.to_owned(),
253 send_at: DateTime::from_timestamp_millis(send_at_millis)?,
254 html: html.to_owned(),
255 delivery_state: properties["deliveryState"].as_str().map(str::to_owned),
256 })
257 }
@@ -0,0 +1,257 @@
1use std::time::Duration;
2
3use chrono::{DateTime, Duration as ChronoDuration, Utc};
4use serde_json::{Value, json};
5use session::{ApiResponse, Method, Request, Session};
6
7use crate::error::Result;
8use crate::messages::{
9 DEFAULT_RETRY_DELAY, MessageTransport, SessionMessageTransport, encode, ensure_success,
10};
11use crate::pins::DEFAULT_REGION;
12
13const SCHEDULED_DRAFT: &str = "ScheduledDraft";
14const NOT_FOUND_RETRIES: u32 = 3;
15const BACKOFF_FACTOR: u32 = 3;
16const CLIENT_MESSAGE_ID_LENGTH: usize = 19;
17const LIST_PAGE_SIZE: u32 = 200;
18const LIST_WINDOW_DAYS: i64 = 8;
19
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct ScheduledDraft {
22 pub id: String,
23 pub client_message_id: String,
24 pub inner_thread_id: String,
25 pub send_at: DateTime<Utc>,
26 pub html: String,
27 pub delivery_state: Option<String>,
28}
29
30pub struct ScheduledDrafts<T: MessageTransport = SessionMessageTransport> {
31 transport: T,
32 base_url: String,
33 retry_delay: Duration,
34}
35
36impl ScheduledDrafts<SessionMessageTransport> {
37 pub fn new(session: &Session) -> Self {
38 Self::with_region(session, DEFAULT_REGION)
39 }
40
41 pub fn with_region(session: &Session, region: &str) -> Self {
42 ScheduledDrafts::with_transport(SessionMessageTransport::new(session), region)
43 }
44}
45
46impl<T: MessageTransport> ScheduledDrafts<T> {
47 pub fn with_transport(transport: T, region: &str) -> Self {
48 ScheduledDrafts {
49 transport,
50 base_url: format!(
51 "https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/drafts"
52 ),
53 retry_delay: DEFAULT_RETRY_DELAY,
54 }
55 }
56
57 pub fn with_retry_delay(mut self, retry_delay: Duration) -> Self {
58 self.retry_delay = retry_delay;
59 self
60 }
61
62 pub fn draft_url(&self, draft_id: &str) -> String {
63 format!("{}/{}", self.base_url, encode(draft_id))
64 }
65
66 pub async fn create(
67 &self,
68 inner_thread_id: &str,
69 html: &str,
70 send_at: DateTime<Utc>,
71 display_name: &str,
72 ) -> Result<ScheduledDraft> {
73 let client_message_id = new_client_message_id();
74 let body = draft_body(
75 inner_thread_id,
76 html,
77 send_at,
78 display_name,
79 &client_message_id,
80 None,
81 );
82 let answer = self
83 .send_retrying_not_found(Method::Post, &self.base_url, &body)
84 .await?;
85 ensure_success(&answer)?;
86 // The POST answers without the draft id, so it is looked up by clientmessageid.
87 let mut delay = self.retry_delay;
88 for attempt in 0..=NOT_FOUND_RETRIES {
89 if attempt > 0 {
90 tokio::time::sleep(delay).await;
91 delay *= BACKOFF_FACTOR;
92 }
93 if let Some(draft) = self.find(&client_message_id).await? {
94 return Ok(draft);
95 }
96 }
97 Ok(ScheduledDraft {
98 id: String::new(),
99 client_message_id,
100 inner_thread_id: inner_thread_id.to_owned(),
101 send_at,
102 html: html.to_owned(),
103 delivery_state: None,
104 })
105 }
106
107 pub async fn list(&self) -> Result<Vec<ScheduledDraft>> {
108 self.list_at(Utc::now()).await
109 }
110
111 pub async fn list_at(&self, now: DateTime<Utc>) -> Result<Vec<ScheduledDraft>> {
112 let start_time = (now - ChronoDuration::days(LIST_WINDOW_DAYS)).timestamp_millis();
113 let url = format!(
114 "{}?view=msnp24Equivalent&pageSize={LIST_PAGE_SIZE}&startTime={start_time}",
115 self.base_url
116 );
117 let answer = self.transport.send(Request::get(&url)).await?;
118 if answer.status == 404 {
119 return Ok(Vec::new());
120 }
121 ensure_success(&answer)?;
122 Ok(parse_drafts(&answer.body))
123 }
124
125 pub async fn update(
126 &self,
127 draft: &ScheduledDraft,
128 html: &str,
129 display_name: &str,
130 ) -> Result<ScheduledDraft> {
131 let body = draft_body(
132 &draft.inner_thread_id,
133 html,
134 draft.send_at,
135 display_name,
136 &draft.client_message_id,
137 Some(&draft.id),
138 );
139 let answer = self
140 .send_retrying_not_found(Method::Put, &self.draft_url(&draft.id), &body)
141 .await?;
142 ensure_success(&answer)?;
143 Ok(ScheduledDraft {
144 html: html.to_owned(),
145 ..draft.clone()
146 })
147 }
148
149 pub async fn cancel(&self, draft_id: &str) -> Result<()> {
150 let answer = self
151 .transport
152 .send(Request::delete(self.draft_url(draft_id)))
153 .await?;
154 ensure_success(&answer)
155 }
156
157 async fn find(&self, client_message_id: &str) -> Result<Option<ScheduledDraft>> {
158 Ok(self
159 .list()
160 .await?
161 .into_iter()
162 .find(|draft| draft.client_message_id == client_message_id))
163 }
164
165 async fn send_retrying_not_found(
166 &self,
167 method: Method,
168 url: &str,
169 body: &Value,
170 ) -> Result<ApiResponse> {
171 let mut delay = self.retry_delay;
172 let mut answer = self
173 .transport
174 .send(Request::with_body(method, url, body.clone()))
175 .await?;
176 for _ in 0..NOT_FOUND_RETRIES {
177 if answer.status != 404 {
178 break;
179 }
180 tokio::time::sleep(delay).await;
181 delay *= BACKOFF_FACTOR;
182 answer = self
183 .transport
184 .send(Request::with_body(method, url, body.clone()))
185 .await?;
186 }
187 Ok(answer)
188 }
189}
190
191fn draft_body(
192 inner_thread_id: &str,
193 html: &str,
194 send_at: DateTime<Utc>,
195 display_name: &str,
196 client_message_id: &str,
197 draft_id: Option<&str>,
198) -> Value {
199 let mut message = json!({
200 "content": html,
201 "messagetype": "RichText/Html",
202 "contenttype": "text",
203 "clientmessageid": client_message_id,
204 "imdisplayname": display_name,
205 "properties": {},
206 });
207 if let Some(draft_id) = draft_id {
208 message["id"] = json!(draft_id);
209 }
210 json!({
211 "draftDetails": {"sendAt": send_at.timestamp_millis().to_string()},
212 "draftType": SCHEDULED_DRAFT,
213 "innerThreadId": inner_thread_id,
214 "message": message,
215 })
216}
217
218fn new_client_message_id() -> String {
219 let random = uuid::Uuid::new_v4().as_u128();
220 let first = (random >> 96) as u32;
221 let second = (random >> 64) as u32;
222 let mut id = format!("{first}{second}");
223 id.truncate(CLIENT_MESSAGE_ID_LENGTH);
224 id
225}
226
227fn parse_drafts(body: &Value) -> Vec<ScheduledDraft> {
228 body.get("drafts")
229 .and_then(Value::as_array)
230 .into_iter()
231 .flatten()
232 .filter_map(parse_draft)
233 .collect()
234}
235
236fn parse_draft(draft: &Value) -> Option<ScheduledDraft> {
237 if draft["draftType"].as_str()? != SCHEDULED_DRAFT {
238 return None;
239 }
240 let properties = &draft["properties"];
241 let html = draft["content"].as_str().filter(|html| !html.is_empty())?;
242 if !properties["deletetime"].is_null() {
243 return None;
244 }
245 let send_at_millis: i64 = draft["draftDetails"]["sendAt"]
246 .as_str()
247 .and_then(|text| text.parse().ok())
248 .or_else(|| draft["draftDetails"]["sendAt"].as_i64())?;
249 Some(ScheduledDraft {
250 id: draft["id"].as_str()?.to_owned(),
251 client_message_id: draft["clientmessageid"].as_str()?.to_owned(),
252 inner_thread_id: draft["innerThreadId"].as_str()?.to_owned(),
253 send_at: DateTime::from_timestamp_millis(send_at_millis)?,
254 html: html.to_owned(),
255 delivery_state: properties["deliveryState"].as_str().map(str::to_owned),
256 })
257}
crates/chatsvc/src/lib.rs +2 −0
@@ -1,5 +1,6 @@
1 1 pub mod cards;
2 2 pub mod conversations;
3 pub mod drafts;
3 4 mod error;
4 5 pub mod links;
5 6 pub mod gifs;
@@ -14,6 +15,7 @@ pub use cards::{
14 15 CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
15 16 };
16 17 pub use conversations::Conversations;
18 pub use drafts::{ScheduledDraft, ScheduledDrafts};
17 19 pub use error::{Error, Result};
18 20 pub use gifs::{Gif, Gifs};
19 21 pub use mask::mask_conversation_id;
@@ -1,5 +1,6 @@
1pub mod cards;
1pub mod cards;
2pub mod conversations;
2pub mod conversations;
3pub mod drafts;
3mod error;
4mod error;
4pub mod links;
5pub mod links;
5pub mod gifs;
6pub mod gifs;
@@ -14,6 +15,7 @@ pub use cards::{
14 CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
15 CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
15};
16};
16pub use conversations::Conversations;
17pub use conversations::Conversations;
18pub use drafts::{ScheduledDraft, ScheduledDrafts};
17pub use error::{Error, Result};
19pub use error::{Error, Result};
18pub use gifs::{Gif, Gifs};
20pub use gifs::{Gif, Gifs};
19pub use mask::mask_conversation_id;
21pub use mask::mask_conversation_id;
crates/chatsvc/tests/drafts.rs added +247 −0
@@ -0,0 +1,247 @@
1 use std::collections::VecDeque;
2 use std::sync::Mutex;
3 use std::time::Duration;
4
5 use chatsvc::drafts::{ScheduledDraft, ScheduledDrafts};
6 use chatsvc::messages::MessageTransport;
7 use chatsvc::{Error, Result};
8 use chrono::{TimeZone, Utc};
9 use serde_json::{Value, json};
10 use session::{ApiResponse, Method, Request};
11
12 struct Mock {
13 answers: Mutex<VecDeque<(u16, Value)>>,
14 requests: Mutex<Vec<Request>>,
15 }
16
17 impl Mock {
18 fn new(answers: Vec<(u16, Value)>) -> Self {
19 Mock {
20 answers: Mutex::new(answers.into()),
21 requests: Mutex::new(Vec::new()),
22 }
23 }
24
25 fn requests(&self) -> Vec<Request> {
26 self.requests.lock().unwrap().clone()
27 }
28 }
29
30 impl MessageTransport for &Mock {
31 async fn send(&self, request: Request) -> Result<ApiResponse> {
32 let mut requests = self.requests.lock().unwrap();
33 requests.push(request);
34 let (status, mut body) = self
35 .answers
36 .lock()
37 .unwrap()
38 .pop_front()
39 .expect("mock exhausted");
40 if body == json!(ECHO_LIST) {
41 body = listed(&sent_client_message_id(&requests[0]));
42 }
43 Ok(ApiResponse {
44 status,
45 body,
46 retry_after: None,
47 })
48 }
49 }
50
51 fn drafts(mock: &Mock) -> ScheduledDrafts<&Mock> {
52 ScheduledDrafts::with_transport(mock, "emea").with_retry_delay(Duration::ZERO)
53 }
54
55 const ECHO_LIST: &str = "echo the posted draft";
56 const BASE: &str = "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/drafts";
57
58 fn send_at() -> chrono::DateTime<Utc> {
59 Utc.with_ymd_and_hms(2026, 10, 12, 6, 0, 0).unwrap()
60 }
61
62 fn listed(client_message_id: &str) -> Value {
63 json!({"drafts": [{
64 "id": "d1",
65 "clientmessageid": client_message_id,
66 "content": "<p>hi</p>",
67 "innerThreadId": "19:a@thread.v2",
68 "draftType": "ScheduledDraft",
69 "draftDetails": {"sendAt": "1791784800000"},
70 "properties": {},
71 }]})
72 }
73
74 fn sent_client_message_id(request: &Request) -> String {
75 request.body.as_ref().unwrap()["message"]["clientmessageid"]
76 .as_str()
77 .unwrap()
78 .to_owned()
79 }
80
81 fn draft() -> ScheduledDraft {
82 ScheduledDraft {
83 id: "d 1".to_owned(),
84 client_message_id: "123".to_owned(),
85 inner_thread_id: "19:a@thread.v2".to_owned(),
86 send_at: send_at(),
87 html: "<p>old</p>".to_owned(),
88 delivery_state: None,
89 }
90 }
91
92 #[tokio::test]
93 async fn create_finds_the_draft_by_client_message_id() {
94 let mock = Mock::new(vec![
95 (201, json!({"OriginalArrivalTime": 1})),
96 (200, json!(ECHO_LIST)),
97 ]);
98 let created = drafts(&mock)
99 .create("19:a@thread.v2", "<p>hi</p>", send_at(), "Me")
100 .await
101 .unwrap();
102 assert_eq!(created.id, "d1");
103 let requests = mock.requests();
104 assert_eq!(requests[0].method, Method::Post);
105 assert_eq!(requests[0].url, BASE);
106 let body = requests[0].body.as_ref().unwrap();
107 assert_eq!(body["draftType"], "ScheduledDraft");
108 assert_eq!(body["draftDetails"]["sendAt"], "1791784800000");
109 assert_eq!(body["innerThreadId"], "19:a@thread.v2");
110 assert_eq!(body["message"]["content"], "<p>hi</p>");
111 assert_eq!(body["message"]["messagetype"], "RichText/Html");
112 assert_eq!(body["message"]["contenttype"], "text");
113 assert_eq!(body["message"]["imdisplayname"], "Me");
114 let client_message_id = sent_client_message_id(&requests[0]);
115 assert!(client_message_id.len() <= 19 && client_message_id.chars().all(|c| c.is_ascii_digit()));
116 assert_eq!(requests[1].method, Method::Get);
117 }
118
119 #[tokio::test]
120 async fn create_retries_the_lookup_with_backoff_until_the_draft_shows() {
121 let mock = Mock::new(vec![
122 (201, json!({})),
123 (200, json!({"drafts": []})),
124 (200, json!({"drafts": []})),
125 (200, json!(ECHO_LIST)),
126 ]);
127 let created = drafts(&mock)
128 .create("19:a@thread.v2", "<p>hi</p>", send_at(), "Me")
129 .await
130 .unwrap();
131 assert_eq!(created.id, "d1");
132 assert_eq!(mock.requests().len(), 4);
133 }
134
135 #[tokio::test]
136 async fn create_without_a_found_id_still_succeeds_with_an_empty_id() {
137 let mock = Mock::new(vec![
138 (201, json!({})),
139 (200, json!({"drafts": []})),
140 (200, json!({"drafts": []})),
141 (200, json!({"drafts": []})),
142 (200, json!({"drafts": []})),
143 ]);
144 let created = drafts(&mock)
145 .create("19:a@thread.v2", "<p>hi</p>", send_at(), "Me")
146 .await
147 .unwrap();
148 let requests = mock.requests();
149 assert_eq!(requests.len(), 5);
150 assert_eq!(created.id, "");
151 assert_eq!(
152 created.client_message_id,
153 sent_client_message_id(&requests[0])
154 );
155 assert_eq!(created.inner_thread_id, "19:a@thread.v2");
156 assert_eq!(created.send_at, send_at());
157 assert_eq!(created.html, "<p>hi</p>");
158 }
159
160 #[tokio::test]
161 async fn list_keeps_scheduled_drafts_and_drops_tombstones() {
162 let mock = Mock::new(vec![(
163 200,
164 json!({"_metadata": {}, "drafts": [
165 {"id": "a", "clientmessageid": "1", "content": "<p>x</p>", "innerThreadId": "c",
166 "draftType": "ScheduledDraft", "draftDetails": {"sendAt": "1791784800000"},
167 "properties": {"deliveryState": "failed"}},
168 {"id": "b", "clientmessageid": "2", "content": "<p>x</p>", "innerThreadId": "c",
169 "draftType": "RegularDraft", "properties": {}},
170 {"id": "c", "clientmessageid": "3", "content": "", "innerThreadId": "c",
171 "draftType": "ScheduledDraft", "draftDetails": {"sendAt": "1791784800000"},
172 "properties": {"deletetime": "1791700000000"}},
173 {"id": "e", "clientmessageid": "4", "content": "<p>x</p>", "innerThreadId": "c",
174 "draftType": "ScheduledDraft", "draftDetails": {"sendAt": "1791784800000"},
175 "properties": {"deletetime": "1791700000000"}},
176 ]}),
177 )]);
178 let now = send_at();
179 let listed = drafts(&mock).list_at(now).await.unwrap();
180 assert_eq!(listed.len(), 1);
181 assert_eq!(listed[0].id, "a");
182 assert_eq!(listed[0].send_at, send_at());
183 assert_eq!(listed[0].delivery_state.as_deref(), Some("failed"));
184 assert_eq!(
185 mock.requests()[0].url,
186 format!(
187 "{BASE}?view=msnp24Equivalent&pageSize=200&startTime={}",
188 (now - chrono::Duration::days(8)).timestamp_millis()
189 )
190 );
191 }
192
193 #[tokio::test]
194 async fn list_answers_empty_when_the_stream_does_not_exist() {
195 let mock = Mock::new(vec![(404, Value::Null)]);
196 assert!(drafts(&mock).list().await.unwrap().is_empty());
197 }
198
199 #[tokio::test]
200 async fn update_puts_the_draft_id_inside_the_message() {
201 let mock = Mock::new(vec![(200, Value::Null)]);
202 let updated = drafts(&mock)
203 .update(&draft(), "<p>new</p>", "Me")
204 .await
205 .unwrap();
206 assert_eq!(updated.html, "<p>new</p>");
207 let requests = mock.requests();
208 assert_eq!(requests[0].method, Method::Put);
209 assert_eq!(requests[0].url, format!("{BASE}/d%201"));
210 let body = requests[0].body.as_ref().unwrap();
211 assert_eq!(body["message"]["id"], "d 1");
212 assert_eq!(body["message"]["clientmessageid"], "123");
213 assert_eq!(body["message"]["content"], "<p>new</p>");
214 assert_eq!(body["draftDetails"]["sendAt"], "1791784800000");
215 }
216
217 #[tokio::test]
218 async fn cancel_deletes_the_encoded_draft_url() {
219 let mock = Mock::new(vec![(200, Value::Null)]);
220 drafts(&mock).cancel("d/1").await.unwrap();
221 let requests = mock.requests();
222 assert_eq!(requests[0].method, Method::Delete);
223 assert_eq!(requests[0].url, format!("{BASE}/d%2F1"));
224 }
225
226 #[tokio::test]
227 async fn edit_retries_on_not_found_up_to_three_times() {
228 let mock = Mock::new(vec![
229 (404, Value::Null),
230 (404, Value::Null),
231 (404, Value::Null),
232 (200, Value::Null),
233 ]);
234 drafts(&mock)
235 .update(&draft(), "<p>new</p>", "Me")
236 .await
237 .unwrap();
238 assert_eq!(mock.requests().len(), 4);
239
240 let mock = Mock::new(vec![(404, Value::Null); 4]);
241 let error = drafts(&mock)
242 .update(&draft(), "<p>new</p>", "Me")
243 .await
244 .unwrap_err();
245 assert!(matches!(error, Error::Session(_)));
246 assert_eq!(mock.requests().len(), 4);
247 }
@@ -0,0 +1,247 @@
1use std::collections::VecDeque;
2use std::sync::Mutex;
3use std::time::Duration;
4
5use chatsvc::drafts::{ScheduledDraft, ScheduledDrafts};
6use chatsvc::messages::MessageTransport;
7use chatsvc::{Error, Result};
8use chrono::{TimeZone, Utc};
9use serde_json::{Value, json};
10use session::{ApiResponse, Method, Request};
11
12struct Mock {
13 answers: Mutex<VecDeque<(u16, Value)>>,
14 requests: Mutex<Vec<Request>>,
15}
16
17impl Mock {
18 fn new(answers: Vec<(u16, Value)>) -> Self {
19 Mock {
20 answers: Mutex::new(answers.into()),
21 requests: Mutex::new(Vec::new()),
22 }
23 }
24
25 fn requests(&self) -> Vec<Request> {
26 self.requests.lock().unwrap().clone()
27 }
28}
29
30impl MessageTransport for &Mock {
31 async fn send(&self, request: Request) -> Result<ApiResponse> {
32 let mut requests = self.requests.lock().unwrap();
33 requests.push(request);
34 let (status, mut body) = self
35 .answers
36 .lock()
37 .unwrap()
38 .pop_front()
39 .expect("mock exhausted");
40 if body == json!(ECHO_LIST) {
41 body = listed(&sent_client_message_id(&requests[0]));
42 }
43 Ok(ApiResponse {
44 status,
45 body,
46 retry_after: None,
47 })
48 }
49}
50
51fn drafts(mock: &Mock) -> ScheduledDrafts<&Mock> {
52 ScheduledDrafts::with_transport(mock, "emea").with_retry_delay(Duration::ZERO)
53}
54
55const ECHO_LIST: &str = "echo the posted draft";
56const BASE: &str = "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/drafts";
57
58fn send_at() -> chrono::DateTime<Utc> {
59 Utc.with_ymd_and_hms(2026, 10, 12, 6, 0, 0).unwrap()
60}
61
62fn listed(client_message_id: &str) -> Value {
63 json!({"drafts": [{
64 "id": "d1",
65 "clientmessageid": client_message_id,
66 "content": "<p>hi</p>",
67 "innerThreadId": "19:a@thread.v2",
68 "draftType": "ScheduledDraft",
69 "draftDetails": {"sendAt": "1791784800000"},
70 "properties": {},
71 }]})
72}
73
74fn sent_client_message_id(request: &Request) -> String {
75 request.body.as_ref().unwrap()["message"]["clientmessageid"]
76 .as_str()
77 .unwrap()
78 .to_owned()
79}
80
81fn draft() -> ScheduledDraft {
82 ScheduledDraft {
83 id: "d 1".to_owned(),
84 client_message_id: "123".to_owned(),
85 inner_thread_id: "19:a@thread.v2".to_owned(),
86 send_at: send_at(),
87 html: "<p>old</p>".to_owned(),
88 delivery_state: None,
89 }
90}
91
92#[tokio::test]
93async fn create_finds_the_draft_by_client_message_id() {
94 let mock = Mock::new(vec![
95 (201, json!({"OriginalArrivalTime": 1})),
96 (200, json!(ECHO_LIST)),
97 ]);
98 let created = drafts(&mock)
99 .create("19:a@thread.v2", "<p>hi</p>", send_at(), "Me")
100 .await
101 .unwrap();
102 assert_eq!(created.id, "d1");
103 let requests = mock.requests();
104 assert_eq!(requests[0].method, Method::Post);
105 assert_eq!(requests[0].url, BASE);
106 let body = requests[0].body.as_ref().unwrap();
107 assert_eq!(body["draftType"], "ScheduledDraft");
108 assert_eq!(body["draftDetails"]["sendAt"], "1791784800000");
109 assert_eq!(body["innerThreadId"], "19:a@thread.v2");
110 assert_eq!(body["message"]["content"], "<p>hi</p>");
111 assert_eq!(body["message"]["messagetype"], "RichText/Html");
112 assert_eq!(body["message"]["contenttype"], "text");
113 assert_eq!(body["message"]["imdisplayname"], "Me");
114 let client_message_id = sent_client_message_id(&requests[0]);
115 assert!(client_message_id.len() <= 19 && client_message_id.chars().all(|c| c.is_ascii_digit()));
116 assert_eq!(requests[1].method, Method::Get);
117}
118
119#[tokio::test]
120async fn create_retries_the_lookup_with_backoff_until_the_draft_shows() {
121 let mock = Mock::new(vec![
122 (201, json!({})),
123 (200, json!({"drafts": []})),
124 (200, json!({"drafts": []})),
125 (200, json!(ECHO_LIST)),
126 ]);
127 let created = drafts(&mock)
128 .create("19:a@thread.v2", "<p>hi</p>", send_at(), "Me")
129 .await
130 .unwrap();
131 assert_eq!(created.id, "d1");
132 assert_eq!(mock.requests().len(), 4);
133}
134
135#[tokio::test]
136async fn create_without_a_found_id_still_succeeds_with_an_empty_id() {
137 let mock = Mock::new(vec![
138 (201, json!({})),
139 (200, json!({"drafts": []})),
140 (200, json!({"drafts": []})),
141 (200, json!({"drafts": []})),
142 (200, json!({"drafts": []})),
143 ]);
144 let created = drafts(&mock)
145 .create("19:a@thread.v2", "<p>hi</p>", send_at(), "Me")
146 .await
147 .unwrap();
148 let requests = mock.requests();
149 assert_eq!(requests.len(), 5);
150 assert_eq!(created.id, "");
151 assert_eq!(
152 created.client_message_id,
153 sent_client_message_id(&requests[0])
154 );
155 assert_eq!(created.inner_thread_id, "19:a@thread.v2");
156 assert_eq!(created.send_at, send_at());
157 assert_eq!(created.html, "<p>hi</p>");
158}
159
160#[tokio::test]
161async fn list_keeps_scheduled_drafts_and_drops_tombstones() {
162 let mock = Mock::new(vec![(
163 200,
164 json!({"_metadata": {}, "drafts": [
165 {"id": "a", "clientmessageid": "1", "content": "<p>x</p>", "innerThreadId": "c",
166 "draftType": "ScheduledDraft", "draftDetails": {"sendAt": "1791784800000"},
167 "properties": {"deliveryState": "failed"}},
168 {"id": "b", "clientmessageid": "2", "content": "<p>x</p>", "innerThreadId": "c",
169 "draftType": "RegularDraft", "properties": {}},
170 {"id": "c", "clientmessageid": "3", "content": "", "innerThreadId": "c",
171 "draftType": "ScheduledDraft", "draftDetails": {"sendAt": "1791784800000"},
172 "properties": {"deletetime": "1791700000000"}},
173 {"id": "e", "clientmessageid": "4", "content": "<p>x</p>", "innerThreadId": "c",
174 "draftType": "ScheduledDraft", "draftDetails": {"sendAt": "1791784800000"},
175 "properties": {"deletetime": "1791700000000"}},
176 ]}),
177 )]);
178 let now = send_at();
179 let listed = drafts(&mock).list_at(now).await.unwrap();
180 assert_eq!(listed.len(), 1);
181 assert_eq!(listed[0].id, "a");
182 assert_eq!(listed[0].send_at, send_at());
183 assert_eq!(listed[0].delivery_state.as_deref(), Some("failed"));
184 assert_eq!(
185 mock.requests()[0].url,
186 format!(
187 "{BASE}?view=msnp24Equivalent&pageSize=200&startTime={}",
188 (now - chrono::Duration::days(8)).timestamp_millis()
189 )
190 );
191}
192
193#[tokio::test]
194async fn list_answers_empty_when_the_stream_does_not_exist() {
195 let mock = Mock::new(vec![(404, Value::Null)]);
196 assert!(drafts(&mock).list().await.unwrap().is_empty());
197}
198
199#[tokio::test]
200async fn update_puts_the_draft_id_inside_the_message() {
201 let mock = Mock::new(vec![(200, Value::Null)]);
202 let updated = drafts(&mock)
203 .update(&draft(), "<p>new</p>", "Me")
204 .await
205 .unwrap();
206 assert_eq!(updated.html, "<p>new</p>");
207 let requests = mock.requests();
208 assert_eq!(requests[0].method, Method::Put);
209 assert_eq!(requests[0].url, format!("{BASE}/d%201"));
210 let body = requests[0].body.as_ref().unwrap();
211 assert_eq!(body["message"]["id"], "d 1");
212 assert_eq!(body["message"]["clientmessageid"], "123");
213 assert_eq!(body["message"]["content"], "<p>new</p>");
214 assert_eq!(body["draftDetails"]["sendAt"], "1791784800000");
215}
216
217#[tokio::test]
218async fn cancel_deletes_the_encoded_draft_url() {
219 let mock = Mock::new(vec![(200, Value::Null)]);
220 drafts(&mock).cancel("d/1").await.unwrap();
221 let requests = mock.requests();
222 assert_eq!(requests[0].method, Method::Delete);
223 assert_eq!(requests[0].url, format!("{BASE}/d%2F1"));
224}
225
226#[tokio::test]
227async fn edit_retries_on_not_found_up_to_three_times() {
228 let mock = Mock::new(vec![
229 (404, Value::Null),
230 (404, Value::Null),
231 (404, Value::Null),
232 (200, Value::Null),
233 ]);
234 drafts(&mock)
235 .update(&draft(), "<p>new</p>", "Me")
236 .await
237 .unwrap();
238 assert_eq!(mock.requests().len(), 4);
239
240 let mock = Mock::new(vec![(404, Value::Null); 4]);
241 let error = drafts(&mock)
242 .update(&draft(), "<p>new</p>", "Me")
243 .await
244 .unwrap_err();
245 assert!(matches!(error, Error::Session(_)));
246 assert_eq!(mock.requests().len(), 4);
247}
crates/core/src/draft.rs +17 −0
@@ -392,6 +392,10 @@ impl Draft {
392 392 draft
393 393 }
394 394
395 pub fn to_lines(&self) -> Vec<DraftLine> {
396 self.slice(0..self.text.len())
397 }
398
395 399 pub fn from_markdown(text: &str) -> Draft {
396 400 Draft::from_lines(&markdown_lines(text))
397 401 }
@@ -2046,6 +2050,19 @@ mod tests {
2046 2050 );
2047 2051 }
2048 2052
2053 #[test]
2054 fn lines_round_trip_through_json_with_formatting() {
2055 let mut draft = Draft::plain("bold\nitem\nafter");
2056 draft.toggle(0..4, MarkKind::Bold);
2057 draft.set_line_kind(1, LineKind::Bullet(0), None, 0);
2058 let json = serde_json::to_string(&draft.to_lines()).unwrap();
2059 let lines: Vec<DraftLine> = serde_json::from_str(&json).unwrap();
2060 let restored = Draft::from_lines(&lines);
2061 assert_eq!(restored.text(), draft.text());
2062 assert_eq!(restored.to_html(), draft.to_html());
2063 assert_eq!(restored.lines(), draft.lines());
2064 }
2065
2049 2066 fn typed_draft(text: &str) -> Draft {
2050 2067 let mut draft = Draft::default();
2051 2068 typed(&mut draft, text);
@@ -392,6 +392,10 @@ impl Draft {
392 draft
392 draft
393 }
393 }
394
394
395 pub fn to_lines(&self) -> Vec<DraftLine> {
396 self.slice(0..self.text.len())
397 }
398
395 pub fn from_markdown(text: &str) -> Draft {
399 pub fn from_markdown(text: &str) -> Draft {
396 Draft::from_lines(&markdown_lines(text))
400 Draft::from_lines(&markdown_lines(text))
397 }
401 }
@@ -2046,6 +2050,19 @@ mod tests {
2046 );
2050 );
2047 }
2051 }
2048
2052
2053 #[test]
2054 fn lines_round_trip_through_json_with_formatting() {
2055 let mut draft = Draft::plain("bold\nitem\nafter");
2056 draft.toggle(0..4, MarkKind::Bold);
2057 draft.set_line_kind(1, LineKind::Bullet(0), None, 0);
2058 let json = serde_json::to_string(&draft.to_lines()).unwrap();
2059 let lines: Vec<DraftLine> = serde_json::from_str(&json).unwrap();
2060 let restored = Draft::from_lines(&lines);
2061 assert_eq!(restored.text(), draft.text());
2062 assert_eq!(restored.to_html(), draft.to_html());
2063 assert_eq!(restored.lines(), draft.lines());
2064 }
2065
2049 fn typed_draft(text: &str) -> Draft {
2066 fn typed_draft(text: &str) -> Draft {
2050 let mut draft = Draft::default();
2067 let mut draft = Draft::default();
2051 typed(&mut draft, text);
2068 typed(&mut draft, text);
crates/core/src/lib.rs +3 −1
@@ -24,6 +24,7 @@ mod presence;
24 24 mod preview;
25 25 mod receipts;
26 26 mod remote;
27 mod scheduled;
27 28 mod search;
28 29 mod sidebar_sync;
29 30 mod spans;
@@ -42,7 +43,7 @@ pub use card_inputs::{
42 43 MomentInput, NumberInput, TIME_PLACEHOLDER, TextInput, TextStyle, ToggleInput,
43 44 collect_input_values, merge_input_data,
44 45 };
45 pub use chatsvc::{ChatApp, Gif};
46 pub use chatsvc::{ChatApp, Gif, ScheduledDraft};
46 47 pub use draft::{
47 48 Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,
48 49 SizeStep, TypingStyle, changed_span, has_markdown, link_url, map_offset, reverse_edits,
@@ -66,6 +67,7 @@ pub use presence::{Availability, Presence};
66 67 pub use preview::preview_text;
67 68 pub use receipts::{ReceiptReader, ReceiptState};
68 69 pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};
70 pub use scheduled::NOTES_CHAT_ID;
69 71 pub use spans::{FontSize, Span, html_to_spans};
70 72 pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};
71 73 pub use stored::{
@@ -24,6 +24,7 @@ mod presence;
24mod preview;
24mod preview;
25mod receipts;
25mod receipts;
26mod remote;
26mod remote;
27mod scheduled;
27mod search;
28mod search;
28mod sidebar_sync;
29mod sidebar_sync;
29mod spans;
30mod spans;
@@ -42,7 +43,7 @@ pub use card_inputs::{
42 MomentInput, NumberInput, TIME_PLACEHOLDER, TextInput, TextStyle, ToggleInput,
43 MomentInput, NumberInput, TIME_PLACEHOLDER, TextInput, TextStyle, ToggleInput,
43 collect_input_values, merge_input_data,
44 collect_input_values, merge_input_data,
44};
45};
45pub use chatsvc::{ChatApp, Gif};
46pub use chatsvc::{ChatApp, Gif, ScheduledDraft};
46pub use draft::{
47pub use draft::{
47 Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,
48 Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,
48 SizeStep, TypingStyle, changed_span, has_markdown, link_url, map_offset, reverse_edits,
49 SizeStep, TypingStyle, changed_span, has_markdown, link_url, map_offset, reverse_edits,
@@ -66,6 +67,7 @@ pub use presence::{Availability, Presence};
66pub use preview::preview_text;
67pub use preview::preview_text;
67pub use receipts::{ReceiptReader, ReceiptState};
68pub use receipts::{ReceiptReader, ReceiptState};
68pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};
69pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};
70pub use scheduled::NOTES_CHAT_ID;
69pub use spans::{FontSize, Span, html_to_spans};
71pub use spans::{FontSize, Span, html_to_spans};
70pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};
72pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};
71pub use stored::{
73pub use stored::{
crates/core/src/mentions.rs +2 −1
@@ -1,10 +1,11 @@
1 1 use graph::{MentionTarget, OutgoingMention};
2 use serde::{Deserialize, Serialize};
2 3
3 4 use crate::error::{Error, Result};
4 5 use crate::markdown::escape_html;
5 6
6 7 /// `text` is the display name exactly as it appears after the `@` in the message text.
7 #[derive(Debug, Clone, PartialEq, Eq)]
8 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
8 9 pub struct MentionInput {
9 10 pub target: MentionTarget,
10 11 pub text: String,
@@ -1,10 +1,11 @@
1use graph::{MentionTarget, OutgoingMention};
1use graph::{MentionTarget, OutgoingMention};
2use serde::{Deserialize, Serialize};
2
3
3use crate::error::{Error, Result};
4use crate::error::{Error, Result};
4use crate::markdown::escape_html;
5use crate::markdown::escape_html;
5
6
6/// `text` is the display name exactly as it appears after the `@` in the message text.
7/// `text` is the display name exactly as it appears after the `@` in the message text.
7#[derive(Debug, Clone, PartialEq, Eq)]
8#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
8pub struct MentionInput {
9pub struct MentionInput {
9 pub target: MentionTarget,
10 pub target: MentionTarget,
10 pub text: String,
11 pub text: String,
crates/core/src/remote.rs +62 −1
@@ -1,6 +1,7 @@
1 1 use chatsvc::{
2 2 CardActions, ChatApp, ConversationRef, Conversations, Gif, Gifs, InvokeRequest, InvokeResponse,
3 LinkInfo, MemberHorizon, MessageLinks, Messages, Receipts,
3 LinkInfo, MemberHorizon, MessageLinks, Messages, Receipts, ScheduledDraft,
4 ScheduledDrafts,
4 5 };
5 6 use chrono::{DateTime, Utc};
6 7 use graph::{
@@ -241,6 +242,33 @@ pub trait Remote {
241 242 async fn search_gifs(&self, _query: &str) -> Result<Vec<Gif>> {
242 243 Err(Error::Unsupported("GIF search"))
243 244 }
245
246 async fn create_scheduled(
247 &self,
248 _inner_thread_id: &str,
249 _html: &str,
250 _send_at: DateTime<Utc>,
251 _display_name: &str,
252 ) -> Result<ScheduledDraft> {
253 Err(Error::Unsupported("schedule send"))
254 }
255
256 async fn scheduled_drafts(&self) -> Result<Vec<ScheduledDraft>> {
257 Err(Error::Unsupported("schedule send"))
258 }
259
260 async fn update_scheduled(
261 &self,
262 _draft: &ScheduledDraft,
263 _html: &str,
264 _display_name: &str,
265 ) -> Result<ScheduledDraft> {
266 Err(Error::Unsupported("schedule send"))
267 }
268
269 async fn cancel_scheduled(&self, _draft_id: &str) -> Result<()> {
270 Err(Error::Unsupported("schedule send"))
271 }
244 272 }
245 273
246 274 impl Remote for Graph {
@@ -628,6 +656,39 @@ impl Remote for Graph {
628 656 async fn search_gifs(&self, query: &str) -> Result<Vec<Gif>> {
629 657 Ok(Gifs::new(self.session()).search(query).await?)
630 658 }
659
660 async fn create_scheduled(
661 &self,
662 inner_thread_id: &str,
663 html: &str,
664 send_at: DateTime<Utc>,
665 display_name: &str,
666 ) -> Result<ScheduledDraft> {
667 Ok(ScheduledDrafts::new(self.session())
668 .create(inner_thread_id, html, send_at, display_name)
669 .await?)
670 }
671
672 async fn scheduled_drafts(&self) -> Result<Vec<ScheduledDraft>> {
673 Ok(ScheduledDrafts::new(self.session()).list().await?)
674 }
675
676 async fn update_scheduled(
677 &self,
678 draft: &ScheduledDraft,
679 html: &str,
680 display_name: &str,
681 ) -> Result<ScheduledDraft> {
682 Ok(ScheduledDrafts::new(self.session())
683 .update(draft, html, display_name)
684 .await?)
685 }
686
687 async fn cancel_scheduled(&self, draft_id: &str) -> Result<()> {
688 Ok(ScheduledDrafts::new(self.session())
689 .cancel(draft_id)
690 .await?)
691 }
631 692 }
632 693
633 694 fn chatsvc_conversation(target: &MessageTarget) -> Option<ConversationRef> {
@@ -1,6 +1,7 @@
1use chatsvc::{
1use chatsvc::{
2 CardActions, ChatApp, ConversationRef, Conversations, Gif, Gifs, InvokeRequest, InvokeResponse,
2 CardActions, ChatApp, ConversationRef, Conversations, Gif, Gifs, InvokeRequest, InvokeResponse,
3 LinkInfo, MemberHorizon, MessageLinks, Messages, Receipts,
3 LinkInfo, MemberHorizon, MessageLinks, Messages, Receipts, ScheduledDraft,
4 ScheduledDrafts,
4};
5};
5use chrono::{DateTime, Utc};
6use chrono::{DateTime, Utc};
6use graph::{
7use graph::{
@@ -241,6 +242,33 @@ pub trait Remote {
241 async fn search_gifs(&self, _query: &str) -> Result<Vec<Gif>> {
242 async fn search_gifs(&self, _query: &str) -> Result<Vec<Gif>> {
242 Err(Error::Unsupported("GIF search"))
243 Err(Error::Unsupported("GIF search"))
243 }
244 }
245
246 async fn create_scheduled(
247 &self,
248 _inner_thread_id: &str,
249 _html: &str,
250 _send_at: DateTime<Utc>,
251 _display_name: &str,
252 ) -> Result<ScheduledDraft> {
253 Err(Error::Unsupported("schedule send"))
254 }
255
256 async fn scheduled_drafts(&self) -> Result<Vec<ScheduledDraft>> {
257 Err(Error::Unsupported("schedule send"))
258 }
259
260 async fn update_scheduled(
261 &self,
262 _draft: &ScheduledDraft,
263 _html: &str,
264 _display_name: &str,
265 ) -> Result<ScheduledDraft> {
266 Err(Error::Unsupported("schedule send"))
267 }
268
269 async fn cancel_scheduled(&self, _draft_id: &str) -> Result<()> {
270 Err(Error::Unsupported("schedule send"))
271 }
244}
272}
245
273
246impl Remote for Graph {
274impl Remote for Graph {
@@ -628,6 +656,39 @@ impl Remote for Graph {
628 async fn search_gifs(&self, query: &str) -> Result<Vec<Gif>> {
656 async fn search_gifs(&self, query: &str) -> Result<Vec<Gif>> {
629 Ok(Gifs::new(self.session()).search(query).await?)
657 Ok(Gifs::new(self.session()).search(query).await?)
630 }
658 }
659
660 async fn create_scheduled(
661 &self,
662 inner_thread_id: &str,
663 html: &str,
664 send_at: DateTime<Utc>,
665 display_name: &str,
666 ) -> Result<ScheduledDraft> {
667 Ok(ScheduledDrafts::new(self.session())
668 .create(inner_thread_id, html, send_at, display_name)
669 .await?)
670 }
671
672 async fn scheduled_drafts(&self) -> Result<Vec<ScheduledDraft>> {
673 Ok(ScheduledDrafts::new(self.session()).list().await?)
674 }
675
676 async fn update_scheduled(
677 &self,
678 draft: &ScheduledDraft,
679 html: &str,
680 display_name: &str,
681 ) -> Result<ScheduledDraft> {
682 Ok(ScheduledDrafts::new(self.session())
683 .update(draft, html, display_name)
684 .await?)
685 }
686
687 async fn cancel_scheduled(&self, draft_id: &str) -> Result<()> {
688 Ok(ScheduledDrafts::new(self.session())
689 .cancel(draft_id)
690 .await?)
691 }
631}
692}
632
693
633fn chatsvc_conversation(target: &MessageTarget) -> Option<ConversationRef> {
694fn chatsvc_conversation(target: &MessageTarget) -> Option<ConversationRef> {
crates/core/src/scheduled.rs added +71 −0
@@ -0,0 +1,71 @@
1 use chatsvc::{ConversationRef, ScheduledDraft};
2 use chrono::{DateTime, Utc};
3
4 use crate::engine::{Conversation, SyncEngine};
5 use crate::error::{Error, Result};
6 use crate::remote::Remote;
7
8 pub const NOTES_CHAT_ID: &str = "48:notes";
9
10 impl<R: Remote> SyncEngine<R> {
11 pub async fn schedule_message(
12 &self,
13 conversation_id: &str,
14 thread_root_id: Option<&str>,
15 html: &str,
16 send_at: DateTime<Utc>,
17 ) -> Result<ScheduledDraft> {
18 let inner_thread_id = self.inner_thread_id(conversation_id, thread_root_id)?;
19 let display_name = self.display_name().await?;
20 self.remote
21 .create_scheduled(&inner_thread_id, html, send_at, &display_name)
22 .await
23 }
24
25 pub async fn scheduled_messages(&self) -> Result<Vec<ScheduledDraft>> {
26 let mut drafts = self.remote.scheduled_drafts().await?;
27 drafts.sort_by_key(|draft| draft.send_at);
28 Ok(drafts)
29 }
30
31 pub async fn update_scheduled(
32 &self,
33 draft: &ScheduledDraft,
34 html: &str,
35 ) -> Result<ScheduledDraft> {
36 let display_name = self.display_name().await?;
37 self.remote
38 .update_scheduled(draft, html, &display_name)
39 .await
40 }
41
42 pub async fn cancel_scheduled(&self, draft_id: &str) -> Result<()> {
43 self.remote.cancel_scheduled(draft_id).await
44 }
45
46 fn inner_thread_id(
47 &self,
48 conversation_id: &str,
49 thread_root_id: Option<&str>,
50 ) -> Result<String> {
51 if conversation_id == NOTES_CHAT_ID {
52 return Err(Error::Unsupported("schedule send in the notes chat"));
53 }
54 let conversation = match (self.resolve(conversation_id)?, thread_root_id) {
55 (Conversation::Chat, None) => ConversationRef::chat(conversation_id),
56 (Conversation::Channel { .. }, None) => ConversationRef::channel_root(conversation_id),
57 (Conversation::Channel { .. }, Some(root_id)) => {
58 ConversationRef::channel_reply(conversation_id, root_id)
59 }
60 (Conversation::Chat, Some(_)) => {
61 return Err(Error::Unsupported("a thread reply in a chat"));
62 }
63 };
64 Ok(conversation.conversation_id())
65 }
66
67 async fn display_name(&self) -> Result<String> {
68 self.ensure_display_name().await?;
69 Ok(self.me().map(|me| me.display_name).unwrap_or_default())
70 }
71 }
@@ -0,0 +1,71 @@
1use chatsvc::{ConversationRef, ScheduledDraft};
2use chrono::{DateTime, Utc};
3
4use crate::engine::{Conversation, SyncEngine};
5use crate::error::{Error, Result};
6use crate::remote::Remote;
7
8pub const NOTES_CHAT_ID: &str = "48:notes";
9
10impl<R: Remote> SyncEngine<R> {
11 pub async fn schedule_message(
12 &self,
13 conversation_id: &str,
14 thread_root_id: Option<&str>,
15 html: &str,
16 send_at: DateTime<Utc>,
17 ) -> Result<ScheduledDraft> {
18 let inner_thread_id = self.inner_thread_id(conversation_id, thread_root_id)?;
19 let display_name = self.display_name().await?;
20 self.remote
21 .create_scheduled(&inner_thread_id, html, send_at, &display_name)
22 .await
23 }
24
25 pub async fn scheduled_messages(&self) -> Result<Vec<ScheduledDraft>> {
26 let mut drafts = self.remote.scheduled_drafts().await?;
27 drafts.sort_by_key(|draft| draft.send_at);
28 Ok(drafts)
29 }
30
31 pub async fn update_scheduled(
32 &self,
33 draft: &ScheduledDraft,
34 html: &str,
35 ) -> Result<ScheduledDraft> {
36 let display_name = self.display_name().await?;
37 self.remote
38 .update_scheduled(draft, html, &display_name)
39 .await
40 }
41
42 pub async fn cancel_scheduled(&self, draft_id: &str) -> Result<()> {
43 self.remote.cancel_scheduled(draft_id).await
44 }
45
46 fn inner_thread_id(
47 &self,
48 conversation_id: &str,
49 thread_root_id: Option<&str>,
50 ) -> Result<String> {
51 if conversation_id == NOTES_CHAT_ID {
52 return Err(Error::Unsupported("schedule send in the notes chat"));
53 }
54 let conversation = match (self.resolve(conversation_id)?, thread_root_id) {
55 (Conversation::Chat, None) => ConversationRef::chat(conversation_id),
56 (Conversation::Channel { .. }, None) => ConversationRef::channel_root(conversation_id),
57 (Conversation::Channel { .. }, Some(root_id)) => {
58 ConversationRef::channel_reply(conversation_id, root_id)
59 }
60 (Conversation::Chat, Some(_)) => {
61 return Err(Error::Unsupported("a thread reply in a chat"));
62 }
63 };
64 Ok(conversation.conversation_id())
65 }
66
67 async fn display_name(&self) -> Result<String> {
68 self.ensure_display_name().await?;
69 Ok(self.me().map(|me| me.display_name).unwrap_or_default())
70 }
71}
crates/core/src/stored.rs +1 −1
@@ -28,7 +28,7 @@ pub struct AttachmentInfo {
28 28 pub content: Option<String>,
29 29 }
30 30
31 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
31 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
32 32 pub enum FileKind {
33 33 Word,
34 34 Excel,
@@ -28,7 +28,7 @@ pub struct AttachmentInfo {
28 pub content: Option<String>,
28 pub content: Option<String>,
29}
29}
30
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
32pub enum FileKind {
32pub enum FileKind {
33 Word,
33 Word,
34 Excel,
34 Excel,
crates/core/tests/engine.rs +79 −0
@@ -63,6 +63,8 @@ fn chat(
63 63 .unwrap()
64 64 }
65 65
66 type ScheduledCall = (String, String, DateTime<Utc>, String);
67
66 68 #[derive(Default)]
67 69 struct Fake {
68 70 chats: Mutex<Vec<Chat>>,
@@ -99,6 +101,7 @@ struct Fake {
99 101 link_page_calls: Mutex<Vec<String>>,
100 102 links_put: Mutex<Vec<(String, String)>>,
101 103 link_info_calls: Mutex<usize>,
104 scheduled: Mutex<Vec<ScheduledCall>>,
102 105 }
103 106
104 107 impl Fake {
@@ -625,6 +628,29 @@ impl Remote for Handle {
625 628 Ok(self.apps.lock().unwrap().clone())
626 629 }
627 630
631 async fn create_scheduled(
632 &self,
633 inner_thread_id: &str,
634 html: &str,
635 send_at: DateTime<Utc>,
636 display_name: &str,
637 ) -> Result<chatsvc::ScheduledDraft> {
638 self.scheduled.lock().unwrap().push((
639 inner_thread_id.to_owned(),
640 html.to_owned(),
641 send_at,
642 display_name.to_owned(),
643 ));
644 Ok(chatsvc::ScheduledDraft {
645 id: "d1".to_owned(),
646 client_message_id: "1".to_owned(),
647 inner_thread_id: inner_thread_id.to_owned(),
648 send_at,
649 html: html.to_owned(),
650 delivery_state: None,
651 })
652 }
653
628 654 async fn invoke_card(&self, invoke: chatsvc::InvokeRequest) -> Result<chatsvc::InvokeResponse> {
629 655 self.invokes.lock().unwrap().push(invoke);
630 656 Ok(self
@@ -3214,3 +3240,56 @@ async fn link_infos_are_fetched_once_per_url_and_internal_links_never() {
3214 3240 );
3215 3241 assert_eq!(*fake.link_info_calls.lock().unwrap(), 1);
3216 3242 }
3243
3244 #[tokio::test]
3245 async fn schedule_message_resolves_the_inner_thread_id() {
3246 let fake = Arc::new(Fake::default());
3247 *fake.teams.lock().unwrap() =
3248 vec![serde_json::from_value(json!({"id": "team-1", "displayName": "Squad"})).unwrap()];
3249 *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)];
3250 let engine = engine_with(&fake, small_pages());
3251 engine.refresh_sidebar().await.unwrap();
3252 let send_at = base() + Duration::days(1);
3253
3254 let draft = engine
3255 .schedule_message(CHAT, None, "<p>a</p>", send_at)
3256 .await
3257 .unwrap();
3258 assert_eq!(draft.id, "d1");
3259 engine
3260 .schedule_message(CHANNEL, None, "<p>b</p>", send_at)
3261 .await
3262 .unwrap();
3263 engine
3264 .schedule_message(CHANNEL, Some("m0030"), "<p>c</p>", send_at)
3265 .await
3266 .unwrap();
3267
3268 let created = fake.scheduled.lock().unwrap().clone();
3269 let thread_ids: Vec<&str> = created.iter().map(|entry| entry.0.as_str()).collect();
3270 assert_eq!(
3271 thread_ids,
3272 [CHAT, CHANNEL, "19:channel@thread.tacv2;messageid=m0030"]
3273 );
3274 assert_eq!(created[0].3, "Me Myself");
3275 }
3276
3277 #[tokio::test]
3278 async fn schedule_message_rejects_notes_and_chat_threads() {
3279 let fake = Arc::new(Fake::default());
3280 let engine = chat_engine(&fake, small_pages()).await;
3281 let send_at = base();
3282 assert!(matches!(
3283 engine
3284 .schedule_message(teams_core::NOTES_CHAT_ID, None, "<p>a</p>", send_at)
3285 .await,
3286 Err(Error::Unsupported(_))
3287 ));
3288 assert!(matches!(
3289 engine
3290 .schedule_message(CHAT, Some("m1"), "<p>a</p>", send_at)
3291 .await,
3292 Err(Error::Unsupported(_))
3293 ));
3294 assert!(fake.scheduled.lock().unwrap().is_empty());
3295 }
@@ -63,6 +63,8 @@ fn chat(
63 .unwrap()
63 .unwrap()
64}
64}
65
65
66type ScheduledCall = (String, String, DateTime<Utc>, String);
67
66#[derive(Default)]
68#[derive(Default)]
67struct Fake {
69struct Fake {
68 chats: Mutex<Vec<Chat>>,
70 chats: Mutex<Vec<Chat>>,
@@ -99,6 +101,7 @@ struct Fake {
99 link_page_calls: Mutex<Vec<String>>,
101 link_page_calls: Mutex<Vec<String>>,
100 links_put: Mutex<Vec<(String, String)>>,
102 links_put: Mutex<Vec<(String, String)>>,
101 link_info_calls: Mutex<usize>,
103 link_info_calls: Mutex<usize>,
104 scheduled: Mutex<Vec<ScheduledCall>>,
102}
105}
103
106
104impl Fake {
107impl Fake {
@@ -625,6 +628,29 @@ impl Remote for Handle {
625 Ok(self.apps.lock().unwrap().clone())
628 Ok(self.apps.lock().unwrap().clone())
626 }
629 }
627
630
631 async fn create_scheduled(
632 &self,
633 inner_thread_id: &str,
634 html: &str,
635 send_at: DateTime<Utc>,
636 display_name: &str,
637 ) -> Result<chatsvc::ScheduledDraft> {
638 self.scheduled.lock().unwrap().push((
639 inner_thread_id.to_owned(),
640 html.to_owned(),
641 send_at,
642 display_name.to_owned(),
643 ));
644 Ok(chatsvc::ScheduledDraft {
645 id: "d1".to_owned(),
646 client_message_id: "1".to_owned(),
647 inner_thread_id: inner_thread_id.to_owned(),
648 send_at,
649 html: html.to_owned(),
650 delivery_state: None,
651 })
652 }
653
628 async fn invoke_card(&self, invoke: chatsvc::InvokeRequest) -> Result<chatsvc::InvokeResponse> {
654 async fn invoke_card(&self, invoke: chatsvc::InvokeRequest) -> Result<chatsvc::InvokeResponse> {
629 self.invokes.lock().unwrap().push(invoke);
655 self.invokes.lock().unwrap().push(invoke);
630 Ok(self
656 Ok(self
@@ -3214,3 +3240,56 @@ async fn link_infos_are_fetched_once_per_url_and_internal_links_never() {
3214 );
3240 );
3215 assert_eq!(*fake.link_info_calls.lock().unwrap(), 1);
3241 assert_eq!(*fake.link_info_calls.lock().unwrap(), 1);
3216}
3242}
3243
3244#[tokio::test]
3245async fn schedule_message_resolves_the_inner_thread_id() {
3246 let fake = Arc::new(Fake::default());
3247 *fake.teams.lock().unwrap() =
3248 vec![serde_json::from_value(json!({"id": "team-1", "displayName": "Squad"})).unwrap()];
3249 *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)];
3250 let engine = engine_with(&fake, small_pages());
3251 engine.refresh_sidebar().await.unwrap();
3252 let send_at = base() + Duration::days(1);
3253
3254 let draft = engine
3255 .schedule_message(CHAT, None, "<p>a</p>", send_at)
3256 .await
3257 .unwrap();
3258 assert_eq!(draft.id, "d1");
3259 engine
3260 .schedule_message(CHANNEL, None, "<p>b</p>", send_at)
3261 .await
3262 .unwrap();
3263 engine
3264 .schedule_message(CHANNEL, Some("m0030"), "<p>c</p>", send_at)
3265 .await
3266 .unwrap();
3267
3268 let created = fake.scheduled.lock().unwrap().clone();
3269 let thread_ids: Vec<&str> = created.iter().map(|entry| entry.0.as_str()).collect();
3270 assert_eq!(
3271 thread_ids,
3272 [CHAT, CHANNEL, "19:channel@thread.tacv2;messageid=m0030"]
3273 );
3274 assert_eq!(created[0].3, "Me Myself");
3275}
3276
3277#[tokio::test]
3278async fn schedule_message_rejects_notes_and_chat_threads() {
3279 let fake = Arc::new(Fake::default());
3280 let engine = chat_engine(&fake, small_pages()).await;
3281 let send_at = base();
3282 assert!(matches!(
3283 engine
3284 .schedule_message(teams_core::NOTES_CHAT_ID, None, "<p>a</p>", send_at)
3285 .await,
3286 Err(Error::Unsupported(_))
3287 ));
3288 assert!(matches!(
3289 engine
3290 .schedule_message(CHAT, Some("m1"), "<p>a</p>", send_at)
3291 .await,
3292 Err(Error::Unsupported(_))
3293 ));
3294 assert!(fake.scheduled.lock().unwrap().is_empty());
3295}
crates/graph/src/files.rs +2 −2
@@ -1,6 +1,6 @@
1 1 use base64::Engine as _;
2 2 use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
3 use serde::Deserialize;
3 use serde::{Deserialize, Serialize};
4 4 use serde_json::{Value, json};
5 5 use session::{Method, Request, Scope, Session};
6 6
@@ -36,7 +36,7 @@ pub struct SharedFile {
36 36 pub download_url: String,
37 37 }
38 38
39 #[derive(Debug, Clone, PartialEq, Eq)]
39 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40 40 pub struct UploadedFile {
41 41 pub drive_id: String,
42 42 pub item_id: String,
@@ -1,6 +1,6 @@
1use base64::Engine as _;
1use base64::Engine as _;
2use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
2use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
3use serde::Deserialize;
3use serde::{Deserialize, Serialize};
4use serde_json::{Value, json};
4use serde_json::{Value, json};
5use session::{Method, Request, Scope, Session};
5use session::{Method, Request, Scope, Session};
6
6
@@ -36,7 +36,7 @@ pub struct SharedFile {
36 pub download_url: String,
36 pub download_url: String,
37}
37}
38
38
39#[derive(Debug, Clone, PartialEq, Eq)]
39#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40pub struct UploadedFile {
40pub struct UploadedFile {
41 pub drive_id: String,
41 pub drive_id: String,
42 pub item_id: String,
42 pub item_id: String,
crates/graph/src/outgoing.rs +3 −2
@@ -2,9 +2,10 @@ use std::sync::Arc;
2 2
3 3 use base64::Engine as _;
4 4 use base64::engine::general_purpose::STANDARD;
5 use serde::{Deserialize, Serialize};
5 6 use serde_json::{Value, json};
6 7
7 #[derive(Debug, Clone, PartialEq, Eq)]
8 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
8 9 pub enum MentionTarget {
9 10 User { user_id: String },
10 11 Channel { channel_id: String },
@@ -43,7 +44,7 @@ pub struct HostedImage {
43 44 }
44 45
45 46 /// `attachment_id` is the GUID inside the file's eTag; it matches the `<attachment id>` tag in the html body.
46 #[derive(Debug, Clone, PartialEq, Eq)]
47 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
47 48 pub struct FileReference {
48 49 pub attachment_id: String,
49 50 pub content_url: String,
@@ -2,9 +2,10 @@ use std::sync::Arc;
2
2
3use base64::Engine as _;
3use base64::Engine as _;
4use base64::engine::general_purpose::STANDARD;
4use base64::engine::general_purpose::STANDARD;
5use serde::{Deserialize, Serialize};
5use serde_json::{Value, json};
6use serde_json::{Value, json};
6
7
7#[derive(Debug, Clone, PartialEq, Eq)]
8#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
8pub enum MentionTarget {
9pub enum MentionTarget {
9 User { user_id: String },
10 User { user_id: String },
10 Channel { channel_id: String },
11 Channel { channel_id: String },
@@ -43,7 +44,7 @@ pub struct HostedImage {
43}
44}
44
45
45/// `attachment_id` is the GUID inside the file's eTag; it matches the `<attachment id>` tag in the html body.
46/// `attachment_id` is the GUID inside the file's eTag; it matches the `<attachment id>` tag in the html body.
46#[derive(Debug, Clone, PartialEq, Eq)]
47#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
47pub struct FileReference {
48pub struct FileReference {
48 pub attachment_id: String,
49 pub attachment_id: String,
49 pub content_url: String,
50 pub content_url: String,
crates/store/src/attachment_images.rs added +68 −0
@@ -0,0 +1,68 @@
1 use rusqlite::{Connection, params};
2
3 use crate::error::Result;
4 use crate::models::AttachmentImage;
5
6 pub(crate) const OUTBOX_OWNER: &str = "outbox";
7 pub(crate) const DRAFT_OWNER: &str = "draft";
8
9 pub(crate) fn replace_images(
10 connection: &Connection,
11 owner_kind: &str,
12 owner_id: &str,
13 images: &[AttachmentImage],
14 ) -> Result<()> {
15 delete_images(connection, owner_kind, owner_id)?;
16 let mut insert = connection.prepare_cached(
17 "INSERT INTO attachment_images (owner_kind, owner_id, position, name, format, bytes, width, height)
18 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
19 )?;
20 for (position, image) in images.iter().enumerate() {
21 insert.execute(params![
22 owner_kind,
23 owner_id,
24 position as i64,
25 image.name,
26 image.format,
27 image.bytes,
28 image.width,
29 image.height,
30 ])?;
31 }
32 Ok(())
33 }
34
35 pub(crate) fn load_images(
36 connection: &Connection,
37 owner_kind: &str,
38 owner_id: &str,
39 ) -> Result<Vec<AttachmentImage>> {
40 let mut statement = connection.prepare_cached(
41 "SELECT name, format, bytes, width, height FROM attachment_images
42 WHERE owner_kind = ?1 AND owner_id = ?2 ORDER BY position",
43 )?;
44 let images = statement
45 .query_map(params![owner_kind, owner_id], |row| {
46 Ok(AttachmentImage {
47 name: row.get(0)?,
48 format: row.get(1)?,
49 bytes: row.get(2)?,
50 width: row.get(3)?,
51 height: row.get(4)?,
52 })
53 })?
54 .collect::<rusqlite::Result<Vec<_>>>()?;
55 Ok(images)
56 }
57
58 pub(crate) fn delete_images(
59 connection: &Connection,
60 owner_kind: &str,
61 owner_id: &str,
62 ) -> Result<()> {
63 connection.execute(
64 "DELETE FROM attachment_images WHERE owner_kind = ?1 AND owner_id = ?2",
65 params![owner_kind, owner_id],
66 )?;
67 Ok(())
68 }
@@ -0,0 +1,68 @@
1use rusqlite::{Connection, params};
2
3use crate::error::Result;
4use crate::models::AttachmentImage;
5
6pub(crate) const OUTBOX_OWNER: &str = "outbox";
7pub(crate) const DRAFT_OWNER: &str = "draft";
8
9pub(crate) fn replace_images(
10 connection: &Connection,
11 owner_kind: &str,
12 owner_id: &str,
13 images: &[AttachmentImage],
14) -> Result<()> {
15 delete_images(connection, owner_kind, owner_id)?;
16 let mut insert = connection.prepare_cached(
17 "INSERT INTO attachment_images (owner_kind, owner_id, position, name, format, bytes, width, height)
18 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
19 )?;
20 for (position, image) in images.iter().enumerate() {
21 insert.execute(params![
22 owner_kind,
23 owner_id,
24 position as i64,
25 image.name,
26 image.format,
27 image.bytes,
28 image.width,
29 image.height,
30 ])?;
31 }
32 Ok(())
33}
34
35pub(crate) fn load_images(
36 connection: &Connection,
37 owner_kind: &str,
38 owner_id: &str,
39) -> Result<Vec<AttachmentImage>> {
40 let mut statement = connection.prepare_cached(
41 "SELECT name, format, bytes, width, height FROM attachment_images
42 WHERE owner_kind = ?1 AND owner_id = ?2 ORDER BY position",
43 )?;
44 let images = statement
45 .query_map(params![owner_kind, owner_id], |row| {
46 Ok(AttachmentImage {
47 name: row.get(0)?,
48 format: row.get(1)?,
49 bytes: row.get(2)?,
50 width: row.get(3)?,
51 height: row.get(4)?,
52 })
53 })?
54 .collect::<rusqlite::Result<Vec<_>>>()?;
55 Ok(images)
56}
57
58pub(crate) fn delete_images(
59 connection: &Connection,
60 owner_kind: &str,
61 owner_id: &str,
62) -> Result<()> {
63 connection.execute(
64 "DELETE FROM attachment_images WHERE owner_kind = ?1 AND owner_id = ?2",
65 params![owner_kind, owner_id],
66 )?;
67 Ok(())
68}
crates/store/src/drafts.rs added +97 −0
@@ -0,0 +1,97 @@
1 use std::collections::HashMap;
2
3 use rusqlite::{OptionalExtension, params};
4
5 use crate::attachment_images::{DRAFT_OWNER, delete_images, load_images, replace_images};
6 use crate::error::Result;
7 use crate::models::DraftRecord;
8 use crate::store::Store;
9 use crate::time::{from_millis, to_millis};
10
11 impl Store {
12 pub fn save_draft(&self, record: &DraftRecord) -> Result<()> {
13 let mut connection = self.lock()?;
14 let transaction = connection.transaction()?;
15 transaction.execute(
16 "INSERT INTO drafts (conversation_id, payload, preview, updated_at) VALUES (?1, ?2, ?3, ?4)
17 ON CONFLICT (conversation_id) DO UPDATE SET
18 payload = excluded.payload, preview = excluded.preview,
19 updated_at = excluded.updated_at",
20 params![
21 record.conversation_id,
22 record.payload,
23 record.preview,
24 to_millis(record.updated_at),
25 ],
26 )?;
27 replace_images(
28 &transaction,
29 DRAFT_OWNER,
30 &record.conversation_id,
31 &record.images,
32 )?;
33 Ok(transaction.commit()?)
34 }
35
36 pub fn save_draft_text(&self, record: &DraftRecord) -> Result<()> {
37 self.lock()?.execute(
38 "INSERT INTO drafts (conversation_id, payload, preview, updated_at) VALUES (?1, ?2, ?3, ?4)
39 ON CONFLICT (conversation_id) DO UPDATE SET
40 payload = excluded.payload, preview = excluded.preview,
41 updated_at = excluded.updated_at",
42 params![
43 record.conversation_id,
44 record.payload,
45 record.preview,
46 to_millis(record.updated_at),
47 ],
48 )?;
49 Ok(())
50 }
51
52 pub fn draft(&self, conversation_id: &str) -> Result<Option<DraftRecord>> {
53 let connection = self.lock()?;
54 let found = connection
55 .query_row(
56 "SELECT payload, preview, updated_at FROM drafts WHERE conversation_id = ?1",
57 [conversation_id],
58 |row| {
59 Ok(DraftRecord {
60 conversation_id: conversation_id.to_owned(),
61 payload: row.get(0)?,
62 preview: row.get(1)?,
63 images: Vec::new(),
64 updated_at: from_millis(row.get(2)?),
65 })
66 },
67 )
68 .optional()?;
69 found
70 .map(|mut record| {
71 record.images = load_images(&connection, DRAFT_OWNER, conversation_id)?;
72 Ok(record)
73 })
74 .transpose()
75 }
76
77 pub fn delete_draft(&self, conversation_id: &str) -> Result<()> {
78 let mut connection = self.lock()?;
79 let transaction = connection.transaction()?;
80 transaction.execute(
81 "DELETE FROM drafts WHERE conversation_id = ?1",
82 [conversation_id],
83 )?;
84 delete_images(&transaction, DRAFT_OWNER, conversation_id)?;
85 Ok(transaction.commit()?)
86 }
87
88 pub fn draft_previews(&self) -> Result<HashMap<String, String>> {
89 let connection = self.lock()?;
90 let mut statement =
91 connection.prepare_cached("SELECT conversation_id, preview FROM drafts")?;
92 let previews = statement
93 .query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?
94 .collect::<rusqlite::Result<_>>()?;
95 Ok(previews)
96 }
97 }
@@ -0,0 +1,97 @@
1use std::collections::HashMap;
2
3use rusqlite::{OptionalExtension, params};
4
5use crate::attachment_images::{DRAFT_OWNER, delete_images, load_images, replace_images};
6use crate::error::Result;
7use crate::models::DraftRecord;
8use crate::store::Store;
9use crate::time::{from_millis, to_millis};
10
11impl Store {
12 pub fn save_draft(&self, record: &DraftRecord) -> Result<()> {
13 let mut connection = self.lock()?;
14 let transaction = connection.transaction()?;
15 transaction.execute(
16 "INSERT INTO drafts (conversation_id, payload, preview, updated_at) VALUES (?1, ?2, ?3, ?4)
17 ON CONFLICT (conversation_id) DO UPDATE SET
18 payload = excluded.payload, preview = excluded.preview,
19 updated_at = excluded.updated_at",
20 params![
21 record.conversation_id,
22 record.payload,
23 record.preview,
24 to_millis(record.updated_at),
25 ],
26 )?;
27 replace_images(
28 &transaction,
29 DRAFT_OWNER,
30 &record.conversation_id,
31 &record.images,
32 )?;
33 Ok(transaction.commit()?)
34 }
35
36 pub fn save_draft_text(&self, record: &DraftRecord) -> Result<()> {
37 self.lock()?.execute(
38 "INSERT INTO drafts (conversation_id, payload, preview, updated_at) VALUES (?1, ?2, ?3, ?4)
39 ON CONFLICT (conversation_id) DO UPDATE SET
40 payload = excluded.payload, preview = excluded.preview,
41 updated_at = excluded.updated_at",
42 params![
43 record.conversation_id,
44 record.payload,
45 record.preview,
46 to_millis(record.updated_at),
47 ],
48 )?;
49 Ok(())
50 }
51
52 pub fn draft(&self, conversation_id: &str) -> Result<Option<DraftRecord>> {
53 let connection = self.lock()?;
54 let found = connection
55 .query_row(
56 "SELECT payload, preview, updated_at FROM drafts WHERE conversation_id = ?1",
57 [conversation_id],
58 |row| {
59 Ok(DraftRecord {
60 conversation_id: conversation_id.to_owned(),
61 payload: row.get(0)?,
62 preview: row.get(1)?,
63 images: Vec::new(),
64 updated_at: from_millis(row.get(2)?),
65 })
66 },
67 )
68 .optional()?;
69 found
70 .map(|mut record| {
71 record.images = load_images(&connection, DRAFT_OWNER, conversation_id)?;
72 Ok(record)
73 })
74 .transpose()
75 }
76
77 pub fn delete_draft(&self, conversation_id: &str) -> Result<()> {
78 let mut connection = self.lock()?;
79 let transaction = connection.transaction()?;
80 transaction.execute(
81 "DELETE FROM drafts WHERE conversation_id = ?1",
82 [conversation_id],
83 )?;
84 delete_images(&transaction, DRAFT_OWNER, conversation_id)?;
85 Ok(transaction.commit()?)
86 }
87
88 pub fn draft_previews(&self) -> Result<HashMap<String, String>> {
89 let connection = self.lock()?;
90 let mut statement =
91 connection.prepare_cached("SELECT conversation_id, preview FROM drafts")?;
92 let previews = statement
93 .query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?
94 .collect::<rusqlite::Result<_>>()?;
95 Ok(previews)
96 }
97}
crates/store/src/lib.rs +7 −3
@@ -1,6 +1,8 @@
1 1 mod activity;
2 mod attachment_images;
2 3 mod avatars;
3 4 mod chats;
5 mod drafts;
4 6 mod error;
5 7 mod folders;
6 8 mod image_files;
@@ -9,6 +11,7 @@ mod messages;
9 11 mod meta;
10 12 mod migrations;
11 13 mod models;
14 mod outbox;
12 15 mod presence;
13 16 mod search;
14 17 mod sidebar;
@@ -21,9 +24,10 @@ mod time;
21 24 pub use error::{Error, Result};
22 25 pub use image_files::ImageFileCache;
23 26 pub use models::{
24 ActivityRecord, AvatarRecord, ChannelLayoutRecord, ChannelRecord, ChatPreview, ChatRecord,
25 ConversationHit, FolderRecord, ImageRecord, MemberRecord, MessageRecord, SearchHit, Sidebar,
26 SidebarTeam, SyncState, TeamLayoutRecord, TeamRecord,
27 ActivityRecord, AttachmentImage, AvatarRecord, ChannelLayoutRecord, ChannelRecord, ChatPreview,
28 ChatRecord, ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord,
29 MessageRecord, OutboxRecord, OutboxState, OutboxTarget, SearchHit, Sidebar, SidebarTeam,
30 SyncState, TeamLayoutRecord, TeamRecord,
27 31 };
28 32 pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};
29 33 pub use store::{DATA_DIR_NAME, Store, default_database_path};
@@ -1,6 +1,8 @@
1mod activity;
1mod activity;
2mod attachment_images;
2mod avatars;
3mod avatars;
3mod chats;
4mod chats;
5mod drafts;
4mod error;
6mod error;
5mod folders;
7mod folders;
6mod image_files;
8mod image_files;
@@ -9,6 +11,7 @@ mod messages;
9mod meta;
11mod meta;
10mod migrations;
12mod migrations;
11mod models;
13mod models;
14mod outbox;
12mod presence;
15mod presence;
13mod search;
16mod search;
14mod sidebar;
17mod sidebar;
@@ -21,9 +24,10 @@ mod time;
21pub use error::{Error, Result};
24pub use error::{Error, Result};
22pub use image_files::ImageFileCache;
25pub use image_files::ImageFileCache;
23pub use models::{
26pub use models::{
24 ActivityRecord, AvatarRecord, ChannelLayoutRecord, ChannelRecord, ChatPreview, ChatRecord,
27 ActivityRecord, AttachmentImage, AvatarRecord, ChannelLayoutRecord, ChannelRecord, ChatPreview,
25 ConversationHit, FolderRecord, ImageRecord, MemberRecord, MessageRecord, SearchHit, Sidebar,
28 ChatRecord, ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord,
26 SidebarTeam, SyncState, TeamLayoutRecord, TeamRecord,
29 MessageRecord, OutboxRecord, OutboxState, OutboxTarget, SearchHit, Sidebar, SidebarTeam,
30 SyncState, TeamLayoutRecord, TeamRecord,
27};
31};
28pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};
32pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};
29pub use store::{DATA_DIR_NAME, Store, default_database_path};
33pub use store::{DATA_DIR_NAME, Store, default_database_path};
crates/store/src/migrations.rs +4 −0
@@ -53,6 +53,10 @@ const MIGRATIONS: &[Migration] = &[
53 53 script: include_str!("migrations/0011_message_links.sql"),
54 54 after: None,
55 55 },
56 Migration {
57 script: include_str!("migrations/0012_outbox_drafts.sql"),
58 after: None,
59 },
56 60 ];
57 61
58 62 pub fn latest_version() -> i64 {
@@ -53,6 +53,10 @@ const MIGRATIONS: &[Migration] = &[
53 script: include_str!("migrations/0011_message_links.sql"),
53 script: include_str!("migrations/0011_message_links.sql"),
54 after: None,
54 after: None,
55 },
55 },
56 Migration {
57 script: include_str!("migrations/0012_outbox_drafts.sql"),
58 after: None,
59 },
56];
60];
57
61
58pub fn latest_version() -> i64 {
62pub fn latest_version() -> i64 {
crates/store/src/migrations/0012_outbox_drafts.sql added +31 −0
@@ -0,0 +1,31 @@
1 CREATE TABLE outbox (
2 id TEXT PRIMARY KEY,
3 conversation_id TEXT NOT NULL,
4 target TEXT NOT NULL,
5 thread_root_id TEXT,
6 payload TEXT NOT NULL,
7 state TEXT NOT NULL,
8 last_error TEXT,
9 created_at INTEGER NOT NULL
10 );
11
12 CREATE INDEX outbox_by_conversation ON outbox (conversation_id, created_at);
13
14 CREATE TABLE drafts (
15 conversation_id TEXT PRIMARY KEY,
16 payload TEXT NOT NULL,
17 preview TEXT NOT NULL,
18 updated_at INTEGER NOT NULL
19 );
20
21 CREATE TABLE attachment_images (
22 owner_kind TEXT NOT NULL,
23 owner_id TEXT NOT NULL,
24 position INTEGER NOT NULL,
25 name TEXT NOT NULL,
26 format TEXT NOT NULL,
27 bytes BLOB NOT NULL,
28 width INTEGER,
29 height INTEGER,
30 PRIMARY KEY (owner_kind, owner_id, position)
31 ) WITHOUT ROWID;
@@ -0,0 +1,31 @@
1CREATE TABLE outbox (
2 id TEXT PRIMARY KEY,
3 conversation_id TEXT NOT NULL,
4 target TEXT NOT NULL,
5 thread_root_id TEXT,
6 payload TEXT NOT NULL,
7 state TEXT NOT NULL,
8 last_error TEXT,
9 created_at INTEGER NOT NULL
10);
11
12CREATE INDEX outbox_by_conversation ON outbox (conversation_id, created_at);
13
14CREATE TABLE drafts (
15 conversation_id TEXT PRIMARY KEY,
16 payload TEXT NOT NULL,
17 preview TEXT NOT NULL,
18 updated_at INTEGER NOT NULL
19);
20
21CREATE TABLE attachment_images (
22 owner_kind TEXT NOT NULL,
23 owner_id TEXT NOT NULL,
24 position INTEGER NOT NULL,
25 name TEXT NOT NULL,
26 format TEXT NOT NULL,
27 bytes BLOB NOT NULL,
28 width INTEGER,
29 height INTEGER,
30 PRIMARY KEY (owner_kind, owner_id, position)
31) WITHOUT ROWID;
crates/store/src/models.rs +80 −0
@@ -168,3 +168,83 @@ pub struct ActivityRecord {
168 168 pub updated_at: DateTime<Utc>,
169 169 pub read: bool,
170 170 }
171
172 #[derive(Debug, Clone, PartialEq, Eq)]
173 pub struct AttachmentImage {
174 pub name: String,
175 pub format: String,
176 pub bytes: Vec<u8>,
177 pub width: Option<u32>,
178 pub height: Option<u32>,
179 }
180
181 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
182 pub enum OutboxTarget {
183 Flat,
184 Post,
185 Thread,
186 }
187
188 impl OutboxTarget {
189 pub(crate) fn as_str(self) -> &'static str {
190 match self {
191 OutboxTarget::Flat => "flat",
192 OutboxTarget::Post => "post",
193 OutboxTarget::Thread => "thread",
194 }
195 }
196
197 pub(crate) fn parse(value: &str) -> Option<Self> {
198 match value {
199 "flat" => Some(OutboxTarget::Flat),
200 "post" => Some(OutboxTarget::Post),
201 "thread" => Some(OutboxTarget::Thread),
202 _ => None,
203 }
204 }
205 }
206
207 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
208 pub enum OutboxState {
209 Sending,
210 Failed,
211 }
212
213 impl OutboxState {
214 pub(crate) fn as_str(self) -> &'static str {
215 match self {
216 OutboxState::Sending => "sending",
217 OutboxState::Failed => "failed",
218 }
219 }
220
221 pub(crate) fn parse(value: &str) -> Option<Self> {
222 match value {
223 "sending" => Some(OutboxState::Sending),
224 "failed" => Some(OutboxState::Failed),
225 _ => None,
226 }
227 }
228 }
229
230 #[derive(Debug, Clone, PartialEq, Eq)]
231 pub struct OutboxRecord {
232 pub id: String,
233 pub conversation_id: String,
234 pub target: OutboxTarget,
235 pub thread_root_id: Option<String>,
236 pub payload: String,
237 pub images: Vec<AttachmentImage>,
238 pub state: OutboxState,
239 pub last_error: Option<String>,
240 pub created_at: DateTime<Utc>,
241 }
242
243 #[derive(Debug, Clone, PartialEq, Eq)]
244 pub struct DraftRecord {
245 pub conversation_id: String,
246 pub payload: String,
247 pub preview: String,
248 pub images: Vec<AttachmentImage>,
249 pub updated_at: DateTime<Utc>,
250 }
@@ -168,3 +168,83 @@ pub struct ActivityRecord {
168 pub updated_at: DateTime<Utc>,
168 pub updated_at: DateTime<Utc>,
169 pub read: bool,
169 pub read: bool,
170}
170}
171
172#[derive(Debug, Clone, PartialEq, Eq)]
173pub struct AttachmentImage {
174 pub name: String,
175 pub format: String,
176 pub bytes: Vec<u8>,
177 pub width: Option<u32>,
178 pub height: Option<u32>,
179}
180
181#[derive(Debug, Clone, Copy, PartialEq, Eq)]
182pub enum OutboxTarget {
183 Flat,
184 Post,
185 Thread,
186}
187
188impl OutboxTarget {
189 pub(crate) fn as_str(self) -> &'static str {
190 match self {
191 OutboxTarget::Flat => "flat",
192 OutboxTarget::Post => "post",
193 OutboxTarget::Thread => "thread",
194 }
195 }
196
197 pub(crate) fn parse(value: &str) -> Option<Self> {
198 match value {
199 "flat" => Some(OutboxTarget::Flat),
200 "post" => Some(OutboxTarget::Post),
201 "thread" => Some(OutboxTarget::Thread),
202 _ => None,
203 }
204 }
205}
206
207#[derive(Debug, Clone, Copy, PartialEq, Eq)]
208pub enum OutboxState {
209 Sending,
210 Failed,
211}
212
213impl OutboxState {
214 pub(crate) fn as_str(self) -> &'static str {
215 match self {
216 OutboxState::Sending => "sending",
217 OutboxState::Failed => "failed",
218 }
219 }
220
221 pub(crate) fn parse(value: &str) -> Option<Self> {
222 match value {
223 "sending" => Some(OutboxState::Sending),
224 "failed" => Some(OutboxState::Failed),
225 _ => None,
226 }
227 }
228}
229
230#[derive(Debug, Clone, PartialEq, Eq)]
231pub struct OutboxRecord {
232 pub id: String,
233 pub conversation_id: String,
234 pub target: OutboxTarget,
235 pub thread_root_id: Option<String>,
236 pub payload: String,
237 pub images: Vec<AttachmentImage>,
238 pub state: OutboxState,
239 pub last_error: Option<String>,
240 pub created_at: DateTime<Utc>,
241}
242
243#[derive(Debug, Clone, PartialEq, Eq)]
244pub struct DraftRecord {
245 pub conversation_id: String,
246 pub payload: String,
247 pub preview: String,
248 pub images: Vec<AttachmentImage>,
249 pub updated_at: DateTime<Utc>,
250}
crates/store/src/outbox.rs added +120 −0
@@ -0,0 +1,120 @@
1 use rusqlite::{Connection, Row, params, types::Type};
2
3 use crate::attachment_images::{OUTBOX_OWNER, delete_images, load_images, replace_images};
4 use crate::error::Result;
5 use crate::models::{OutboxRecord, OutboxState, OutboxTarget};
6 use crate::store::Store;
7 use crate::time::{from_millis, to_millis};
8
9 const OUTBOX_COLUMNS: &str =
10 "id, conversation_id, target, thread_root_id, payload, state, last_error, created_at";
11
12 impl Store {
13 pub fn put_outbox(&self, record: &OutboxRecord) -> Result<()> {
14 let mut connection = self.lock()?;
15 let transaction = connection.transaction()?;
16 transaction.execute(
17 &format!(
18 "INSERT INTO outbox ({OUTBOX_COLUMNS}) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
19 ON CONFLICT (id) DO UPDATE SET
20 conversation_id = excluded.conversation_id, target = excluded.target,
21 thread_root_id = excluded.thread_root_id, payload = excluded.payload,
22 state = excluded.state, last_error = excluded.last_error,
23 created_at = excluded.created_at"
24 ),
25 params![
26 record.id,
27 record.conversation_id,
28 record.target.as_str(),
29 record.thread_root_id,
30 record.payload,
31 record.state.as_str(),
32 record.last_error,
33 to_millis(record.created_at),
34 ],
35 )?;
36 replace_images(&transaction, OUTBOX_OWNER, &record.id, &record.images)?;
37 Ok(transaction.commit()?)
38 }
39
40 pub fn outbox_for_conversation(&self, conversation_id: &str) -> Result<Vec<OutboxRecord>> {
41 let connection = self.lock()?;
42 let mut statement = connection.prepare_cached(&format!(
43 "SELECT {OUTBOX_COLUMNS} FROM outbox WHERE conversation_id = ?1
44 ORDER BY created_at ASC, id ASC"
45 ))?;
46 let records = statement
47 .query_map([conversation_id], outbox_from_row)?
48 .collect::<rusqlite::Result<Vec<_>>>()?;
49 with_images(&connection, records)
50 }
51
52 pub fn sending_outbox(&self) -> Result<Vec<OutboxRecord>> {
53 let connection = self.lock()?;
54 let mut statement = connection.prepare_cached(&format!(
55 "SELECT {OUTBOX_COLUMNS} FROM outbox WHERE state = ?1 ORDER BY created_at ASC, id ASC"
56 ))?;
57 let records = statement
58 .query_map([OutboxState::Sending.as_str()], outbox_from_row)?
59 .collect::<rusqlite::Result<Vec<_>>>()?;
60 with_images(&connection, records)
61 }
62
63 pub fn failed_outbox_conversations(&self) -> Result<Vec<String>> {
64 let connection = self.lock()?;
65 let mut statement = connection.prepare_cached(
66 "SELECT DISTINCT conversation_id FROM outbox WHERE state = ?1 ORDER BY conversation_id",
67 )?;
68 let ids = statement
69 .query_map([OutboxState::Failed.as_str()], |row| row.get(0))?
70 .collect::<rusqlite::Result<Vec<_>>>()?;
71 Ok(ids)
72 }
73
74 pub fn mark_outbox_failed(&self, id: &str, error: &str) -> Result<()> {
75 let connection = self.lock()?;
76 connection.execute(
77 "UPDATE outbox SET state = ?2, last_error = ?3 WHERE id = ?1",
78 params![id, OutboxState::Failed.as_str(), error],
79 )?;
80 Ok(())
81 }
82
83 pub fn delete_outbox(&self, id: &str) -> Result<()> {
84 let mut connection = self.lock()?;
85 let transaction = connection.transaction()?;
86 transaction.execute("DELETE FROM outbox WHERE id = ?1", [id])?;
87 delete_images(&transaction, OUTBOX_OWNER, id)?;
88 Ok(transaction.commit()?)
89 }
90 }
91
92 fn with_images(connection: &Connection, records: Vec<OutboxRecord>) -> Result<Vec<OutboxRecord>> {
93 records
94 .into_iter()
95 .map(|mut record| {
96 record.images = load_images(connection, OUTBOX_OWNER, &record.id)?;
97 Ok(record)
98 })
99 .collect()
100 }
101
102 fn outbox_from_row(row: &Row<'_>) -> rusqlite::Result<OutboxRecord> {
103 let target: String = row.get(2)?;
104 let state: String = row.get(5)?;
105 Ok(OutboxRecord {
106 id: row.get(0)?,
107 conversation_id: row.get(1)?,
108 target: OutboxTarget::parse(&target).ok_or_else(|| unknown_value(2, "outbox target"))?,
109 thread_root_id: row.get(3)?,
110 payload: row.get(4)?,
111 images: Vec::new(),
112 state: OutboxState::parse(&state).ok_or_else(|| unknown_value(5, "outbox state"))?,
113 last_error: row.get(6)?,
114 created_at: from_millis(row.get(7)?),
115 })
116 }
117
118 fn unknown_value(column: usize, what: &str) -> rusqlite::Error {
119 rusqlite::Error::FromSqlConversionFailure(column, Type::Text, format!("unknown {what}").into())
120 }
@@ -0,0 +1,120 @@
1use rusqlite::{Connection, Row, params, types::Type};
2
3use crate::attachment_images::{OUTBOX_OWNER, delete_images, load_images, replace_images};
4use crate::error::Result;
5use crate::models::{OutboxRecord, OutboxState, OutboxTarget};
6use crate::store::Store;
7use crate::time::{from_millis, to_millis};
8
9const OUTBOX_COLUMNS: &str =
10 "id, conversation_id, target, thread_root_id, payload, state, last_error, created_at";
11
12impl Store {
13 pub fn put_outbox(&self, record: &OutboxRecord) -> Result<()> {
14 let mut connection = self.lock()?;
15 let transaction = connection.transaction()?;
16 transaction.execute(
17 &format!(
18 "INSERT INTO outbox ({OUTBOX_COLUMNS}) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
19 ON CONFLICT (id) DO UPDATE SET
20 conversation_id = excluded.conversation_id, target = excluded.target,
21 thread_root_id = excluded.thread_root_id, payload = excluded.payload,
22 state = excluded.state, last_error = excluded.last_error,
23 created_at = excluded.created_at"
24 ),
25 params![
26 record.id,
27 record.conversation_id,
28 record.target.as_str(),
29 record.thread_root_id,
30 record.payload,
31 record.state.as_str(),
32 record.last_error,
33 to_millis(record.created_at),
34 ],
35 )?;
36 replace_images(&transaction, OUTBOX_OWNER, &record.id, &record.images)?;
37 Ok(transaction.commit()?)
38 }
39
40 pub fn outbox_for_conversation(&self, conversation_id: &str) -> Result<Vec<OutboxRecord>> {
41 let connection = self.lock()?;
42 let mut statement = connection.prepare_cached(&format!(
43 "SELECT {OUTBOX_COLUMNS} FROM outbox WHERE conversation_id = ?1
44 ORDER BY created_at ASC, id ASC"
45 ))?;
46 let records = statement
47 .query_map([conversation_id], outbox_from_row)?
48 .collect::<rusqlite::Result<Vec<_>>>()?;
49 with_images(&connection, records)
50 }
51
52 pub fn sending_outbox(&self) -> Result<Vec<OutboxRecord>> {
53 let connection = self.lock()?;
54 let mut statement = connection.prepare_cached(&format!(
55 "SELECT {OUTBOX_COLUMNS} FROM outbox WHERE state = ?1 ORDER BY created_at ASC, id ASC"
56 ))?;
57 let records = statement
58 .query_map([OutboxState::Sending.as_str()], outbox_from_row)?
59 .collect::<rusqlite::Result<Vec<_>>>()?;
60 with_images(&connection, records)
61 }
62
63 pub fn failed_outbox_conversations(&self) -> Result<Vec<String>> {
64 let connection = self.lock()?;
65 let mut statement = connection.prepare_cached(
66 "SELECT DISTINCT conversation_id FROM outbox WHERE state = ?1 ORDER BY conversation_id",
67 )?;
68 let ids = statement
69 .query_map([OutboxState::Failed.as_str()], |row| row.get(0))?
70 .collect::<rusqlite::Result<Vec<_>>>()?;
71 Ok(ids)
72 }
73
74 pub fn mark_outbox_failed(&self, id: &str, error: &str) -> Result<()> {
75 let connection = self.lock()?;
76 connection.execute(
77 "UPDATE outbox SET state = ?2, last_error = ?3 WHERE id = ?1",
78 params![id, OutboxState::Failed.as_str(), error],
79 )?;
80 Ok(())
81 }
82
83 pub fn delete_outbox(&self, id: &str) -> Result<()> {
84 let mut connection = self.lock()?;
85 let transaction = connection.transaction()?;
86 transaction.execute("DELETE FROM outbox WHERE id = ?1", [id])?;
87 delete_images(&transaction, OUTBOX_OWNER, id)?;
88 Ok(transaction.commit()?)
89 }
90}
91
92fn with_images(connection: &Connection, records: Vec<OutboxRecord>) -> Result<Vec<OutboxRecord>> {
93 records
94 .into_iter()
95 .map(|mut record| {
96 record.images = load_images(connection, OUTBOX_OWNER, &record.id)?;
97 Ok(record)
98 })
99 .collect()
100}
101
102fn outbox_from_row(row: &Row<'_>) -> rusqlite::Result<OutboxRecord> {
103 let target: String = row.get(2)?;
104 let state: String = row.get(5)?;
105 Ok(OutboxRecord {
106 id: row.get(0)?,
107 conversation_id: row.get(1)?,
108 target: OutboxTarget::parse(&target).ok_or_else(|| unknown_value(2, "outbox target"))?,
109 thread_root_id: row.get(3)?,
110 payload: row.get(4)?,
111 images: Vec::new(),
112 state: OutboxState::parse(&state).ok_or_else(|| unknown_value(5, "outbox state"))?,
113 last_error: row.get(6)?,
114 created_at: from_millis(row.get(7)?),
115 })
116}
117
118fn unknown_value(column: usize, what: &str) -> rusqlite::Error {
119 rusqlite::Error::FromSqlConversionFailure(column, Type::Text, format!("unknown {what}").into())
120}
crates/store/tests/outbox_drafts.rs added +153 −0
@@ -0,0 +1,153 @@
1 use chrono::{DateTime, TimeZone, Utc};
2 use store::{AttachmentImage, DraftRecord, OutboxRecord, OutboxState, OutboxTarget, Store};
3
4 fn at(second: u32) -> DateTime<Utc> {
5 Utc.with_ymd_and_hms(2026, 10, 6, 9, 0, second).unwrap()
6 }
7
8 fn image(name: &str) -> AttachmentImage {
9 AttachmentImage {
10 name: name.to_owned(),
11 format: "image/png".to_owned(),
12 bytes: vec![1, 2, 3, 4],
13 width: Some(10),
14 height: None,
15 }
16 }
17
18 fn outbox(id: &str, conversation_id: &str, second: u32) -> OutboxRecord {
19 OutboxRecord {
20 id: id.to_owned(),
21 conversation_id: conversation_id.to_owned(),
22 target: OutboxTarget::Flat,
23 thread_root_id: None,
24 payload: format!("{{\"id\":\"{id}\"}}"),
25 images: vec![image("a.png"), image("b.png")],
26 state: OutboxState::Sending,
27 last_error: None,
28 created_at: at(second),
29 }
30 }
31
32 fn draft(conversation_id: &str, preview: &str) -> DraftRecord {
33 DraftRecord {
34 conversation_id: conversation_id.to_owned(),
35 payload: "{}".to_owned(),
36 preview: preview.to_owned(),
37 images: vec![image("pasted.png")],
38 updated_at: at(1),
39 }
40 }
41
42 #[test]
43 fn outbox_rows_round_trip_with_images_oldest_first() {
44 let store = Store::open_in_memory().unwrap();
45 let mut thread = outbox("late", "chat-1", 30);
46 thread.target = OutboxTarget::Thread;
47 thread.thread_root_id = Some("root-1".to_owned());
48 store.put_outbox(&thread).unwrap();
49 store.put_outbox(&outbox("early", "chat-1", 10)).unwrap();
50 store.put_outbox(&outbox("other", "chat-2", 20)).unwrap();
51 let rows = store.outbox_for_conversation("chat-1").unwrap();
52 assert_eq!(rows, vec![outbox("early", "chat-1", 10), thread]);
53 }
54
55 #[test]
56 fn failed_rows_leave_the_sending_list_and_keep_their_error() {
57 let store = Store::open_in_memory().unwrap();
58 store.put_outbox(&outbox("a", "chat-1", 10)).unwrap();
59 store.put_outbox(&outbox("b", "chat-2", 20)).unwrap();
60 store.mark_outbox_failed("a", "HTTP 403").unwrap();
61 let sending = store.sending_outbox().unwrap();
62 assert_eq!(sending.len(), 1);
63 assert_eq!(sending[0].id, "b");
64 let failed = store.outbox_for_conversation("chat-1").unwrap();
65 assert_eq!(failed[0].state, OutboxState::Failed);
66 assert_eq!(failed[0].last_error.as_deref(), Some("HTTP 403"));
67 assert_eq!(store.failed_outbox_conversations().unwrap(), vec!["chat-1"]);
68 }
69
70 #[test]
71 fn putting_a_failed_row_again_makes_it_a_fresh_attempt() {
72 let store = Store::open_in_memory().unwrap();
73 store.put_outbox(&outbox("a", "chat-1", 10)).unwrap();
74 store.mark_outbox_failed("a", "boom").unwrap();
75 store.put_outbox(&outbox("a", "chat-1", 40)).unwrap();
76 let rows = store.outbox_for_conversation("chat-1").unwrap();
77 assert_eq!(rows, vec![outbox("a", "chat-1", 40)]);
78 assert!(store.failed_outbox_conversations().unwrap().is_empty());
79 }
80
81 #[test]
82 fn deleting_an_outbox_row_removes_its_images() {
83 let store = Store::open_in_memory().unwrap();
84 store.put_outbox(&outbox("a", "chat-1", 10)).unwrap();
85 store.delete_outbox("a").unwrap();
86 assert!(store.outbox_for_conversation("chat-1").unwrap().is_empty());
87 store.put_outbox(&outbox("a", "chat-1", 10)).unwrap();
88 assert_eq!(
89 store.outbox_for_conversation("chat-1").unwrap()[0]
90 .images
91 .len(),
92 2
93 );
94 }
95
96 #[test]
97 fn drafts_save_load_replace_and_delete() {
98 let store = Store::open_in_memory().unwrap();
99 assert_eq!(store.draft("chat-1").unwrap(), None);
100 store.save_draft(&draft("chat-1", "first")).unwrap();
101 store.save_draft(&draft("chat-2", "other")).unwrap();
102 let mut changed = draft("chat-1", "second");
103 changed.images.clear();
104 store.save_draft(&changed).unwrap();
105 assert_eq!(store.draft("chat-1").unwrap(), Some(changed));
106 assert_eq!(
107 store.draft("chat-2").unwrap(),
108 Some(draft("chat-2", "other"))
109 );
110 store.delete_draft("chat-1").unwrap();
111 assert_eq!(store.draft("chat-1").unwrap(), None);
112 }
113
114 #[test]
115 fn draft_previews_map_conversations_to_plain_text() {
116 let store = Store::open_in_memory().unwrap();
117 store.save_draft(&draft("chat-1", "hello")).unwrap();
118 store.save_draft(&draft("chat-2", "world")).unwrap();
119 let previews = store.draft_previews().unwrap();
120 assert_eq!(previews.len(), 2);
121 assert_eq!(previews["chat-1"], "hello");
122 assert_eq!(previews["chat-2"], "world");
123 }
124
125 #[test]
126 fn draft_and_outbox_images_do_not_collide_on_the_same_id() {
127 let store = Store::open_in_memory().unwrap();
128 store.put_outbox(&outbox("same", "chat-1", 10)).unwrap();
129 store.save_draft(&draft("same", "text")).unwrap();
130 store.delete_draft("same").unwrap();
131 assert_eq!(
132 store.outbox_for_conversation("chat-1").unwrap()[0]
133 .images
134 .len(),
135 2
136 );
137 }
138
139 #[test]
140 fn saving_only_the_draft_text_keeps_the_stored_images() {
141 let store = Store::open_in_memory().unwrap();
142 store.save_draft(&draft("chat-1", "first")).unwrap();
143 let mut edited = draft("chat-1", "second");
144 edited.payload = "{\"lines\":[]}".to_owned();
145 edited.images.clear();
146 edited.updated_at = at(9);
147 store.save_draft_text(&edited).unwrap();
148 let loaded = store.draft("chat-1").unwrap().unwrap();
149 assert_eq!(loaded.preview, "second");
150 assert_eq!(loaded.payload, "{\"lines\":[]}");
151 assert_eq!(loaded.updated_at, at(9));
152 assert_eq!(loaded.images, vec![image("pasted.png")]);
153 }
@@ -0,0 +1,153 @@
1use chrono::{DateTime, TimeZone, Utc};
2use store::{AttachmentImage, DraftRecord, OutboxRecord, OutboxState, OutboxTarget, Store};
3
4fn at(second: u32) -> DateTime<Utc> {
5 Utc.with_ymd_and_hms(2026, 10, 6, 9, 0, second).unwrap()
6}
7
8fn image(name: &str) -> AttachmentImage {
9 AttachmentImage {
10 name: name.to_owned(),
11 format: "image/png".to_owned(),
12 bytes: vec![1, 2, 3, 4],
13 width: Some(10),
14 height: None,
15 }
16}
17
18fn outbox(id: &str, conversation_id: &str, second: u32) -> OutboxRecord {
19 OutboxRecord {
20 id: id.to_owned(),
21 conversation_id: conversation_id.to_owned(),
22 target: OutboxTarget::Flat,
23 thread_root_id: None,
24 payload: format!("{{\"id\":\"{id}\"}}"),
25 images: vec![image("a.png"), image("b.png")],
26 state: OutboxState::Sending,
27 last_error: None,
28 created_at: at(second),
29 }
30}
31
32fn draft(conversation_id: &str, preview: &str) -> DraftRecord {
33 DraftRecord {
34 conversation_id: conversation_id.to_owned(),
35 payload: "{}".to_owned(),
36 preview: preview.to_owned(),
37 images: vec![image("pasted.png")],
38 updated_at: at(1),
39 }
40}
41
42#[test]
43fn outbox_rows_round_trip_with_images_oldest_first() {
44 let store = Store::open_in_memory().unwrap();
45 let mut thread = outbox("late", "chat-1", 30);
46 thread.target = OutboxTarget::Thread;
47 thread.thread_root_id = Some("root-1".to_owned());
48 store.put_outbox(&thread).unwrap();
49 store.put_outbox(&outbox("early", "chat-1", 10)).unwrap();
50 store.put_outbox(&outbox("other", "chat-2", 20)).unwrap();
51 let rows = store.outbox_for_conversation("chat-1").unwrap();
52 assert_eq!(rows, vec![outbox("early", "chat-1", 10), thread]);
53}
54
55#[test]
56fn failed_rows_leave_the_sending_list_and_keep_their_error() {
57 let store = Store::open_in_memory().unwrap();
58 store.put_outbox(&outbox("a", "chat-1", 10)).unwrap();
59 store.put_outbox(&outbox("b", "chat-2", 20)).unwrap();
60 store.mark_outbox_failed("a", "HTTP 403").unwrap();
61 let sending = store.sending_outbox().unwrap();
62 assert_eq!(sending.len(), 1);
63 assert_eq!(sending[0].id, "b");
64 let failed = store.outbox_for_conversation("chat-1").unwrap();
65 assert_eq!(failed[0].state, OutboxState::Failed);
66 assert_eq!(failed[0].last_error.as_deref(), Some("HTTP 403"));
67 assert_eq!(store.failed_outbox_conversations().unwrap(), vec!["chat-1"]);
68}
69
70#[test]
71fn putting_a_failed_row_again_makes_it_a_fresh_attempt() {
72 let store = Store::open_in_memory().unwrap();
73 store.put_outbox(&outbox("a", "chat-1", 10)).unwrap();
74 store.mark_outbox_failed("a", "boom").unwrap();
75 store.put_outbox(&outbox("a", "chat-1", 40)).unwrap();
76 let rows = store.outbox_for_conversation("chat-1").unwrap();
77 assert_eq!(rows, vec![outbox("a", "chat-1", 40)]);
78 assert!(store.failed_outbox_conversations().unwrap().is_empty());
79}
80
81#[test]
82fn deleting_an_outbox_row_removes_its_images() {
83 let store = Store::open_in_memory().unwrap();
84 store.put_outbox(&outbox("a", "chat-1", 10)).unwrap();
85 store.delete_outbox("a").unwrap();
86 assert!(store.outbox_for_conversation("chat-1").unwrap().is_empty());
87 store.put_outbox(&outbox("a", "chat-1", 10)).unwrap();
88 assert_eq!(
89 store.outbox_for_conversation("chat-1").unwrap()[0]
90 .images
91 .len(),
92 2
93 );
94}
95
96#[test]
97fn drafts_save_load_replace_and_delete() {
98 let store = Store::open_in_memory().unwrap();
99 assert_eq!(store.draft("chat-1").unwrap(), None);
100 store.save_draft(&draft("chat-1", "first")).unwrap();
101 store.save_draft(&draft("chat-2", "other")).unwrap();
102 let mut changed = draft("chat-1", "second");
103 changed.images.clear();
104 store.save_draft(&changed).unwrap();
105 assert_eq!(store.draft("chat-1").unwrap(), Some(changed));
106 assert_eq!(
107 store.draft("chat-2").unwrap(),
108 Some(draft("chat-2", "other"))
109 );
110 store.delete_draft("chat-1").unwrap();
111 assert_eq!(store.draft("chat-1").unwrap(), None);
112}
113
114#[test]
115fn draft_previews_map_conversations_to_plain_text() {
116 let store = Store::open_in_memory().unwrap();
117 store.save_draft(&draft("chat-1", "hello")).unwrap();
118 store.save_draft(&draft("chat-2", "world")).unwrap();
119 let previews = store.draft_previews().unwrap();
120 assert_eq!(previews.len(), 2);
121 assert_eq!(previews["chat-1"], "hello");
122 assert_eq!(previews["chat-2"], "world");
123}
124
125#[test]
126fn draft_and_outbox_images_do_not_collide_on_the_same_id() {
127 let store = Store::open_in_memory().unwrap();
128 store.put_outbox(&outbox("same", "chat-1", 10)).unwrap();
129 store.save_draft(&draft("same", "text")).unwrap();
130 store.delete_draft("same").unwrap();
131 assert_eq!(
132 store.outbox_for_conversation("chat-1").unwrap()[0]
133 .images
134 .len(),
135 2
136 );
137}
138
139#[test]
140fn saving_only_the_draft_text_keeps_the_stored_images() {
141 let store = Store::open_in_memory().unwrap();
142 store.save_draft(&draft("chat-1", "first")).unwrap();
143 let mut edited = draft("chat-1", "second");
144 edited.payload = "{\"lines\":[]}".to_owned();
145 edited.images.clear();
146 edited.updated_at = at(9);
147 store.save_draft_text(&edited).unwrap();
148 let loaded = store.draft("chat-1").unwrap().unwrap();
149 assert_eq!(loaded.preview, "second");
150 assert_eq!(loaded.payload, "{\"lines\":[]}");
151 assert_eq!(loaded.updated_at, at(9));
152 assert_eq!(loaded.images, vec![image("pasted.png")]);
153}
crates/store/tests/store.rs +6 −6
@@ -430,11 +430,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {
430 430 let path = directory.path().join("nested").join("cache.sqlite3");
431 431 {
432 432 let store = Store::open(&path).unwrap();
433 assert_eq!(store.schema_version().unwrap(), 11);
433 assert_eq!(store.schema_version().unwrap(), 12);
434 434 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
435 435 }
436 436 let reopened = Store::open(&path).unwrap();
437 assert_eq!(reopened.schema_version().unwrap(), 11);
437 assert_eq!(reopened.schema_version().unwrap(), 12);
438 438 assert_eq!(reopened.message_count("c").unwrap(), 1);
439 439 drop(reopened);
440 440 let mode: String = rusqlite_open(&path)
@@ -463,10 +463,10 @@ fn old_schema_is_upgraded_in_place() {
463 463 let path = directory.path().join("cache.sqlite3");
464 464 drop(Store::open(&path).unwrap());
465 465 let connection = rusqlite_open(&path);
466 connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity; PRAGMA user_version = 0").unwrap();
466 connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; PRAGMA user_version = 0").unwrap();
467 467 drop(connection);
468 468 let store = Store::open(&path).unwrap();
469 assert_eq!(store.schema_version().unwrap(), 11);
469 assert_eq!(store.schema_version().unwrap(), 12);
470 470 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
471 471 }
472 472
@@ -532,7 +532,7 @@ fn migration_to_v2_keeps_existing_sync_state() {
532 532 let store = Store::open(&path).unwrap();
533 533 let state = store.sync_state("c").unwrap().unwrap();
534 534 assert_eq!(state.delta_link, None);
535 assert_eq!(store.schema_version().unwrap(), 11);
535 assert_eq!(store.schema_version().unwrap(), 12);
536 536 }
537 537
538 538 #[test]
@@ -762,7 +762,7 @@ fn migration_indexes_rows_that_predate_search() {
762 762 "DROP TRIGGER chats_title_insert; DROP TRIGGER chats_title_update; DROP TRIGGER chats_title_delete;
763 763 DROP TRIGGER channels_title_insert; DROP TRIGGER channels_title_update; DROP TRIGGER channels_title_delete;
764 764 DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search;
765 DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity;
765 DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images;
766 766 DROP INDEX messages_by_sender; DROP INDEX chat_members_by_user;
767 767 ALTER TABLE messages DROP COLUMN sender_application_id;
768 768 ALTER TABLE messages DROP COLUMN links_json;
@@ -430,11 +430,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {
430 let path = directory.path().join("nested").join("cache.sqlite3");
430 let path = directory.path().join("nested").join("cache.sqlite3");
431 {
431 {
432 let store = Store::open(&path).unwrap();
432 let store = Store::open(&path).unwrap();
433 assert_eq!(store.schema_version().unwrap(), 11);
433 assert_eq!(store.schema_version().unwrap(), 12);
434 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
434 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
435 }
435 }
436 let reopened = Store::open(&path).unwrap();
436 let reopened = Store::open(&path).unwrap();
437 assert_eq!(reopened.schema_version().unwrap(), 11);
437 assert_eq!(reopened.schema_version().unwrap(), 12);
438 assert_eq!(reopened.message_count("c").unwrap(), 1);
438 assert_eq!(reopened.message_count("c").unwrap(), 1);
439 drop(reopened);
439 drop(reopened);
440 let mode: String = rusqlite_open(&path)
440 let mode: String = rusqlite_open(&path)
@@ -463,10 +463,10 @@ fn old_schema_is_upgraded_in_place() {
463 let path = directory.path().join("cache.sqlite3");
463 let path = directory.path().join("cache.sqlite3");
464 drop(Store::open(&path).unwrap());
464 drop(Store::open(&path).unwrap());
465 let connection = rusqlite_open(&path);
465 let connection = rusqlite_open(&path);
466 connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity; PRAGMA user_version = 0").unwrap();
466 connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; PRAGMA user_version = 0").unwrap();
467 drop(connection);
467 drop(connection);
468 let store = Store::open(&path).unwrap();
468 let store = Store::open(&path).unwrap();
469 assert_eq!(store.schema_version().unwrap(), 11);
469 assert_eq!(store.schema_version().unwrap(), 12);
470 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
470 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
471}
471}
472
472
@@ -532,7 +532,7 @@ fn migration_to_v2_keeps_existing_sync_state() {
532 let store = Store::open(&path).unwrap();
532 let store = Store::open(&path).unwrap();
533 let state = store.sync_state("c").unwrap().unwrap();
533 let state = store.sync_state("c").unwrap().unwrap();
534 assert_eq!(state.delta_link, None);
534 assert_eq!(state.delta_link, None);
535 assert_eq!(store.schema_version().unwrap(), 11);
535 assert_eq!(store.schema_version().unwrap(), 12);
536}
536}
537
537
538#[test]
538#[test]
@@ -762,7 +762,7 @@ fn migration_indexes_rows_that_predate_search() {
762 "DROP TRIGGER chats_title_insert; DROP TRIGGER chats_title_update; DROP TRIGGER chats_title_delete;
762 "DROP TRIGGER chats_title_insert; DROP TRIGGER chats_title_update; DROP TRIGGER chats_title_delete;
763 DROP TRIGGER channels_title_insert; DROP TRIGGER channels_title_update; DROP TRIGGER channels_title_delete;
763 DROP TRIGGER channels_title_insert; DROP TRIGGER channels_title_update; DROP TRIGGER channels_title_delete;
764 DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search;
764 DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search;
765 DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity;
765 DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images;
766 DROP INDEX messages_by_sender; DROP INDEX chat_members_by_user;
766 DROP INDEX messages_by_sender; DROP INDEX chat_members_by_user;
767 ALTER TABLE messages DROP COLUMN sender_application_id;
767 ALTER TABLE messages DROP COLUMN sender_application_id;
768 ALTER TABLE messages DROP COLUMN links_json;
768 ALTER TABLE messages DROP COLUMN links_json;