Convert telemetry into a model

Co-Authored-By: Julia <30666851+ForLoveOfCats@users.noreply.github.com>
This commit is contained in:
Joseph T. Lyons 2023-11-21 21:11:17 -05:00
parent a4a1e6ba98
commit 6e4268a471
9 changed files with 208 additions and 199 deletions

View file

@ -302,7 +302,11 @@ impl AutoUpdater {
let mut dmg_file = File::create(&dmg_path).await?; let mut dmg_file = File::create(&dmg_path).await?;
let (installation_id, release_channel, telemetry) = cx.update(|cx| { let (installation_id, release_channel, telemetry) = cx.update(|cx| {
let installation_id = cx.global::<Arc<Client>>().telemetry().installation_id(); let installation_id = cx
.global::<Arc<Client>>()
.telemetry()
.read(cx)
.installation_id();
let release_channel = cx let release_channel = cx
.has_global::<ReleaseChannel>() .has_global::<ReleaseChannel>()
.then(|| cx.global::<ReleaseChannel>().display_name()); .then(|| cx.global::<ReleaseChannel>().display_name());

View file

@ -482,27 +482,26 @@ pub fn report_call_event_for_room(
let telemetry = client.telemetry(); let telemetry = client.telemetry();
let telemetry_settings = *TelemetrySettings::get_global(cx); let telemetry_settings = *TelemetrySettings::get_global(cx);
telemetry.report_call_event(telemetry_settings, operation, Some(room_id), channel_id) telemetry.update(cx, |this, cx| {
this.report_call_event(telemetry_settings, operation, Some(room_id), channel_id, cx)
});
} }
pub fn report_call_event_for_channel( pub fn report_call_event_for_channel(
operation: &'static str, operation: &'static str,
channel_id: u64, channel_id: u64,
client: &Arc<Client>, client: &Arc<Client>,
cx: &AppContext, cx: &mut AppContext,
) { ) {
let room = ActiveCall::global(cx).read(cx).room(); let room = ActiveCall::global(cx).read(cx).room();
let room_id = room.map(|r| r.read(cx).id());
let telemetry = client.telemetry(); let telemetry = client.telemetry();
let telemetry_settings = *TelemetrySettings::get_global(cx); let telemetry_settings = *TelemetrySettings::get_global(cx);
telemetry.report_call_event( telemetry.update(cx, |this, cx| {
telemetry_settings, this.report_call_event(telemetry_settings, operation, room_id, Some(channel_id), cx)
operation, });
room.map(|r| r.read(cx).id()),
Some(channel_id),
)
} }
#[cfg(test)] #[cfg(test)]

View file

@ -121,7 +121,7 @@ pub struct Client {
id: AtomicU64, id: AtomicU64,
peer: Arc<Peer>, peer: Arc<Peer>,
http: Arc<dyn HttpClient>, http: Arc<dyn HttpClient>,
telemetry: Arc<Telemetry>, telemetry: Model<Telemetry>,
state: RwLock<ClientState>, state: RwLock<ClientState>,
#[allow(clippy::type_complexity)] #[allow(clippy::type_complexity)]
@ -501,8 +501,12 @@ impl Client {
})); }));
} }
Status::SignedOut | Status::UpgradeRequired => { Status::SignedOut | Status::UpgradeRequired => {
cx.update(|cx| self.telemetry.set_authenticated_user_info(None, false, cx)) cx.update(|cx| {
.log_err(); self.telemetry.update(cx, |this, cx| {
this.set_authenticated_user_info(None, false, cx)
})
})
.log_err();
state._reconnect_task.take(); state._reconnect_task.take();
} }
_ => {} _ => {}
@ -1320,7 +1324,7 @@ impl Client {
} }
} }
pub fn telemetry(&self) -> &Arc<Telemetry> { pub fn telemetry(&self) -> &Model<Telemetry> {
&self.telemetry &self.telemetry
} }
} }

View file

@ -1,12 +1,12 @@
use crate::{TelemetrySettings, ZED_SECRET_CLIENT_TOKEN, ZED_SERVER_URL}; use crate::{TelemetrySettings, ZED_SECRET_CLIENT_TOKEN, ZED_SERVER_URL};
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use futures::Future; use futures::Future;
use gpui::{serde_json, AppContext, AppMetadata, BackgroundExecutor, Task}; use gpui::{serde_json, AppContext, AppMetadata, Context, Model, ModelContext, Task};
use lazy_static::lazy_static; use lazy_static::lazy_static;
use parking_lot::Mutex;
use serde::Serialize; use serde::Serialize;
use settings::Settings; use settings::Settings;
use std::{env, io::Write, mem, path::PathBuf, sync::Arc, time::Duration}; use std::io::Write;
use std::{env, mem, path::PathBuf, sync::Arc, time::Duration};
use sysinfo::{ use sysinfo::{
CpuRefreshKind, Pid, PidExt, ProcessExt, ProcessRefreshKind, RefreshKind, System, SystemExt, CpuRefreshKind, Pid, PidExt, ProcessExt, ProcessRefreshKind, RefreshKind, System, SystemExt,
}; };
@ -16,11 +16,6 @@ use util::{channel::ReleaseChannel, TryFutureExt};
pub struct Telemetry { pub struct Telemetry {
http_client: Arc<dyn HttpClient>, http_client: Arc<dyn HttpClient>,
executor: BackgroundExecutor,
state: Mutex<TelemetryState>,
}
struct TelemetryState {
metrics_id: Option<Arc<str>>, // Per logged-in user metrics_id: Option<Arc<str>>, // Per logged-in user
installation_id: Option<Arc<str>>, // Per app installation (different for dev, nightly, preview, and stable) installation_id: Option<Arc<str>>, // Per app installation (different for dev, nightly, preview, and stable)
session_id: Option<Arc<str>>, // Per app launch session_id: Option<Arc<str>>, // Per app launch
@ -127,7 +122,7 @@ const DEBOUNCE_INTERVAL: Duration = Duration::from_secs(1);
const DEBOUNCE_INTERVAL: Duration = Duration::from_secs(30); const DEBOUNCE_INTERVAL: Duration = Duration::from_secs(30);
impl Telemetry { impl Telemetry {
pub fn new(client: Arc<dyn HttpClient>, cx: &mut AppContext) -> Arc<Self> { pub fn new(client: Arc<dyn HttpClient>, cx: &mut AppContext) -> Model<Self> {
let release_channel = if cx.has_global::<ReleaseChannel>() { let release_channel = if cx.has_global::<ReleaseChannel>() {
Some(cx.global::<ReleaseChannel>().display_name()) Some(cx.global::<ReleaseChannel>().display_name())
} else { } else {
@ -135,57 +130,48 @@ impl Telemetry {
}; };
// TODO: Replace all hardware stuff with nested SystemSpecs json // TODO: Replace all hardware stuff with nested SystemSpecs json
let this = Arc::new(Self { let this = cx.build_model(|cx| Self {
http_client: client, http_client: client,
executor: cx.background_executor().clone(), app_metadata: cx.app_metadata(),
state: Mutex::new(TelemetryState { architecture: env::consts::ARCH,
app_metadata: cx.app_metadata(), release_channel,
architecture: env::consts::ARCH, installation_id: None,
release_channel, metrics_id: None,
installation_id: None, session_id: None,
metrics_id: None, clickhouse_events_queue: Default::default(),
session_id: None, flush_clickhouse_events_task: Default::default(),
clickhouse_events_queue: Default::default(), log_file: None,
flush_clickhouse_events_task: Default::default(), is_staff: None,
log_file: None, first_event_datetime: None,
is_staff: None,
first_event_datetime: None,
}),
}); });
// We should only ever have one instance of Telemetry, leak the subscription to keep it alive // We should only ever have one instance of Telemetry, leak the subscription to keep it alive
// rather than store in TelemetryState, complicating spawn as subscriptions are not Send // rather than store in TelemetryState, complicating spawn as subscriptions are not Send
std::mem::forget(cx.on_app_quit({ std::mem::forget(this.update(cx, |_, cx| cx.on_app_quit(Self::shutdown_telemetry)));
let this = this.clone();
move |cx| this.shutdown_telemetry(cx)
}));
this this
} }
fn shutdown_telemetry(self: &Arc<Self>, cx: &mut AppContext) -> impl Future<Output = ()> { fn shutdown_telemetry(&mut self, cx: &mut ModelContext<Self>) -> impl Future<Output = ()> {
let telemetry_settings = TelemetrySettings::get_global(cx).clone(); let telemetry_settings = TelemetrySettings::get_global(cx).clone();
self.report_app_event(telemetry_settings, "close"); self.report_app_event(telemetry_settings, "close", cx);
Task::ready(()) Task::ready(())
} }
pub fn log_file_path(&self) -> Option<PathBuf> { pub fn log_file_path(&self) -> Option<PathBuf> {
Some(self.state.lock().log_file.as_ref()?.path().to_path_buf()) Some(self.log_file.as_ref()?.path().to_path_buf())
} }
pub fn start( pub fn start(
self: &Arc<Self>, &mut self,
installation_id: Option<String>, installation_id: Option<String>,
session_id: String, session_id: String,
cx: &mut AppContext, cx: &mut ModelContext<Self>,
) { ) {
let mut state = self.state.lock(); self.installation_id = installation_id.map(|id| id.into());
state.installation_id = installation_id.map(|id| id.into()); self.session_id = Some(session_id.into());
state.session_id = Some(session_id.into());
drop(state);
let this = self.clone(); cx.spawn(|this, mut cx| async move {
cx.spawn(|cx| async move {
// Avoiding calling `System::new_all()`, as there have been crashes related to it // Avoiding calling `System::new_all()`, as there have been crashes related to it
let refresh_kind = RefreshKind::new() let refresh_kind = RefreshKind::new()
.with_memory() // For memory usage .with_memory() // For memory usage
@ -221,23 +207,28 @@ impl Telemetry {
break; break;
}; };
this.report_memory_event( this.update(&mut cx, |this, cx| {
telemetry_settings, this.report_memory_event(
process.memory(), telemetry_settings,
process.virtual_memory(), process.memory(),
); process.virtual_memory(),
this.report_cpu_event( cx,
telemetry_settings, );
process.cpu_usage(), this.report_cpu_event(
system.cpus().len() as u32, telemetry_settings,
); process.cpu_usage(),
system.cpus().len() as u32,
cx,
);
})
.ok();
} }
}) })
.detach(); .detach();
} }
pub fn set_authenticated_user_info( pub fn set_authenticated_user_info(
self: &Arc<Self>, &mut self,
metrics_id: Option<String>, metrics_id: Option<String>,
is_staff: bool, is_staff: bool,
cx: &AppContext, cx: &AppContext,
@ -246,21 +237,20 @@ impl Telemetry {
return; return;
} }
let mut state = self.state.lock();
let metrics_id: Option<Arc<str>> = metrics_id.map(|id| id.into()); let metrics_id: Option<Arc<str>> = metrics_id.map(|id| id.into());
state.metrics_id = metrics_id.clone(); self.metrics_id = metrics_id.clone();
state.is_staff = Some(is_staff); self.is_staff = Some(is_staff);
drop(state);
} }
pub fn report_editor_event( pub fn report_editor_event(
self: &Arc<Self>, &mut self,
telemetry_settings: TelemetrySettings, telemetry_settings: TelemetrySettings,
file_extension: Option<String>, file_extension: Option<String>,
vim_mode: bool, vim_mode: bool,
operation: &'static str, operation: &'static str,
copilot_enabled: bool, copilot_enabled: bool,
copilot_enabled_for_language: bool, copilot_enabled_for_language: bool,
cx: &ModelContext<Self>,
) { ) {
let event = ClickhouseEvent::Editor { let event = ClickhouseEvent::Editor {
file_extension, file_extension,
@ -271,15 +261,16 @@ impl Telemetry {
milliseconds_since_first_event: self.milliseconds_since_first_event(), milliseconds_since_first_event: self.milliseconds_since_first_event(),
}; };
self.report_clickhouse_event(event, telemetry_settings, false) self.report_clickhouse_event(event, telemetry_settings, false, cx)
} }
pub fn report_copilot_event( pub fn report_copilot_event(
self: &Arc<Self>, &mut self,
telemetry_settings: TelemetrySettings, telemetry_settings: TelemetrySettings,
suggestion_id: Option<String>, suggestion_id: Option<String>,
suggestion_accepted: bool, suggestion_accepted: bool,
file_extension: Option<String>, file_extension: Option<String>,
cx: &ModelContext<Self>,
) { ) {
let event = ClickhouseEvent::Copilot { let event = ClickhouseEvent::Copilot {
suggestion_id, suggestion_id,
@ -288,15 +279,16 @@ impl Telemetry {
milliseconds_since_first_event: self.milliseconds_since_first_event(), milliseconds_since_first_event: self.milliseconds_since_first_event(),
}; };
self.report_clickhouse_event(event, telemetry_settings, false) self.report_clickhouse_event(event, telemetry_settings, false, cx)
} }
pub fn report_assistant_event( pub fn report_assistant_event(
self: &Arc<Self>, &mut self,
telemetry_settings: TelemetrySettings, telemetry_settings: TelemetrySettings,
conversation_id: Option<String>, conversation_id: Option<String>,
kind: AssistantKind, kind: AssistantKind,
model: &'static str, model: &'static str,
cx: &ModelContext<Self>,
) { ) {
let event = ClickhouseEvent::Assistant { let event = ClickhouseEvent::Assistant {
conversation_id, conversation_id,
@ -305,15 +297,16 @@ impl Telemetry {
milliseconds_since_first_event: self.milliseconds_since_first_event(), milliseconds_since_first_event: self.milliseconds_since_first_event(),
}; };
self.report_clickhouse_event(event, telemetry_settings, false) self.report_clickhouse_event(event, telemetry_settings, false, cx)
} }
pub fn report_call_event( pub fn report_call_event(
self: &Arc<Self>, &mut self,
telemetry_settings: TelemetrySettings, telemetry_settings: TelemetrySettings,
operation: &'static str, operation: &'static str,
room_id: Option<u64>, room_id: Option<u64>,
channel_id: Option<u64>, channel_id: Option<u64>,
cx: &ModelContext<Self>,
) { ) {
let event = ClickhouseEvent::Call { let event = ClickhouseEvent::Call {
operation, operation,
@ -322,14 +315,15 @@ impl Telemetry {
milliseconds_since_first_event: self.milliseconds_since_first_event(), milliseconds_since_first_event: self.milliseconds_since_first_event(),
}; };
self.report_clickhouse_event(event, telemetry_settings, false) self.report_clickhouse_event(event, telemetry_settings, false, cx)
} }
pub fn report_cpu_event( pub fn report_cpu_event(
self: &Arc<Self>, &mut self,
telemetry_settings: TelemetrySettings, telemetry_settings: TelemetrySettings,
usage_as_percentage: f32, usage_as_percentage: f32,
core_count: u32, core_count: u32,
cx: &ModelContext<Self>,
) { ) {
let event = ClickhouseEvent::Cpu { let event = ClickhouseEvent::Cpu {
usage_as_percentage, usage_as_percentage,
@ -337,14 +331,15 @@ impl Telemetry {
milliseconds_since_first_event: self.milliseconds_since_first_event(), milliseconds_since_first_event: self.milliseconds_since_first_event(),
}; };
self.report_clickhouse_event(event, telemetry_settings, false) self.report_clickhouse_event(event, telemetry_settings, false, cx)
} }
pub fn report_memory_event( pub fn report_memory_event(
self: &Arc<Self>, &mut self,
telemetry_settings: TelemetrySettings, telemetry_settings: TelemetrySettings,
memory_in_bytes: u64, memory_in_bytes: u64,
virtual_memory_in_bytes: u64, virtual_memory_in_bytes: u64,
cx: &ModelContext<Self>,
) { ) {
let event = ClickhouseEvent::Memory { let event = ClickhouseEvent::Memory {
memory_in_bytes, memory_in_bytes,
@ -352,94 +347,90 @@ impl Telemetry {
milliseconds_since_first_event: self.milliseconds_since_first_event(), milliseconds_since_first_event: self.milliseconds_since_first_event(),
}; };
self.report_clickhouse_event(event, telemetry_settings, false) self.report_clickhouse_event(event, telemetry_settings, false, cx)
} }
// app_events are called at app open and app close, so flush is set to immediately send // app_events are called at app open and app close, so flush is set to immediately send
pub fn report_app_event( pub fn report_app_event(
self: &Arc<Self>, &mut self,
telemetry_settings: TelemetrySettings, telemetry_settings: TelemetrySettings,
operation: &'static str, operation: &'static str,
cx: &ModelContext<Self>,
) { ) {
let event = ClickhouseEvent::App { let event = ClickhouseEvent::App {
operation, operation,
milliseconds_since_first_event: self.milliseconds_since_first_event(), milliseconds_since_first_event: self.milliseconds_since_first_event(),
}; };
self.report_clickhouse_event(event, telemetry_settings, true) self.report_clickhouse_event(event, telemetry_settings, true, cx)
} }
fn milliseconds_since_first_event(&self) -> i64 { fn milliseconds_since_first_event(&mut self) -> i64 {
let mut state = self.state.lock(); match self.first_event_datetime {
match state.first_event_datetime {
Some(first_event_datetime) => { Some(first_event_datetime) => {
let now: DateTime<Utc> = Utc::now(); let now: DateTime<Utc> = Utc::now();
now.timestamp_millis() - first_event_datetime.timestamp_millis() now.timestamp_millis() - first_event_datetime.timestamp_millis()
} }
None => { None => {
state.first_event_datetime = Some(Utc::now()); self.first_event_datetime = Some(Utc::now());
0 0
} }
} }
} }
fn report_clickhouse_event( fn report_clickhouse_event(
self: &Arc<Self>, &mut self,
event: ClickhouseEvent, event: ClickhouseEvent,
telemetry_settings: TelemetrySettings, telemetry_settings: TelemetrySettings,
immediate_flush: bool, immediate_flush: bool,
cx: &ModelContext<Self>,
) { ) {
if !telemetry_settings.metrics { if !telemetry_settings.metrics {
return; return;
} }
let mut state = self.state.lock(); let signed_in = self.metrics_id.is_some();
let signed_in = state.metrics_id.is_some(); self.clickhouse_events_queue
state
.clickhouse_events_queue
.push(ClickhouseEventWrapper { signed_in, event }); .push(ClickhouseEventWrapper { signed_in, event });
if state.installation_id.is_some() { if self.installation_id.is_some() {
if immediate_flush || state.clickhouse_events_queue.len() >= MAX_QUEUE_LEN { if immediate_flush || self.clickhouse_events_queue.len() >= MAX_QUEUE_LEN {
drop(state); self.flush_clickhouse_events(cx);
self.flush_clickhouse_events();
} else { } else {
let this = self.clone(); self.flush_clickhouse_events_task = Some(cx.spawn(|this, mut cx| async move {
let executor = self.executor.clone(); smol::Timer::after(DEBOUNCE_INTERVAL).await;
state.flush_clickhouse_events_task = Some(self.executor.spawn(async move { this.update(&mut cx, |this, cx| this.flush_clickhouse_events(cx))
executor.timer(DEBOUNCE_INTERVAL).await; .ok();
this.flush_clickhouse_events();
})); }));
} }
} }
} }
pub fn metrics_id(self: &Arc<Self>) -> Option<Arc<str>> { pub fn metrics_id(&self) -> Option<Arc<str>> {
self.state.lock().metrics_id.clone() self.metrics_id.clone()
} }
pub fn installation_id(self: &Arc<Self>) -> Option<Arc<str>> { pub fn installation_id(&self) -> Option<Arc<str>> {
self.state.lock().installation_id.clone() self.installation_id.clone()
} }
pub fn is_staff(self: &Arc<Self>) -> Option<bool> { pub fn is_staff(&self) -> Option<bool> {
self.state.lock().is_staff self.is_staff
} }
fn flush_clickhouse_events(self: &Arc<Self>) { fn flush_clickhouse_events(&mut self, cx: &ModelContext<Self>) {
let mut state = self.state.lock(); self.first_event_datetime = None;
state.first_event_datetime = None; let mut events = mem::take(&mut self.clickhouse_events_queue);
let mut events = mem::take(&mut state.clickhouse_events_queue); self.flush_clickhouse_events_task.take();
state.flush_clickhouse_events_task.take();
drop(state);
let this = self.clone(); let http_client = self.http_client.clone();
self.executor
.spawn(
async move {
let mut json_bytes = Vec::new();
if let Some(file) = &mut this.state.lock().log_file { cx.spawn(|this, mut cx| {
async move {
let mut json_bytes = Vec::new();
this.update(&mut cx, |this, _| {
if let Some(file) = &mut this.log_file {
let file = file.as_file_mut(); let file = file.as_file_mut();
for event in &mut events { for event in &mut events {
json_bytes.clear(); json_bytes.clear();
@ -449,39 +440,43 @@ impl Telemetry {
} }
} }
{ std::io::Result::Ok(())
let state = this.state.lock(); })??;
let request_body = ClickhouseEventRequestBody {
token: ZED_SECRET_CLIENT_TOKEN,
installation_id: state.installation_id.clone(),
session_id: state.session_id.clone(),
is_staff: state.is_staff.clone(),
app_version: state
.app_metadata
.app_version
.map(|version| version.to_string()),
os_name: state.app_metadata.os_name,
os_version: state
.app_metadata
.os_version
.map(|version| version.to_string()),
architecture: state.architecture,
release_channel: state.release_channel, if let Ok(Ok(json_bytes)) = this.update(&mut cx, |this, _| {
events, let request_body = ClickhouseEventRequestBody {
}; token: ZED_SECRET_CLIENT_TOKEN,
dbg!(&request_body); installation_id: this.installation_id.clone(),
json_bytes.clear(); session_id: this.session_id.clone(),
serde_json::to_writer(&mut json_bytes, &request_body)?; is_staff: this.is_staff.clone(),
} app_version: this
.app_metadata
.app_version
.map(|version| version.to_string()),
os_name: this.app_metadata.os_name,
os_version: this
.app_metadata
.os_version
.map(|version| version.to_string()),
architecture: this.architecture,
this.http_client release_channel: this.release_channel,
events,
};
json_bytes.clear();
serde_json::to_writer(&mut json_bytes, &request_body)?;
std::io::Result::Ok(json_bytes)
}) {
http_client
.post_json(CLICKHOUSE_EVENTS_URL.as_str(), json_bytes.into()) .post_json(CLICKHOUSE_EVENTS_URL.as_str(), json_bytes.into())
.await?; .await?;
anyhow::Ok(())
} }
.log_err(),
) anyhow::Ok(())
.detach(); }
.log_err()
})
.detach();
} }
} }

View file

@ -168,11 +168,13 @@ impl UserStore {
cx.update(|cx| { cx.update(|cx| {
if let Some(info) = info { if let Some(info) = info {
cx.update_flags(info.staff, info.flags); cx.update_flags(info.staff, info.flags);
client.telemetry.set_authenticated_user_info( client.telemetry.update(cx, |this, cx| {
Some(info.metrics_id.clone()), this.set_authenticated_user_info(
info.staff, Some(info.metrics_id.clone()),
cx, info.staff,
) cx,
)
})
} }
})?; })?;

View file

@ -8951,7 +8951,7 @@ impl Editor {
&self, &self,
suggestion_id: Option<String>, suggestion_id: Option<String>,
suggestion_accepted: bool, suggestion_accepted: bool,
cx: &AppContext, cx: &mut AppContext,
) { ) {
let Some(project) = &self.project else { return }; let Some(project) = &self.project else { return };
@ -8968,12 +8968,15 @@ impl Editor {
let telemetry = project.read(cx).client().telemetry().clone(); let telemetry = project.read(cx).client().telemetry().clone();
let telemetry_settings = *TelemetrySettings::get_global(cx); let telemetry_settings = *TelemetrySettings::get_global(cx);
telemetry.report_copilot_event( telemetry.update(cx, |this, cx| {
telemetry_settings, this.report_copilot_event(
suggestion_id, telemetry_settings,
suggestion_accepted, suggestion_id,
file_extension, suggestion_accepted,
) file_extension,
cx,
)
});
} }
#[cfg(any(test, feature = "test-support"))] #[cfg(any(test, feature = "test-support"))]
@ -8981,7 +8984,7 @@ impl Editor {
&self, &self,
_operation: &'static str, _operation: &'static str,
_file_extension: Option<String>, _file_extension: Option<String>,
_cx: &AppContext, _cx: &mut AppContext,
) { ) {
} }
@ -8990,7 +8993,7 @@ impl Editor {
&self, &self,
operation: &'static str, operation: &'static str,
file_extension: Option<String>, file_extension: Option<String>,
cx: &AppContext, cx: &mut AppContext,
) { ) {
let Some(project) = &self.project else { return }; let Some(project) = &self.project else { return };
@ -9020,14 +9023,17 @@ impl Editor {
.show_copilot_suggestions; .show_copilot_suggestions;
let telemetry = project.read(cx).client().telemetry().clone(); let telemetry = project.read(cx).client().telemetry().clone();
telemetry.report_editor_event( telemetry.update(cx, |this, cx| {
telemetry_settings, this.report_editor_event(
file_extension, telemetry_settings,
vim_mode, file_extension,
operation, vim_mode,
copilot_enabled, operation,
copilot_enabled_for_language, copilot_enabled,
) copilot_enabled_for_language,
cx,
)
});
} }
/// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines, /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,

View file

@ -10,7 +10,6 @@ pub use entity_map::*;
pub use model_context::*; pub use model_context::*;
use refineable::Refineable; use refineable::Refineable;
use smallvec::SmallVec; use smallvec::SmallVec;
use smol::future::FutureExt;
#[cfg(any(test, feature = "test-support"))] #[cfg(any(test, feature = "test-support"))]
pub use test_context::*; pub use test_context::*;
@ -985,21 +984,21 @@ impl AppContext {
self.actions.all_action_names() self.actions.all_action_names()
} }
pub fn on_app_quit<Fut>( // pub fn on_app_quit<Fut>(
&mut self, // &mut self,
mut on_quit: impl FnMut(&mut AppContext) -> Fut + 'static, // mut on_quit: impl FnMut(&mut AppContext) -> Fut + 'static,
) -> Subscription // ) -> Subscription
where // where
Fut: 'static + Future<Output = ()>, // Fut: 'static + Future<Output = ()>,
{ // {
self.quit_observers.insert( // self.quit_observers.insert(
(), // (),
Box::new(move |cx| { // Box::new(move |cx| {
let future = on_quit(cx); // let future = on_quit(cx);
async move { future.await }.boxed_local() // async move { future.await }.boxed_local()
}), // }),
) // )
} // }
} }
impl Context for AppContext { impl Context for AppContext {

View file

@ -176,15 +176,15 @@ fn main() {
// }) // })
// .detach(); // .detach();
client.telemetry().start(installation_id, session_id, cx); client.telemetry().update(cx, |this, cx| {
let telemetry_settings = *client::TelemetrySettings::get_global(cx); this.start(installation_id, session_id, cx);
let event_operation = match existing_installation_id_found { let telemetry_settings = *client::TelemetrySettings::get_global(cx);
Some(false) => "first open", let event_operation = match existing_installation_id_found {
_ => "open", Some(false) => "first open",
}; _ => "open",
client };
.telemetry() this.report_app_event(telemetry_settings, event_operation, cx);
.report_app_event(telemetry_settings, event_operation); });
let app_state = Arc::new(AppState { let app_state = Arc::new(AppState {
languages, languages,

View file

@ -10,8 +10,8 @@ pub use assets::*;
use collections::VecDeque; use collections::VecDeque;
use editor::{Editor, MultiBuffer}; use editor::{Editor, MultiBuffer};
use gpui::{ use gpui::{
actions, point, px, AppContext, Context, FocusableView, PromptLevel, TitlebarOptions, actions, point, px, AppContext, AsyncAppContext, Context, FocusableView, PromptLevel,
ViewContext, VisualContext, WindowBounds, WindowKind, WindowOptions, TitlebarOptions, ViewContext, VisualContext, WindowBounds, WindowKind, WindowOptions,
}; };
pub use only_instance::*; pub use only_instance::*;
pub use open_listener::*; pub use open_listener::*;
@ -628,12 +628,12 @@ fn open_telemetry_log_file(workspace: &mut Workspace, cx: &mut ViewContext<Works
workspace.with_local_workspace(cx, move |workspace, cx| { workspace.with_local_workspace(cx, move |workspace, cx| {
let app_state = workspace.app_state().clone(); let app_state = workspace.app_state().clone();
cx.spawn(|workspace, mut cx| async move { cx.spawn(|workspace, mut cx| async move {
async fn fetch_log_string(app_state: &Arc<AppState>) -> Option<String> { async fn fetch_log_string(app_state: &Arc<AppState>, cx: &AsyncAppContext) -> Option<String> {
let path = app_state.client.telemetry().log_file_path()?; let path = cx.update(|cx| app_state.client.telemetry().read(cx).log_file_path()).ok()??;
app_state.fs.load(&path).await.log_err() app_state.fs.load(&path).await.log_err()
} }
let log = fetch_log_string(&app_state).await.unwrap_or_else(|| "// No data has been collected yet".to_string()); let log = fetch_log_string(&app_state, &cx).await.unwrap_or_else(|| "// No data has been collected yet".to_string());
const MAX_TELEMETRY_LOG_LEN: usize = 5 * 1024 * 1024; const MAX_TELEMETRY_LOG_LEN: usize = 5 * 1024 * 1024;
let mut start_offset = log.len().saturating_sub(MAX_TELEMETRY_LOG_LEN); let mut start_offset = log.len().saturating_sub(MAX_TELEMETRY_LOG_LEN);