1use super::{Client, Status, TypedEnvelope, proto};
2use anyhow::{Context as _, Result};
3use chrono::{DateTime, Utc};
4use cloud_api_client::websocket_protocol::MessageToClient;
5use cloud_api_client::{GetAuthenticatedUserResponse, PlanInfo};
6use cloud_llm_client::{
7 EDIT_PREDICTIONS_USAGE_AMOUNT_HEADER_NAME, EDIT_PREDICTIONS_USAGE_LIMIT_HEADER_NAME,
8 MODEL_REQUESTS_USAGE_AMOUNT_HEADER_NAME, MODEL_REQUESTS_USAGE_LIMIT_HEADER_NAME, UsageLimit,
9};
10use collections::{HashMap, HashSet, hash_map::Entry};
11use derive_more::Deref;
12use feature_flags::FeatureFlagAppExt;
13use futures::{Future, StreamExt, channel::mpsc};
14use gpui::{
15 App, AsyncApp, Context, Entity, EventEmitter, SharedString, SharedUri, Task, WeakEntity,
16};
17use http_client::http::{HeaderMap, HeaderValue};
18use postage::{sink::Sink, watch};
19use rpc::proto::{RequestMessage, UsersResponse};
20use std::{
21 str::FromStr as _,
22 sync::{Arc, Weak},
23};
24use text::ReplicaId;
25use util::{ResultExt, TryFutureExt as _};
26
27pub type UserId = u64;
28
29#[derive(
30 Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, serde::Serialize, serde::Deserialize,
31)]
32pub struct ChannelId(pub u64);
33
34impl std::fmt::Display for ChannelId {
35 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36 self.0.fmt(f)
37 }
38}
39
40#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
41pub struct ProjectId(pub u64);
42
43impl ProjectId {
44 pub fn to_proto(self) -> u64 {
45 self.0
46 }
47}
48
49#[derive(
50 Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, serde::Serialize, serde::Deserialize,
51)]
52pub struct DevServerProjectId(pub u64);
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub struct ParticipantIndex(pub u32);
56
57#[derive(Default, Debug)]
58pub struct User {
59 pub id: UserId,
60 pub github_login: SharedString,
61 pub avatar_uri: SharedUri,
62 pub name: Option<String>,
63}
64
65#[derive(Clone, Debug, PartialEq, Eq)]
66pub struct Collaborator {
67 pub peer_id: proto::PeerId,
68 pub replica_id: ReplicaId,
69 pub user_id: UserId,
70 pub is_host: bool,
71 pub committer_name: Option<String>,
72 pub committer_email: Option<String>,
73}
74
75impl PartialOrd for User {
76 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
77 Some(self.cmp(other))
78 }
79}
80
81impl Ord for User {
82 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
83 self.github_login.cmp(&other.github_login)
84 }
85}
86
87impl PartialEq for User {
88 fn eq(&self, other: &Self) -> bool {
89 self.id == other.id && self.github_login == other.github_login
90 }
91}
92
93impl Eq for User {}
94
95#[derive(Debug, PartialEq)]
96pub struct Contact {
97 pub user: Arc<User>,
98 pub online: bool,
99 pub busy: bool,
100}
101
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub enum ContactRequestStatus {
104 None,
105 RequestSent,
106 RequestReceived,
107 RequestAccepted,
108}
109
110pub struct UserStore {
111 users: HashMap<u64, Arc<User>>,
112 by_github_login: HashMap<SharedString, u64>,
113 participant_indices: HashMap<u64, ParticipantIndex>,
114 update_contacts_tx: mpsc::UnboundedSender<UpdateContacts>,
115 model_request_usage: Option<ModelRequestUsage>,
116 edit_prediction_usage: Option<EditPredictionUsage>,
117 plan_info: Option<PlanInfo>,
118 current_user: watch::Receiver<Option<Arc<User>>>,
119 contacts: Vec<Arc<Contact>>,
120 incoming_contact_requests: Vec<Arc<User>>,
121 outgoing_contact_requests: Vec<Arc<User>>,
122 pending_contact_requests: HashMap<u64, usize>,
123 invite_info: Option<InviteInfo>,
124 client: Weak<Client>,
125 _maintain_contacts: Task<()>,
126 _maintain_current_user: Task<Result<()>>,
127 weak_self: WeakEntity<Self>,
128}
129
130#[derive(Clone)]
131pub struct InviteInfo {
132 pub count: u32,
133 pub url: Arc<str>,
134}
135
136pub enum Event {
137 Contact {
138 user: Arc<User>,
139 kind: ContactEventKind,
140 },
141 ShowContacts,
142 ParticipantIndicesChanged,
143 PrivateUserInfoUpdated,
144 PlanUpdated,
145}
146
147#[derive(Clone, Copy)]
148pub enum ContactEventKind {
149 Requested,
150 Accepted,
151 Cancelled,
152}
153
154impl EventEmitter<Event> for UserStore {}
155
156enum UpdateContacts {
157 Update(proto::UpdateContacts),
158 Wait(postage::barrier::Sender),
159 Clear(postage::barrier::Sender),
160}
161
162#[derive(Debug, Clone, Copy, Deref)]
163pub struct ModelRequestUsage(pub RequestUsage);
164
165#[derive(Debug, Clone, Copy, Deref)]
166pub struct EditPredictionUsage(pub RequestUsage);
167
168#[derive(Debug, Clone, Copy)]
169pub struct RequestUsage {
170 pub limit: UsageLimit,
171 pub amount: i32,
172}
173
174impl UserStore {
175 pub fn new(client: Arc<Client>, cx: &Context<Self>) -> Self {
176 let (mut current_user_tx, current_user_rx) = watch::channel();
177 let (update_contacts_tx, mut update_contacts_rx) = mpsc::unbounded();
178 let rpc_subscriptions = vec![
179 client.add_message_handler(cx.weak_entity(), Self::handle_update_contacts),
180 client.add_message_handler(cx.weak_entity(), Self::handle_update_invite_info),
181 client.add_message_handler(cx.weak_entity(), Self::handle_show_contacts),
182 ];
183
184 client.add_message_to_client_handler({
185 let this = cx.weak_entity();
186 move |message, cx| Self::handle_message_to_client(this.clone(), message, cx)
187 });
188
189 Self {
190 users: Default::default(),
191 by_github_login: Default::default(),
192 current_user: current_user_rx,
193 plan_info: None,
194 model_request_usage: None,
195 edit_prediction_usage: None,
196 contacts: Default::default(),
197 incoming_contact_requests: Default::default(),
198 participant_indices: Default::default(),
199 outgoing_contact_requests: Default::default(),
200 invite_info: None,
201 client: Arc::downgrade(&client),
202 update_contacts_tx,
203 _maintain_contacts: cx.spawn(async move |this, cx| {
204 let _subscriptions = rpc_subscriptions;
205 while let Some(message) = update_contacts_rx.next().await {
206 if let Ok(task) = this.update(cx, |this, cx| this.update_contacts(message, cx))
207 {
208 task.log_err().await;
209 } else {
210 break;
211 }
212 }
213 }),
214 _maintain_current_user: cx.spawn(async move |this, cx| {
215 let mut status = client.status();
216 let weak = Arc::downgrade(&client);
217 drop(client);
218 while let Some(status) = status.next().await {
219 // if the client is dropped, the app is shutting down.
220 let Some(client) = weak.upgrade() else {
221 return Ok(());
222 };
223 match status {
224 Status::Authenticated | Status::Connected { .. } => {
225 if let Some(user_id) = client.user_id() {
226 let response = client
227 .cloud_client()
228 .get_authenticated_user()
229 .await
230 .log_err();
231
232 let current_user_and_response = if let Some(response) = response {
233 let user = Arc::new(User {
234 id: user_id,
235 github_login: response.user.github_login.clone().into(),
236 avatar_uri: response.user.avatar_url.clone().into(),
237 name: response.user.name.clone(),
238 });
239
240 Some((user, response))
241 } else {
242 None
243 };
244 current_user_tx
245 .send(
246 current_user_and_response
247 .as_ref()
248 .map(|(user, _)| user.clone()),
249 )
250 .await
251 .ok();
252
253 cx.update(|cx| {
254 if let Some((user, response)) = current_user_and_response {
255 this.update(cx, |this, cx| {
256 this.by_github_login
257 .insert(user.github_login.clone(), user_id);
258 this.users.insert(user_id, user);
259 this.update_authenticated_user(response, cx)
260 })
261 } else {
262 anyhow::Ok(())
263 }
264 })??;
265
266 this.update(cx, |_, cx| cx.notify())?;
267 }
268 }
269 Status::SignedOut => {
270 current_user_tx.send(None).await.ok();
271 this.update(cx, |this, cx| {
272 cx.emit(Event::PrivateUserInfoUpdated);
273 cx.notify();
274 this.clear_contacts()
275 })?
276 .await;
277 }
278 Status::ConnectionLost => {
279 this.update(cx, |this, cx| {
280 cx.notify();
281 this.clear_contacts()
282 })?
283 .await;
284 }
285 _ => {}
286 }
287 }
288 Ok(())
289 }),
290 pending_contact_requests: Default::default(),
291 weak_self: cx.weak_entity(),
292 }
293 }
294
295 #[cfg(feature = "test-support")]
296 pub fn clear_cache(&mut self) {
297 self.users.clear();
298 self.by_github_login.clear();
299 }
300
301 async fn handle_update_invite_info(
302 this: Entity<Self>,
303 message: TypedEnvelope<proto::UpdateInviteInfo>,
304 mut cx: AsyncApp,
305 ) -> Result<()> {
306 this.update(&mut cx, |this, cx| {
307 this.invite_info = Some(InviteInfo {
308 url: Arc::from(message.payload.url),
309 count: message.payload.count,
310 });
311 cx.notify();
312 })?;
313 Ok(())
314 }
315
316 async fn handle_show_contacts(
317 this: Entity<Self>,
318 _: TypedEnvelope<proto::ShowContacts>,
319 mut cx: AsyncApp,
320 ) -> Result<()> {
321 this.update(&mut cx, |_, cx| cx.emit(Event::ShowContacts))?;
322 Ok(())
323 }
324
325 pub fn invite_info(&self) -> Option<&InviteInfo> {
326 self.invite_info.as_ref()
327 }
328
329 async fn handle_update_contacts(
330 this: Entity<Self>,
331 message: TypedEnvelope<proto::UpdateContacts>,
332 cx: AsyncApp,
333 ) -> Result<()> {
334 this.read_with(&cx, |this, _| {
335 this.update_contacts_tx
336 .unbounded_send(UpdateContacts::Update(message.payload))
337 .unwrap();
338 })?;
339 Ok(())
340 }
341
342 fn update_contacts(&mut self, message: UpdateContacts, cx: &Context<Self>) -> Task<Result<()>> {
343 match message {
344 UpdateContacts::Wait(barrier) => {
345 drop(barrier);
346 Task::ready(Ok(()))
347 }
348 UpdateContacts::Clear(barrier) => {
349 self.contacts.clear();
350 self.incoming_contact_requests.clear();
351 self.outgoing_contact_requests.clear();
352 drop(barrier);
353 Task::ready(Ok(()))
354 }
355 UpdateContacts::Update(message) => {
356 let mut user_ids = HashSet::default();
357 for contact in &message.contacts {
358 user_ids.insert(contact.user_id);
359 }
360 user_ids.extend(message.incoming_requests.iter().map(|req| req.requester_id));
361 user_ids.extend(message.outgoing_requests.iter());
362
363 let load_users = self.get_users(user_ids.into_iter().collect(), cx);
364 cx.spawn(async move |this, cx| {
365 load_users.await?;
366
367 // Users are fetched in parallel above and cached in call to get_users
368 // No need to parallelize here
369 let mut updated_contacts = Vec::new();
370 let this = this.upgrade().context("can't upgrade user store handle")?;
371 for contact in message.contacts {
372 updated_contacts
373 .push(Arc::new(Contact::from_proto(contact, &this, cx).await?));
374 }
375
376 let mut incoming_requests = Vec::new();
377 for request in message.incoming_requests {
378 incoming_requests.push({
379 this.update(cx, |this, cx| this.get_user(request.requester_id, cx))?
380 .await?
381 });
382 }
383
384 let mut outgoing_requests = Vec::new();
385 for requested_user_id in message.outgoing_requests {
386 outgoing_requests.push(
387 this.update(cx, |this, cx| this.get_user(requested_user_id, cx))?
388 .await?,
389 );
390 }
391
392 let removed_contacts =
393 HashSet::<u64>::from_iter(message.remove_contacts.iter().copied());
394 let removed_incoming_requests =
395 HashSet::<u64>::from_iter(message.remove_incoming_requests.iter().copied());
396 let removed_outgoing_requests =
397 HashSet::<u64>::from_iter(message.remove_outgoing_requests.iter().copied());
398
399 this.update(cx, |this, cx| {
400 // Remove contacts
401 this.contacts
402 .retain(|contact| !removed_contacts.contains(&contact.user.id));
403 // Update existing contacts and insert new ones
404 for updated_contact in updated_contacts {
405 match this.contacts.binary_search_by_key(
406 &&updated_contact.user.github_login,
407 |contact| &contact.user.github_login,
408 ) {
409 Ok(ix) => this.contacts[ix] = updated_contact,
410 Err(ix) => this.contacts.insert(ix, updated_contact),
411 }
412 }
413
414 // Remove incoming contact requests
415 this.incoming_contact_requests.retain(|user| {
416 if removed_incoming_requests.contains(&user.id) {
417 cx.emit(Event::Contact {
418 user: user.clone(),
419 kind: ContactEventKind::Cancelled,
420 });
421 false
422 } else {
423 true
424 }
425 });
426 // Update existing incoming requests and insert new ones
427 for user in incoming_requests {
428 match this
429 .incoming_contact_requests
430 .binary_search_by_key(&&user.github_login, |contact| {
431 &contact.github_login
432 }) {
433 Ok(ix) => this.incoming_contact_requests[ix] = user,
434 Err(ix) => this.incoming_contact_requests.insert(ix, user),
435 }
436 }
437
438 // Remove outgoing contact requests
439 this.outgoing_contact_requests
440 .retain(|user| !removed_outgoing_requests.contains(&user.id));
441 // Update existing incoming requests and insert new ones
442 for request in outgoing_requests {
443 match this
444 .outgoing_contact_requests
445 .binary_search_by_key(&&request.github_login, |contact| {
446 &contact.github_login
447 }) {
448 Ok(ix) => this.outgoing_contact_requests[ix] = request,
449 Err(ix) => this.outgoing_contact_requests.insert(ix, request),
450 }
451 }
452
453 cx.notify();
454 })?;
455
456 Ok(())
457 })
458 }
459 }
460 }
461
462 pub fn contacts(&self) -> &[Arc<Contact>] {
463 &self.contacts
464 }
465
466 pub fn has_contact(&self, user: &Arc<User>) -> bool {
467 self.contacts
468 .binary_search_by_key(&&user.github_login, |contact| &contact.user.github_login)
469 .is_ok()
470 }
471
472 pub fn incoming_contact_requests(&self) -> &[Arc<User>] {
473 &self.incoming_contact_requests
474 }
475
476 pub fn outgoing_contact_requests(&self) -> &[Arc<User>] {
477 &self.outgoing_contact_requests
478 }
479
480 pub fn is_contact_request_pending(&self, user: &User) -> bool {
481 self.pending_contact_requests.contains_key(&user.id)
482 }
483
484 pub fn contact_request_status(&self, user: &User) -> ContactRequestStatus {
485 if self
486 .contacts
487 .binary_search_by_key(&&user.github_login, |contact| &contact.user.github_login)
488 .is_ok()
489 {
490 ContactRequestStatus::RequestAccepted
491 } else if self
492 .outgoing_contact_requests
493 .binary_search_by_key(&&user.github_login, |user| &user.github_login)
494 .is_ok()
495 {
496 ContactRequestStatus::RequestSent
497 } else if self
498 .incoming_contact_requests
499 .binary_search_by_key(&&user.github_login, |user| &user.github_login)
500 .is_ok()
501 {
502 ContactRequestStatus::RequestReceived
503 } else {
504 ContactRequestStatus::None
505 }
506 }
507
508 pub fn request_contact(
509 &mut self,
510 responder_id: u64,
511 cx: &mut Context<Self>,
512 ) -> Task<Result<()>> {
513 self.perform_contact_request(responder_id, proto::RequestContact { responder_id }, cx)
514 }
515
516 pub fn remove_contact(&mut self, user_id: u64, cx: &mut Context<Self>) -> Task<Result<()>> {
517 self.perform_contact_request(user_id, proto::RemoveContact { user_id }, cx)
518 }
519
520 pub fn has_incoming_contact_request(&self, user_id: u64) -> bool {
521 self.incoming_contact_requests
522 .iter()
523 .any(|user| user.id == user_id)
524 }
525
526 pub fn respond_to_contact_request(
527 &mut self,
528 requester_id: u64,
529 accept: bool,
530 cx: &mut Context<Self>,
531 ) -> Task<Result<()>> {
532 self.perform_contact_request(
533 requester_id,
534 proto::RespondToContactRequest {
535 requester_id,
536 response: if accept {
537 proto::ContactRequestResponse::Accept
538 } else {
539 proto::ContactRequestResponse::Decline
540 } as i32,
541 },
542 cx,
543 )
544 }
545
546 pub fn dismiss_contact_request(
547 &self,
548 requester_id: u64,
549 cx: &Context<Self>,
550 ) -> Task<Result<()>> {
551 let client = self.client.upgrade();
552 cx.spawn(async move |_, _| {
553 client
554 .context("can't upgrade client reference")?
555 .request(proto::RespondToContactRequest {
556 requester_id,
557 response: proto::ContactRequestResponse::Dismiss as i32,
558 })
559 .await?;
560 Ok(())
561 })
562 }
563
564 fn perform_contact_request<T: RequestMessage>(
565 &mut self,
566 user_id: u64,
567 request: T,
568 cx: &mut Context<Self>,
569 ) -> Task<Result<()>> {
570 let client = self.client.upgrade();
571 *self.pending_contact_requests.entry(user_id).or_insert(0) += 1;
572 cx.notify();
573
574 cx.spawn(async move |this, cx| {
575 let response = client
576 .context("can't upgrade client reference")?
577 .request(request)
578 .await;
579 this.update(cx, |this, cx| {
580 if let Entry::Occupied(mut request_count) =
581 this.pending_contact_requests.entry(user_id)
582 {
583 *request_count.get_mut() -= 1;
584 if *request_count.get() == 0 {
585 request_count.remove();
586 }
587 }
588 cx.notify();
589 })?;
590 response?;
591 Ok(())
592 })
593 }
594
595 pub fn clear_contacts(&self) -> impl Future<Output = ()> + use<> {
596 let (tx, mut rx) = postage::barrier::channel();
597 self.update_contacts_tx
598 .unbounded_send(UpdateContacts::Clear(tx))
599 .unwrap();
600 async move {
601 rx.next().await;
602 }
603 }
604
605 pub fn contact_updates_done(&self) -> impl Future<Output = ()> {
606 let (tx, mut rx) = postage::barrier::channel();
607 self.update_contacts_tx
608 .unbounded_send(UpdateContacts::Wait(tx))
609 .unwrap();
610 async move {
611 rx.next().await;
612 }
613 }
614
615 pub fn get_users(
616 &self,
617 user_ids: Vec<u64>,
618 cx: &Context<Self>,
619 ) -> Task<Result<Vec<Arc<User>>>> {
620 let mut user_ids_to_fetch = user_ids.clone();
621 user_ids_to_fetch.retain(|id| !self.users.contains_key(id));
622
623 cx.spawn(async move |this, cx| {
624 if !user_ids_to_fetch.is_empty() {
625 this.update(cx, |this, cx| {
626 this.load_users(
627 proto::GetUsers {
628 user_ids: user_ids_to_fetch,
629 },
630 cx,
631 )
632 })?
633 .await?;
634 }
635
636 this.read_with(cx, |this, _| {
637 user_ids
638 .iter()
639 .map(|user_id| {
640 this.users
641 .get(user_id)
642 .cloned()
643 .with_context(|| format!("user {user_id} not found"))
644 })
645 .collect()
646 })?
647 })
648 }
649
650 pub fn fuzzy_search_users(
651 &self,
652 query: String,
653 cx: &Context<Self>,
654 ) -> Task<Result<Vec<Arc<User>>>> {
655 self.load_users(proto::FuzzySearchUsers { query }, cx)
656 }
657
658 pub fn get_cached_user(&self, user_id: u64) -> Option<Arc<User>> {
659 self.users.get(&user_id).cloned()
660 }
661
662 pub fn get_user_optimistic(&self, user_id: u64, cx: &Context<Self>) -> Option<Arc<User>> {
663 if let Some(user) = self.users.get(&user_id).cloned() {
664 return Some(user);
665 }
666
667 self.get_user(user_id, cx).detach_and_log_err(cx);
668 None
669 }
670
671 pub fn get_user(&self, user_id: u64, cx: &Context<Self>) -> Task<Result<Arc<User>>> {
672 if let Some(user) = self.users.get(&user_id).cloned() {
673 return Task::ready(Ok(user));
674 }
675
676 let load_users = self.get_users(vec![user_id], cx);
677 cx.spawn(async move |this, cx| {
678 load_users.await?;
679 this.read_with(cx, |this, _| {
680 this.users
681 .get(&user_id)
682 .cloned()
683 .context("server responded with no users")
684 })?
685 })
686 }
687
688 pub fn cached_user_by_github_login(&self, github_login: &str) -> Option<Arc<User>> {
689 self.by_github_login
690 .get(github_login)
691 .and_then(|id| self.users.get(id).cloned())
692 }
693
694 pub fn current_user(&self) -> Option<Arc<User>> {
695 self.current_user.borrow().clone()
696 }
697
698 pub fn plan(&self) -> Option<cloud_llm_client::Plan> {
699 #[cfg(debug_assertions)]
700 if let Ok(plan) = std::env::var("ZED_SIMULATE_PLAN").as_ref() {
701 return match plan.as_str() {
702 "free" => Some(cloud_llm_client::Plan::ZedFree),
703 "trial" => Some(cloud_llm_client::Plan::ZedProTrial),
704 "pro" => Some(cloud_llm_client::Plan::ZedPro),
705 _ => {
706 panic!("ZED_SIMULATE_PLAN must be one of 'free', 'trial', or 'pro'");
707 }
708 };
709 }
710
711 self.plan_info.as_ref().map(|info| info.plan)
712 }
713
714 pub fn subscription_period(&self) -> Option<(DateTime<Utc>, DateTime<Utc>)> {
715 self.plan_info
716 .as_ref()
717 .and_then(|plan| plan.subscription_period)
718 .map(|subscription_period| {
719 (
720 subscription_period.started_at.0,
721 subscription_period.ended_at.0,
722 )
723 })
724 }
725
726 pub fn trial_started_at(&self) -> Option<DateTime<Utc>> {
727 self.plan_info
728 .as_ref()
729 .and_then(|plan| plan.trial_started_at)
730 .map(|trial_started_at| trial_started_at.0)
731 }
732
733 /// Returns whether the user's account is too new to use the service.
734 pub fn account_too_young(&self) -> bool {
735 self.plan_info
736 .as_ref()
737 .map(|plan| plan.is_account_too_young)
738 .unwrap_or_default()
739 }
740
741 /// Returns whether the current user has overdue invoices and usage should be blocked.
742 pub fn has_overdue_invoices(&self) -> bool {
743 self.plan_info
744 .as_ref()
745 .map(|plan| plan.has_overdue_invoices)
746 .unwrap_or_default()
747 }
748
749 pub fn is_usage_based_billing_enabled(&self) -> bool {
750 self.plan_info
751 .as_ref()
752 .map(|plan| plan.is_usage_based_billing_enabled)
753 .unwrap_or_default()
754 }
755
756 pub fn model_request_usage(&self) -> Option<ModelRequestUsage> {
757 self.model_request_usage
758 }
759
760 pub fn update_model_request_usage(&mut self, usage: ModelRequestUsage, cx: &mut Context<Self>) {
761 self.model_request_usage = Some(usage);
762 cx.notify();
763 }
764
765 pub fn edit_prediction_usage(&self) -> Option<EditPredictionUsage> {
766 self.edit_prediction_usage
767 }
768
769 pub fn update_edit_prediction_usage(
770 &mut self,
771 usage: EditPredictionUsage,
772 cx: &mut Context<Self>,
773 ) {
774 self.edit_prediction_usage = Some(usage);
775 cx.notify();
776 }
777
778 fn update_authenticated_user(
779 &mut self,
780 response: GetAuthenticatedUserResponse,
781 cx: &mut Context<Self>,
782 ) {
783 let staff = response.user.is_staff && !*feature_flags::ZED_DISABLE_STAFF;
784 cx.update_flags(staff, response.feature_flags);
785 if let Some(client) = self.client.upgrade() {
786 client
787 .telemetry
788 .set_authenticated_user_info(Some(response.user.metrics_id.clone()), staff);
789 }
790
791 self.model_request_usage = Some(ModelRequestUsage(RequestUsage {
792 limit: response.plan.usage.model_requests.limit,
793 amount: response.plan.usage.model_requests.used as i32,
794 }));
795 self.edit_prediction_usage = Some(EditPredictionUsage(RequestUsage {
796 limit: response.plan.usage.edit_predictions.limit,
797 amount: response.plan.usage.edit_predictions.used as i32,
798 }));
799 self.plan_info = Some(response.plan);
800 cx.emit(Event::PrivateUserInfoUpdated);
801 }
802
803 fn handle_message_to_client(this: WeakEntity<Self>, message: &MessageToClient, cx: &App) {
804 cx.spawn(async move |cx| {
805 match message {
806 MessageToClient::UserUpdated => {
807 let cloud_client = cx
808 .update(|cx| {
809 this.read_with(cx, |this, _cx| {
810 this.client.upgrade().map(|client| client.cloud_client())
811 })
812 })??
813 .ok_or(anyhow::anyhow!("Failed to get Cloud client"))?;
814
815 let response = cloud_client.get_authenticated_user().await?;
816 cx.update(|cx| {
817 this.update(cx, |this, cx| {
818 this.update_authenticated_user(response, cx);
819 })
820 })??;
821 }
822 }
823
824 anyhow::Ok(())
825 })
826 .detach_and_log_err(cx);
827 }
828
829 pub fn watch_current_user(&self) -> watch::Receiver<Option<Arc<User>>> {
830 self.current_user.clone()
831 }
832
833 fn load_users(
834 &self,
835 request: impl RequestMessage<Response = UsersResponse>,
836 cx: &Context<Self>,
837 ) -> Task<Result<Vec<Arc<User>>>> {
838 let client = self.client.clone();
839 cx.spawn(async move |this, cx| {
840 if let Some(rpc) = client.upgrade() {
841 let response = rpc.request(request).await.context("error loading users")?;
842 let users = response.users;
843
844 this.update(cx, |this, _| this.insert(users))
845 } else {
846 Ok(Vec::new())
847 }
848 })
849 }
850
851 pub fn insert(&mut self, users: Vec<proto::User>) -> Vec<Arc<User>> {
852 let mut ret = Vec::with_capacity(users.len());
853 for user in users {
854 let user = User::new(user);
855 if let Some(old) = self.users.insert(user.id, user.clone())
856 && old.github_login != user.github_login
857 {
858 self.by_github_login.remove(&old.github_login);
859 }
860 self.by_github_login
861 .insert(user.github_login.clone(), user.id);
862 ret.push(user)
863 }
864 ret
865 }
866
867 pub fn set_participant_indices(
868 &mut self,
869 participant_indices: HashMap<u64, ParticipantIndex>,
870 cx: &mut Context<Self>,
871 ) {
872 if participant_indices != self.participant_indices {
873 self.participant_indices = participant_indices;
874 cx.emit(Event::ParticipantIndicesChanged);
875 }
876 }
877
878 pub fn participant_indices(&self) -> &HashMap<u64, ParticipantIndex> {
879 &self.participant_indices
880 }
881
882 pub fn participant_names(
883 &self,
884 user_ids: impl Iterator<Item = u64>,
885 cx: &App,
886 ) -> HashMap<u64, SharedString> {
887 let mut ret = HashMap::default();
888 let mut missing_user_ids = Vec::new();
889 for id in user_ids {
890 if let Some(github_login) = self.get_cached_user(id).map(|u| u.github_login.clone()) {
891 ret.insert(id, github_login);
892 } else {
893 missing_user_ids.push(id)
894 }
895 }
896 if !missing_user_ids.is_empty() {
897 let this = self.weak_self.clone();
898 cx.spawn(async move |cx| {
899 this.update(cx, |this, cx| this.get_users(missing_user_ids, cx))?
900 .await
901 })
902 .detach_and_log_err(cx);
903 }
904 ret
905 }
906}
907
908impl User {
909 fn new(message: proto::User) -> Arc<Self> {
910 Arc::new(User {
911 id: message.id,
912 github_login: message.github_login.into(),
913 avatar_uri: message.avatar_url.into(),
914 name: message.name,
915 })
916 }
917}
918
919impl Contact {
920 async fn from_proto(
921 contact: proto::Contact,
922 user_store: &Entity<UserStore>,
923 cx: &mut AsyncApp,
924 ) -> Result<Self> {
925 let user = user_store
926 .update(cx, |user_store, cx| {
927 user_store.get_user(contact.user_id, cx)
928 })?
929 .await?;
930 Ok(Self {
931 user,
932 online: contact.online,
933 busy: contact.busy,
934 })
935 }
936}
937
938impl Collaborator {
939 pub fn from_proto(message: proto::Collaborator) -> Result<Self> {
940 Ok(Self {
941 peer_id: message.peer_id.context("invalid peer id")?,
942 replica_id: message.replica_id as ReplicaId,
943 user_id: message.user_id as UserId,
944 is_host: message.is_host,
945 committer_name: message.committer_name,
946 committer_email: message.committer_email,
947 })
948 }
949}
950
951impl RequestUsage {
952 pub fn over_limit(&self) -> bool {
953 match self.limit {
954 UsageLimit::Limited(limit) => self.amount >= limit,
955 UsageLimit::Unlimited => false,
956 }
957 }
958
959 fn from_headers(
960 limit_name: &str,
961 amount_name: &str,
962 headers: &HeaderMap<HeaderValue>,
963 ) -> Result<Self> {
964 let limit = headers
965 .get(limit_name)
966 .with_context(|| format!("missing {limit_name:?} header"))?;
967 let limit = UsageLimit::from_str(limit.to_str()?)?;
968
969 let amount = headers
970 .get(amount_name)
971 .with_context(|| format!("missing {amount_name:?} header"))?;
972 let amount = amount.to_str()?.parse::<i32>()?;
973
974 Ok(Self { limit, amount })
975 }
976}
977
978impl ModelRequestUsage {
979 pub fn from_headers(headers: &HeaderMap<HeaderValue>) -> Result<Self> {
980 Ok(Self(RequestUsage::from_headers(
981 MODEL_REQUESTS_USAGE_LIMIT_HEADER_NAME,
982 MODEL_REQUESTS_USAGE_AMOUNT_HEADER_NAME,
983 headers,
984 )?))
985 }
986}
987
988impl EditPredictionUsage {
989 pub fn from_headers(headers: &HeaderMap<HeaderValue>) -> Result<Self> {
990 Ok(Self(RequestUsage::from_headers(
991 EDIT_PREDICTIONS_USAGE_LIMIT_HEADER_NAME,
992 EDIT_PREDICTIONS_USAGE_AMOUNT_HEADER_NAME,
993 headers,
994 )?))
995 }
996}