Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
Implement telemetry for the remote server (#59692)
Lukas Wirth479bce099509
diff --git a/Cargo.lock b/Cargo.lockindex f4fdccb084f..ef5bc3b20a9 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -15062,6 +15062,7 @@ dependencies = ["serde_json","settings","smol",+ "telemetry","tempfile","thiserror 2.0.17","urlencoding",@@ -15154,6 +15155,7 @@ dependencies = ["smol","sysinfo 0.37.2","task",+ "telemetry","tempfile","theme","theme_settings",diff --git a/crates/client/src/telemetry.rs b/crates/client/src/telemetry.rsindex ab9e1643fc9..0f7ee3174c3 100644--- a/crates/client/src/telemetry.rs+++ b/crates/client/src/telemetry.rs@@ -156,18 +156,7 @@ pub fn os_version() -> String {);"".to_string()};- let mut name = "unknown";- let mut version = "unknown";-- for line in content.lines() {- match line.split_once('=') {- Some(("ID", val)) => name = val.trim_matches('"'),- Some(("VERSION_ID", val)) => version = val.trim_matches('"'),- _ => {}- }- }-- format!("{} {}", name, version)+ util::parse_os_release(&content).unwrap_or_else(|| "unknown".to_string())}target_os = "windows" => {let mut info = unsafe { std::mem::zeroed() };@@ -512,6 +501,61 @@ impl Telemetry {Some(project_types)}+ /// Report a telemetry event that originated on a remote server.+ ///+ /// The remote server cannot upload telemetry itself, so it forwards events+ /// (as a JSON-serialized [`Event`]) to the client. Since the OS metadata in+ /// [`EventRequestBody`] is batch-level (describing the uploading client),+ /// the remote server's OS is attached as event properties instead, so the+ /// origin can still be distinguished downstream.+ pub fn report_remote_event(+ self: &Arc<Self>,+ event_json: &str,+ connection_type: &str,+ os_name: String,+ os_version: Option<String>,+ architecture: String,+ ) -> Result<()> {+ // The remote server forwards a bare `telemetry_events::FlexibleEvent`+ // (the type behind `telemetry::event!`), not the tagged `Event` enum.+ let mut flexible: telemetry_events::FlexibleEvent =+ serde_json::from_str(event_json).context("invalid remote telemetry event")?;+ flexible+ .event_properties+ .insert("remote".into(), true.into());+ flexible+ .event_properties+ .insert("remote_connection_type".into(), connection_type.into());+ flexible+ .event_properties+ .insert("remote_os_name".into(), os_name.into());+ flexible+ .event_properties+ .insert("remote_architecture".into(), architecture.into());+ if let Some(os_version) = os_version {+ flexible+ .event_properties+ .insert("remote_os_version".into(), os_version.into());+ }+ self.report_event(Event::Flexible(flexible));+ Ok(())+ }++ /// Returns a snapshot of the currently queued (not-yet-flushed) telemetry+ /// events, for use in tests.+ #[cfg(any(test, feature = "test-support"))]+ pub fn queued_events(self: &Arc<Self>) -> Vec<telemetry_events::FlexibleEvent> {+ self.state+ .lock()+ .events_queue+ .iter()+ .map(|wrapper| {+ let Event::Flexible(event) = &wrapper.event;+ event.clone()+ })+ .collect()+ }+fn report_event(self: &Arc<Self>, mut event: Event) {let mut state = self.state.lock();// RUST_LOG=telemetry=trace to debug telemetry events@@ -822,6 +866,79 @@ mod tests {});}+ #[gpui::test]+ async fn test_report_remote_event_tags_origin(cx: &mut TestAppContext) {+ init_test(cx);+ let clock = Arc::new(FakeSystemClock::new());+ let http = FakeHttpClient::with_200_response();++ let telemetry = cx.update(|cx| {+ let telemetry = Telemetry::new(clock.clone(), http, cx);+ telemetry.start(+ Some("system_id".to_string()),+ Some("installation_id".to_string()),+ "session_id".to_string(),+ cx,+ );+ telemetry+ });++ // Mirror what the remote server forwards: a bare `FlexibleEvent`, which+ // is the type produced by `telemetry::event!` / sent over the queue.+ let event_json = serde_json::to_string(&FlexibleEvent {+ event_type: "fs_watcher_poll".to_string(),+ event_properties: HashMap::from_iter([(+ "path".to_string(),+ serde_json::Value::String("/code/project".to_string()),+ )]),+ })+ .unwrap();++ cx.update(|_| {+ telemetry+ .report_remote_event(+ &event_json,+ "ssh",+ "Linux".to_string(),+ Some("ubuntu 24.04".to_string()),+ "aarch64".to_string(),+ )+ .unwrap();+ });++ let queue = telemetry.state.lock().events_queue.clone();+ assert_eq!(queue.len(), 1);+ let Event::Flexible(event) = &queue[0].event;+ assert_eq!(event.event_type, "fs_watcher_poll");+ // Original properties are preserved.+ assert_eq!(+ event.event_properties.get("path"),+ Some(&serde_json::Value::String("/code/project".to_string()))+ );+ // The remote server's OS is attached as properties, since the batch-level+ // OS describes the uploading client rather than the remote host.+ assert_eq!(+ event.event_properties.get("remote"),+ Some(&serde_json::Value::Bool(true))+ );+ assert_eq!(+ event.event_properties.get("remote_connection_type"),+ Some(&serde_json::Value::String("ssh".to_string()))+ );+ assert_eq!(+ event.event_properties.get("remote_os_name"),+ Some(&serde_json::Value::String("Linux".to_string()))+ );+ assert_eq!(+ event.event_properties.get("remote_os_version"),+ Some(&serde_json::Value::String("ubuntu 24.04".to_string()))+ );+ assert_eq!(+ event.event_properties.get("remote_architecture"),+ Some(&serde_json::Value::String("aarch64".to_string()))+ );+ }+#[gpui::test]fn test_project_discovery_does_not_double_report(cx: &mut gpui::TestAppContext) {init_test(cx);diff --git a/crates/project/src/project.rs b/crates/project/src/project.rsindex 9ae67a85633..2864313d8d7 100644--- a/crates/project/src/project.rs+++ b/crates/project/src/project.rs@@ -1633,6 +1633,7 @@ impl Project {remote_proto.add_entity_message_handler(Self::handle_update_worktree);remote_proto.add_entity_message_handler(Self::handle_update_project);remote_proto.add_entity_message_handler(Self::handle_toast);+ remote_proto.add_entity_message_handler(Self::handle_telemetry_event);remote_proto.add_entity_request_handler(Self::handle_language_server_prompt_request);remote_proto.add_entity_message_handler(Self::handle_hide_toast);remote_proto.add_entity_request_handler(Self::handle_update_buffer_from_remote_server);@@ -5302,6 +5303,42 @@ impl Project {})}+ async fn handle_telemetry_event(+ this: Entity<Self>,+ envelope: TypedEnvelope<proto::TelemetryEvent>,+ mut cx: AsyncApp,+ ) -> Result<()> {+ let payload = envelope.payload;+ this.update(&mut cx, |this, cx| {+ // The remote connection type, OS, version, and architecture are all+ // already known from connection setup, so they don't need to be sent+ // with each event.+ let Some((connection_type, platform, os_version)) =+ this.remote_client.as_ref().map(|client| {+ let client = client.read(cx);+ (+ client.connection_type(),+ client.remote_platform(),+ client.remote_os_version(),+ )+ })+ else {+ return;+ };+ this.client()+ .telemetry()+ .report_remote_event(+ &payload.event_json,+ connection_type,+ platform.os.display_name().to_string(),+ os_version,+ platform.arch.as_str().to_string(),+ )+ .log_err();+ });+ Ok(())+ }+async fn handle_language_server_prompt_request(this: Entity<Self>,envelope: TypedEnvelope<proto::LanguageServerPromptRequest>,diff --git a/crates/proto/proto/app.proto b/crates/proto/proto/app.protoindex 2ced6a16d44..c3982ebc82b 100644--- a/crates/proto/proto/app.proto+++ b/crates/proto/proto/app.proto@@ -14,6 +14,15 @@ message HideToast {string notification_id = 2;}+// A telemetry event generated on the remote server, forwarded to the client for+// reporting. The OS metadata is not included: the client already knows the+// remote platform from connection setup and attaches it when reporting.+message TelemetryEvent {+ uint64 project_id = 1;+ // JSON-serialized telemetry_events::FlexibleEvent { event_type, event_properties }.+ string event_json = 2;+}+message OpenServerSettings {uint64 project_id = 1;}diff --git a/crates/proto/proto/zed.proto b/crates/proto/proto/zed.protoindex 1af251f0ab4..31e86e9ba6e 100644--- a/crates/proto/proto/zed.proto+++ b/crates/proto/proto/zed.proto@@ -490,7 +490,8 @@ message Envelope {ResolveDocumentLink resolve_document_link = 455;ResolveDocumentLinkResponse resolve_document_link_response = 456;GitWorktreeCreatedAt git_worktree_created_at = 457;- GitWorktreeCreatedAtResponse git_worktree_created_at_response = 458; // current max+ GitWorktreeCreatedAtResponse git_worktree_created_at_response = 458;+ TelemetryEvent telemetry_event = 459; // current max}reserved 87 to 88;diff --git a/crates/proto/src/proto.rs b/crates/proto/src/proto.rsindex 16b8f38fb07..feb8bc9c6cd 100644--- a/crates/proto/src/proto.rs+++ b/crates/proto/src/proto.rs@@ -259,6 +259,7 @@ messages!((SynchronizeBuffersResponse, Foreground),(TaskContext, Background),(TaskContextForLocation, Background),+ (TelemetryEvent, Background),(Test, Foreground),(Toast, Background),(Unfollow, Foreground),@@ -723,6 +724,7 @@ entity_messages!(LspExtRunFlycheck,LspExtClearFlycheck,LanguageServerLog,+ TelemetryEvent,Toast,HideToast,OpenServerSettings,diff --git a/crates/remote/Cargo.toml b/crates/remote/Cargo.tomlindex c08561954eb..f420c2dca13 100644--- a/crates/remote/Cargo.toml+++ b/crates/remote/Cargo.toml@@ -39,6 +39,7 @@ serde.workspace = trueserde_json.workspace = truesettings.workspace = truesmol.workspace = true+telemetry.workspace = truetempfile.workspace = truethiserror.workspace = trueurlencoding.workspace = truediff --git a/crates/remote/src/remote_client.rs b/crates/remote/src/remote_client.rsindex c0981d0706a..239e9785931 100644--- a/crates/remote/src/remote_client.rs+++ b/crates/remote/src/remote_client.rs@@ -71,6 +71,16 @@ impl RemoteOs {pub fn is_windows(&self) -> bool {matches!(self, RemoteOs::Windows)}++ /// A human-readable OS name for telemetry. Matches `client::telemetry::os_name`+ /// ignoring the compositor (as we run headless on remotes).+ pub fn display_name(&self) -> &'static str {+ match self {+ RemoteOs::Linux => "Linux",+ RemoteOs::MacOs => "macOS",+ RemoteOs::Windows => "Windows",+ }+ }}impl std::fmt::Display for RemoteOs {@@ -320,6 +330,8 @@ pub struct RemoteClient {unique_identifier: String,connection_options: RemoteConnectionOptions,path_style: PathStyle,+ platform: RemotePlatform,+ os_version: Option<String>,state: Option<State>,}@@ -418,11 +430,17 @@ impl RemoteClient {});let path_style = remote_connection.path_style();+ let platform = remote_connection.remote_platform();+ let os_version = remote_connection.remote_os_version();+ let connection_options = remote_connection.connection_options();+ let connection_type = connection_options.connection_type();let this = cx.new(|_| Self {client: client.clone(),unique_identifier: unique_identifier.clone(),- connection_options: remote_connection.connection_options(),+ connection_options,path_style,+ platform,+ os_version: os_version.clone(),state: Some(State::Connecting),});@@ -491,6 +509,18 @@ impl RemoteClient {});});+ // Use the same `remote_*` property schema as the forwarded+ // remote events (see `client::telemetry::report_remote_event`)+ // so all remote-origin telemetry can be queried uniformly.+ telemetry::event!(+ "Remote Connection Established",+ remote = true,+ remote_connection_type = connection_type,+ remote_os_name = platform.os.display_name(),+ remote_os_version = os_version,+ remote_architecture = platform.arch.as_str(),+ );+Ok(Some(this))});@@ -994,6 +1024,24 @@ impl RemoteClient {self.path_style}+ /// The platform (OS and architecture) of the remote host, detected during+ /// connection setup.+ pub fn remote_platform(&self) -> RemotePlatform {+ self.platform+ }++ /// The OS version of the remote host (e.g. `"ubuntu 24.04"`), detected+ /// during connection setup. `None` if it could not be determined.+ pub fn remote_os_version(&self) -> Option<String> {+ self.os_version.clone()+ }++ /// A stable identifier for the kind of remote connection (e.g. `"ssh"`,+ /// `"wsl"`, `"docker"`, `"podman"`).+ pub fn connection_type(&self) -> &'static str {+ self.connection_options.connection_type()+ }+/// Forcibly disconnects from the remote server by killing the underlying connection./// This will trigger the reconnection logic if reconnection attempts remain./// Useful for testing reconnection behavior in real environments.@@ -1298,6 +1346,24 @@ impl RemoteConnectionOptions {RemoteConnectionOptions::Mock(opts) => format!("mock-{}", opts.id),}}++ /// A stable identifier for the kind of remote connection, suitable for+ /// telemetry (e.g. `"ssh"`, `"wsl"`, `"docker"`, `"podman"`).+ pub fn connection_type(&self) -> &'static str {+ match self {+ RemoteConnectionOptions::Ssh(_) => "ssh",+ RemoteConnectionOptions::Wsl(_) => "wsl",+ RemoteConnectionOptions::Docker(opts) => {+ if opts.use_podman {+ "podman"+ } else {+ "docker"+ }+ }+ #[cfg(any(test, feature = "test-support"))]+ RemoteConnectionOptions::Mock(_) => "mock",+ }+ }}#[cfg(test)]@@ -1327,6 +1393,38 @@ mod tests {assert_eq!(options.display_name(), "1.2.3.4");}+ #[test]+ fn test_connection_type() {+ assert_eq!(+ RemoteConnectionOptions::Ssh(SshConnectionOptions::default()).connection_type(),+ "ssh"+ );+ assert_eq!(+ RemoteConnectionOptions::Wsl(WslConnectionOptions {+ distro_name: "Ubuntu".to_string(),+ user: None,+ })+ .connection_type(),+ "wsl"+ );+ assert_eq!(+ RemoteConnectionOptions::Docker(DockerConnectionOptions {+ use_podman: false,+ ..Default::default()+ })+ .connection_type(),+ "docker"+ );+ assert_eq!(+ RemoteConnectionOptions::Docker(DockerConnectionOptions {+ use_podman: true,+ ..Default::default()+ })+ .connection_type(),+ "podman"+ );+ }+#[gpui::test]async fn test_channel_client_request_stream_terminates_on_error(cx: &mut TestAppContext) {let (incoming_tx, incoming_rx) = mpsc::unbounded::<Envelope>();@@ -1525,6 +1623,11 @@ pub trait RemoteConnection: Send + Sync {) -> Result<CommandTemplate>;fn connection_options(&self) -> RemoteConnectionOptions;fn path_style(&self) -> PathStyle;+ /// The remote platform (OS and architecture), detected during connection setup.+ fn remote_platform(&self) -> RemotePlatform;+ /// The remote host's OS version (e.g. `"ubuntu 24.04"` or `"15.6.1"`),+ /// detected during connection setup. `None` if it could not be determined.+ fn remote_os_version(&self) -> Option<String>;fn shell(&self) -> String;fn default_system_shell(&self) -> String;fn has_wsl_interop(&self) -> bool;diff --git a/crates/remote/src/transport.rs b/crates/remote/src/transport.rsindex 1794a68839a..275b36905d3 100644--- a/crates/remote/src/transport.rs+++ b/crates/remote/src/transport.rs@@ -55,6 +55,63 @@ fn parse_platform(output: &str) -> Result<RemotePlatform> {Ok(RemotePlatform { os, arch })}+/// The command (program + args) used to read a remote host's OS version, given+/// its detected OS.+///+/// The output is parsed by [`parse_os_version`].+pub(crate) fn os_version_command(os: RemoteOs) -> (&'static str, &'static [&'static str]) {+ match os {+ // Matches the `/etc/os-release` parsing in `client::telemetry::os_version`.+ RemoteOs::Linux => ("cat", &["/etc/os-release"]),+ RemoteOs::MacOs => ("sw_vers", &["-productVersion"]),+ // Prints e.g. "Microsoft Windows [Version 10.0.19045.5011]".+ RemoteOs::Windows => ("cmd.exe", &["/c", "ver"]),+ }+}++/// Parses the output of [`os_version_command`] into a human-readable version+/// string, matching the conventions used by `client::telemetry::os_version`.+///+/// For Linux this is `"{ID} {VERSION_ID}"` (e.g. `"ubuntu 24.04"`); for macOS it+/// is the product version (e.g. `"15.6.1"`); for Windows it is the+/// `major.minor.build` version (e.g. `"10.0.19045"`). Returns `None` if nothing+/// usable could be parsed.+pub(crate) fn parse_os_version(os: RemoteOs, output: &str) -> Option<String> {+ let output = output.trim();+ if output.is_empty() {+ return None;+ }+ match os {+ RemoteOs::Linux => util::parse_os_release(output),+ RemoteOs::MacOs => {+ // `sw_vers -productVersion` prints a single version line.+ output+ .lines()+ .next_back()+ .map(|line| line.trim().to_string())+ .filter(|line| !line.is_empty())+ }+ RemoteOs::Windows => parse_windows_version(output),+ }+}++/// Extracts a `major.minor.build` version from the output of `cmd.exe /c ver`,+/// e.g. `"Microsoft Windows [Version 10.0.19045.5011]"` -> `"10.0.19045"`.+///+/// Scans for the first dotted run of integers (rather than relying on the+/// surrounding, potentially localized, text) and drops the trailing revision so+/// the format matches `client::telemetry::os_version` on Windows.+fn parse_windows_version(output: &str) -> Option<String> {+ output+ .split(|c: char| !c.is_ascii_digit() && c != '.')+ .filter_map(|token| {+ let parts: Vec<&str> = token.split('.').filter(|part| !part.is_empty()).collect();+ (parts.len() >= 3 && parts.iter().all(|part| part.parse::<u32>().is_ok()))+ .then(|| parts[..3].join("."))+ })+ .next()+}+/// Parses the output of `echo $SHELL` to determine the remote shell./// Takes the last line to skip possible shell initialization output.fn parse_shell(output: &str, fallback_shell: &str) -> String {@@ -446,6 +503,48 @@ mod tests {assert!(parse_platform("Linux armv7l\n").is_err());}+ #[test]+ fn test_parse_os_version() {+ // Linux delegates to `util::parse_os_release` (tested there); confirm+ // the dispatch is wired up.+ let os_release = "ID=ubuntu\nVERSION_ID=\"24.04\"\n";+ assert_eq!(+ parse_os_version(RemoteOs::Linux, os_release),+ Some("ubuntu 24.04".to_string())+ );++ // macOS `sw_vers -productVersion` prints a bare version, possibly after+ // shell initialization noise.+ assert_eq!(+ parse_os_version(RemoteOs::MacOs, "15.6.1\n"),+ Some("15.6.1".to_string())+ );+ assert_eq!(+ parse_os_version(RemoteOs::MacOs, "shell noise\n26.0\n"),+ Some("26.0".to_string())+ );+ assert_eq!(parse_os_version(RemoteOs::MacOs, ""), None);++ // Windows `cmd.exe /c ver`, with the trailing revision dropped to match+ // the `major.minor.build` format used by local Windows telemetry.+ assert_eq!(+ parse_os_version(+ RemoteOs::Windows,+ "Microsoft Windows [Version 10.0.19045.5011]\n"+ ),+ Some("10.0.19045".to_string())+ );+ // Localized output: only the version number is relied upon.+ assert_eq!(+ parse_os_version(+ RemoteOs::Windows,+ "Microsoft Windows [Versione 10.0.22631.1]"+ ),+ Some("10.0.22631".to_string())+ );+ assert_eq!(parse_os_version(RemoteOs::Windows, "no version here"), None);+ }+#[test]fn test_parse_shell() {assert_eq!(parse_shell("/bin/bash\n", "sh"), "/bin/bash");diff --git a/crates/remote/src/transport/docker.rs b/crates/remote/src/transport/docker.rsindex 872d1d460ec..efefbe8e50d 100644--- a/crates/remote/src/transport/docker.rs+++ b/crates/remote/src/transport/docker.rs@@ -25,7 +25,8 @@ use gpui::{App, AppContext, AsyncApp, Task};use rpc::proto::Envelope;use crate::{- RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions, RemoteOs, RemotePlatform,+ RemoteArch, RemoteClientDelegate, RemoteConnection, RemoteConnectionOptions, RemoteOs,+ RemotePlatform,remote_client::{CommandTemplate, Interactive},transport::parse_platform,};@@ -57,6 +58,7 @@ pub(crate) struct DockerExecConnection {remote_binary_relpath: Option<Arc<RelPath>>,connection_options: DockerConnectionOptions,remote_platform: Option<RemotePlatform>,+ os_version: Option<String>,path_style: Option<PathStyle>,shell: String,}@@ -73,6 +75,7 @@ impl DockerExecConnection {remote_binary_relpath: None,connection_options,remote_platform: None,+ os_version: None,path_style: None,shell: "sh".to_owned(),};@@ -93,6 +96,9 @@ impl DockerExecConnection {this.remote_platform = Some(remote_platform);log::info!("Remote platform discovered: {:?}", this.remote_platform);+ this.os_version = this.discover_os_version(remote_platform.os).await;+ log::info!("Remote OS version discovered: {:?}", this.os_version);+this.shell = this.discover_shell().await;log::info!("Remote shell discovered: {}", this.shell);@@ -171,6 +177,21 @@ impl DockerExecConnection {parse_platform(&uname)}+ /// Best-effort detection of the container's OS version for telemetry.+ async fn discover_os_version(&self, os: RemoteOs) -> Option<String> {+ let (program, args) = super::os_version_command(os);+ match self+ .run_docker_exec(program, None, &Default::default(), args)+ .await+ {+ Ok(output) => super::parse_os_version(os, &output),+ Err(error) => {+ log::warn!("Failed to determine remote OS version: {error:#}");+ None+ }+ }+ }+async fn ensure_server_binary(&self,delegate: &Arc<dyn RemoteClientDelegate>,@@ -832,6 +853,19 @@ impl RemoteConnection for DockerExecConnection {self.path_style.unwrap_or(PathStyle::Posix)}+ fn remote_platform(&self) -> RemotePlatform {+ // Docker containers are always Linux; the platform is populated during+ // setup, so this fallback is only for the brief pre-detection window.+ self.remote_platform.unwrap_or(RemotePlatform {+ os: RemoteOs::Linux,+ arch: RemoteArch::X86_64,+ })+ }++ fn remote_os_version(&self) -> Option<String> {+ self.os_version.clone()+ }+fn shell(&self) -> String {self.shell.clone()}diff --git a/crates/remote/src/transport/mock.rs b/crates/remote/src/transport/mock.rsindex 01f7579ea56..3b860ac4e5d 100644--- a/crates/remote/src/transport/mock.rs+++ b/crates/remote/src/transport/mock.rs@@ -292,6 +292,17 @@ impl RemoteConnection for MockRemoteConnection {PathStyle::local()}+ fn remote_platform(&self) -> crate::RemotePlatform {+ crate::RemotePlatform {+ os: crate::RemoteOs::Linux,+ arch: crate::RemoteArch::X86_64,+ }+ }++ fn remote_os_version(&self) -> Option<String> {+ None+ }+fn shell(&self) -> String {"sh".to_owned()}diff --git a/crates/remote/src/transport/ssh.rs b/crates/remote/src/transport/ssh.rsindex 2beae54f2f5..25946c0b7c0 100644--- a/crates/remote/src/transport/ssh.rs+++ b/crates/remote/src/transport/ssh.rs@@ -44,6 +44,7 @@ pub(crate) struct SshRemoteConnection {killed: AtomicBool,remote_binary_path: Option<Arc<RelPath>>,ssh_platform: RemotePlatform,+ ssh_os_version: Option<String>,ssh_path_style: PathStyle,ssh_shell: String,ssh_shell_kind: ShellKind,@@ -512,6 +513,14 @@ impl RemoteConnection for SshRemoteConnection {self.ssh_path_style}+ fn remote_platform(&self) -> RemotePlatform {+ self.ssh_platform+ }++ fn remote_os_version(&self) -> Option<String> {+ self.ssh_os_version.clone()+ }+fn has_wsl_interop(&self) -> bool {false}@@ -757,6 +766,9 @@ impl SshRemoteConnection {let ssh_platform = socket.platform(ssh_shell_kind, is_windows).await?;log::info!("Remote platform discovered: {:?}", ssh_platform);+ let ssh_os_version = socket.os_version(ssh_platform.os, ssh_shell_kind).await;+ log::info!("Remote OS version discovered: {:?}", ssh_os_version);+let (ssh_path_style, ssh_default_system_shell) = match ssh_platform.os {RemoteOs::Windows => (PathStyle::Windows, ssh_shell.clone()),_ => (PathStyle::Posix, String::from("/bin/sh")),@@ -770,6 +782,7 @@ impl SshRemoteConnection {remote_binary_path: None,ssh_path_style,ssh_platform,+ ssh_os_version,ssh_shell,ssh_shell_kind,ssh_default_system_shell,@@ -1411,6 +1424,20 @@ impl SshSocket {parse_platform(&output)}+ /// Best-effort detection of the remote OS version. Failures are logged and+ /// result in `None` rather than failing the connection, since this is only+ /// used for telemetry.+ async fn os_version(&self, os: RemoteOs, shell: ShellKind) -> Option<String> {+ let (program, args) = super::os_version_command(os);+ match self.run_command(shell, program, args, false).await {+ Ok(output) => super::parse_os_version(os, &output),+ Err(error) => {+ log::warn!("Failed to determine remote OS version: {error:#}");+ None+ }+ }+ }+async fn platform_windows(&self, shell: ShellKind) -> Result<RemotePlatform> {let output = self.run_command(diff --git a/crates/remote/src/transport/wsl.rs b/crates/remote/src/transport/wsl.rsindex 1bbbaca2235..21ebdcbd049 100644--- a/crates/remote/src/transport/wsl.rs+++ b/crates/remote/src/transport/wsl.rs@@ -49,6 +49,7 @@ impl From<settings::WslConnection> for WslConnectionOptions {pub(crate) struct WslRemoteConnection {remote_binary_path: Option<Arc<RelPath>>,platform: RemotePlatform,+ os_version: Option<String>,shell: String,shell_kind: ShellKind,default_system_shell: String,@@ -77,6 +78,7 @@ impl WslRemoteConnection {os: RemoteOs::Linux,arch: RemoteArch::X86_64,},+ os_version: None,shell: String::new(),shell_kind: ShellKind::Posix,default_system_shell: String::from("/bin/sh"),@@ -103,6 +105,8 @@ impl WslRemoteConnection {.await.context("failed detecting platform")?;log::info!("Remote platform discovered: {:?}", this.platform);+ this.os_version = this.detect_os_version().await;+ log::info!("Remote OS version discovered: {:?}", this.os_version);this.remote_binary_path = Some(this.ensure_server_binary(&delegate, release_channel, version, cx).await@@ -119,6 +123,20 @@ impl WslRemoteConnection {parse_platform(&output)}+ /// Best-effort detection of the remote OS version for telemetry. Failures+ /// result in `None` rather than failing the connection.+ async fn detect_os_version(&self) -> Option<String> {+ let (program, args) = super::os_version_command(self.platform.os);+ let program = self.shell_kind.prepend_command_prefix(program);+ match self.run_wsl_command_with_output(&program, args).await {+ Ok(output) => super::parse_os_version(self.platform.os, &output),+ Err(error) => {+ log::warn!("Failed to determine remote OS version: {error:#}");+ None+ }+ }+ }+async fn detect_shell(&self) -> Result<String> {const DEFAULT_SHELL: &str = "sh";match self@@ -521,6 +539,14 @@ impl RemoteConnection for WslRemoteConnection {PathStyle::Posix}+ fn remote_platform(&self) -> RemotePlatform {+ self.platform+ }++ fn remote_os_version(&self) -> Option<String> {+ self.os_version.clone()+ }+fn shell(&self) -> String {self.shell.clone()}diff --git a/crates/remote_server/Cargo.toml b/crates/remote_server/Cargo.tomlindex 05bebd25fd0..66cb46688ec 100644--- a/crates/remote_server/Cargo.toml+++ b/crates/remote_server/Cargo.toml@@ -68,6 +68,7 @@ shellexpand.workspace = truesmol.workspace = truesysinfo.workspace = truetask.workspace = true+telemetry.workspace = trueutil.workspace = truewatch.workspace = trueworktree.workspace = truediff --git a/crates/remote_server/src/remote_editing_tests.rs b/crates/remote_server/src/remote_editing_tests.rsindex 8bd3493a9d2..0233057260a 100644--- a/crates/remote_server/src/remote_editing_tests.rs+++ b/crates/remote_server/src/remote_editing_tests.rs@@ -182,6 +182,107 @@ async fn test_basic_remote_editing(cx: &mut TestAppContext, server_cx: &mut Test});}+#[gpui::test]+async fn test_remote_telemetry_event_forwarding(+ cx: &mut TestAppContext,+ server_cx: &mut TestAppContext,+) {+ // This mirrors `init_test`, but retains the server-side session so the test+ // can drive a forwarded telemetry event over the proto channel (as+ // `init_telemetry_forwarding` does on a real remote server).+ let server_fs = FakeFs::new(server_cx.executor());+ server_fs+ .insert_tree(+ path!("/code"),+ json!({ "project1": { "README.md": "# project 1" } }),+ )+ .await;++ cx.update(|cx| release_channel::init(semver::Version::new(0, 0, 0), cx));+ server_cx.update(|cx| release_channel::init(semver::Version::new(0, 0, 0), cx));+ init_logger();++ let (opts, server_session, _) = RemoteClient::fake_server(cx, server_cx);+ let http_client = Arc::new(BlockedHttpClient);+ let node_runtime = NodeRuntime::unavailable();+ let languages = Arc::new(LanguageRegistry::new(cx.executor()));+ let proxy = Arc::new(ExtensionHostProxy::new());+ server_cx.update(HeadlessProject::init);+ let headless = server_cx.new(|cx| {+ HeadlessProject::new(+ crate::HeadlessAppState {+ session: server_session.clone(),+ fs: server_fs.clone(),+ http_client,+ node_runtime,+ languages,+ extension_host_proxy: proxy,+ startup_time: std::time::Instant::now(),+ },+ false,+ cx,+ )+ });++ let ssh = RemoteClient::connect_mock(opts, cx).await;+ let project = build_project(ssh, cx);+ project+ .update(cx, {+ let headless = headless.clone();+ |_, cx| cx.on_release(|_, _| drop(headless))+ })+ .detach();++ // The remote server forwards a bare `FlexibleEvent` as JSON; mirror that+ // here by sending the proto message the forwarding task would send.+ let event_json = json!({+ "event_type": "fs_watcher_poll",+ "event_properties": { "path": "/code/project1" },+ })+ .to_string();+ server_session+ .send(proto::TelemetryEvent {+ project_id: proto::REMOTE_SERVER_PROJECT_ID,+ event_json,+ })+ .unwrap();+ cx.executor().run_until_parked();++ let events = project.read_with(cx, |project, _| {+ project.client().telemetry().queued_events()+ });+ assert_eq!(+ events.len(),+ 1,+ "the forwarded event should be reported once"+ );+ let event = &events[0];+ assert_eq!(event.event_type, "fs_watcher_poll");+ // The event's original properties survive the round-trip.+ assert_eq!(+ event.event_properties.get("path"),+ Some(&serde_json::Value::String("/code/project1".to_string()))+ );+ // The client stamps the remote host metadata it learned at connection time.+ // The mock connection reports a Linux/x86_64 host over a "mock" connection.+ assert_eq!(+ event.event_properties.get("remote"),+ Some(&serde_json::Value::Bool(true))+ );+ assert_eq!(+ event.event_properties.get("remote_connection_type"),+ Some(&serde_json::Value::String("mock".to_string()))+ );+ assert_eq!(+ event.event_properties.get("remote_os_name"),+ Some(&serde_json::Value::String("Linux".to_string()))+ );+ assert_eq!(+ event.event_properties.get("remote_architecture"),+ Some(&serde_json::Value::String("x86_64".to_string()))+ );+}+async fn do_search_and_assert(project: &Entity<Project>,query: &str,diff --git a/crates/remote_server/src/server.rs b/crates/remote_server/src/server.rsindex 51d774f2e6c..e00c9173bbf 100644--- a/crates/remote_server/src/server.rs+++ b/crates/remote_server/src/server.rs@@ -304,6 +304,34 @@ fn init_logging_server(log_file_path: &Path) -> Result<Receiver<Vec<u8>>> {Ok(rx)}+/// Initializes the telemetry queue on the remote server, forwarding every+/// emitted event to the connected client over the proto channel.+///+/// The remote server cannot upload telemetry itself (it has no logged-in user,+/// no checksum seed, and no Telemetry instance), so without this its+/// `telemetry::event!` calls are silently dropped. The client attributes these+/// events to the remote host using the platform it already detected during+/// connection setup, so no OS metadata needs to be sent here.+fn init_telemetry_forwarding(session: AnyProtoClient, cx: &mut App) {+ let (tx, mut rx) = mpsc::unbounded::<telemetry::Event>();+ telemetry::init(tx);++ cx.background_spawn(async move {+ while let Some(event) = rx.next().await {+ let Some(event_json) = serde_json::to_string(&event).log_err() else {+ continue;+ };+ session+ .send(proto::TelemetryEvent {+ project_id: REMOTE_SERVER_PROJECT_ID,+ event_json,+ })+ .log_err();+ }+ })+ .detach();+}+fn handle_crash_files_requests(project: &Entity<HeadlessProject>, client: &AnyProtoClient) {client.add_request_handler(project.downgrade(),@@ -639,6 +667,7 @@ pub fn execute_run(log::info!("gpui app started, initializing server");let session = start_server(listeners, log_rx, cx, is_wsl_interop);+ init_telemetry_forwarding(session.clone(), cx);trusted_worktrees::init(HashMap::default(), cx);GitHostingProviderRegistry::set_global(git_hosting_provider_registry, cx);diff --git a/crates/util/src/util.rs b/crates/util/src/util.rsindex 3b704e50a53..b479660d924 100644--- a/crates/util/src/util.rs+++ b/crates/util/src/util.rs@@ -53,6 +53,29 @@ pub fn truncate(s: &str, max_chars: usize) -> &str {}}+/// Parses the contents of an `os-release` file (as found at `/etc/os-release`+/// and described by the systemd spec) into a human-readable string such as+/// `"ubuntu 24.04"`, combining the `ID` and `VERSION_ID` fields.+///+/// Returns `None` if no `ID` field is present. When `VERSION_ID` is absent+/// (e.g. on rolling releases), only the `ID` is returned.+pub fn parse_os_release(content: &str) -> Option<String> {+ let mut id = None;+ let mut version_id = None;+ for line in content.lines() {+ match line.split_once('=') {+ Some(("ID", value)) => id = Some(value.trim_matches('"')),+ Some(("VERSION_ID", value)) => version_id = Some(value.trim_matches('"')),+ _ => {}+ }+ }+ let id = id?;+ Some(match version_id {+ Some(version) => format!("{id} {version}"),+ None => id.to_string(),+ })+}+/// Removes characters from the end of the string if its length is greater than `max_chars` and/// appends "..." to the string. Returns string unchanged if its length is smaller than max_chars.pub fn truncate_and_trailoff(s: &str, max_chars: usize) -> String {@@ -792,6 +815,23 @@ pub fn normalize_path(path: &Path) -> PathBuf {mod tests {use super::*;+ #[test]+ fn test_parse_os_release() {+ let os_release =+ "NAME=\"Ubuntu\"\nID=ubuntu\nVERSION_ID=\"24.04\"\nPRETTY_NAME=\"Ubuntu 24.04 LTS\"\n";+ assert_eq!(+ parse_os_release(os_release),+ Some("ubuntu 24.04".to_string())+ );++ // VERSION_ID may be absent (e.g. rolling releases like Arch).+ assert_eq!(parse_os_release("ID=arch\n"), Some("arch".to_string()));++ // Without an ID there is nothing usable to report.+ assert_eq!(parse_os_release("VERSION_ID=1\n"), None);+ assert_eq!(parse_os_release(""), None);+ }+#[test]fn test_extend_sorted() {let mut vec = vec![];diff --git a/crates/workspace/src/workspace.rs b/crates/workspace/src/workspace.rsindex 1b508163955..f1c9984334a 100644--- a/crates/workspace/src/workspace.rs+++ b/crates/workspace/src/workspace.rs@@ -10435,8 +10435,6 @@ async fn open_remote_project_inner(}let workspace = window.update(cx, |multi_workspace, window, cx| {- telemetry::event!("SSH Project Opened");-let new_workspace = cx.new(|cx| {let mut workspace =Workspace::new(Some(workspace_id), project, app_state.clone(), window, cx);