Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
Merge branch 'main' into randomized-tests-operation-script
Max Brunsfeld5a4fa4b11ebe
diff --cc crates/collab/src/tests/randomized_integration_tests.rsindex 4d87ca9ccc6,b067cac5ff5..34ae96e6656--- a/crates/collab/src/tests/randomized_integration_tests.rs+++ b/crates/collab/src/tests/randomized_integration_tests.rs@@@ -14,20 -13,12 +14,23 @@@ use gpui::{executor::Deterministic, Moduse language::{range_to_lsp, FakeLspAdapter, Language, LanguageConfig, PointUtf16};use lsp::FakeLanguageServer;use parking_lot::Mutex;-use project::{search::SearchQuery, Project};+use project::{search::SearchQuery, Project, ProjectPath};- use rand::prelude::*;+ use rand::{+ distributions::{Alphanumeric, DistString},+ prelude::*,+ };-use std::{env, ffi::OsStr, path::PathBuf, sync::Arc};+use serde::{Deserialize, Serialize};+use std::{+ env,+ ops::Range,+ path::{Path, PathBuf},+ rc::Rc,+ sync::{+ atomic::{AtomicBool, Ordering::SeqCst},+ Arc,+ },+};+use util::ResultExt;#[gpui::test(iterations = 100)]async fn test_random_collaboration(@@@ -888,911 -1102,42 +897,980 @@@ async fn apply_client_operation.await.map_err(|err| anyhow!("search request failed: {:?}", err))});- if rng.lock().gen_bool(0.3) {- log::info!("{}: detaching search request", client.username);+ if detach {+ log::info!("{}: detaching save request", client.username);cx.update(|cx| search.detach_and_log_err(cx));} else {- buffers.extend(search.await?.into_keys());+ search.await?;}}- _ => {- buffer.update(cx, |buffer, cx| {- log::info!(- "{}: updating buffer {} ({:?})",- client.username,- buffer.remote_id(),- buffer.file().unwrap().full_path(cx)- );- if rng.lock().gen_bool(0.7) {- buffer.randomly_edit(&mut *rng.lock(), 5, cx);- } else {- buffer.randomly_undo_redo(&mut *rng.lock(), cx);++ ClientOperation::CreateFsEntry { path, is_dir } => {+ if client.fs.metadata(&path.parent().unwrap()).await?.is_none() {+ return Ok(false);+ }++ log::info!(+ "{}: creating {} at {:?}",+ client.username,+ if is_dir { "dir" } else { "file" },+ path+ );++ if is_dir {+ client.fs.create_dir(&path).await.unwrap();+ } else {+ client+ .fs+ .create_file(&path, Default::default())+ .await+ .unwrap();+ }+ }++++ ClientOperation::WriteGitIndex {++ repo_path,++ contents,++ } => {++ if !client++ .fs++ .metadata(&repo_path)++ .await?++ .map_or(false, |m| m.is_dir)++ {++ return Ok(false);++ }++++ log::info!(++ "{}: writing git index for repo {:?}: {:?}",++ client.username,++ repo_path,++ contents++ );++++ let dot_git_dir = repo_path.join(".git");++ let contents = contents++ .iter()++ .map(|(path, contents)| (path.as_path(), contents.clone()))++ .collect::<Vec<_>>();++ if client.fs.metadata(&dot_git_dir).await?.is_none() {++ client.fs.create_dir(&dot_git_dir).await?;++ }++ client.fs.set_index_for_repo(&dot_git_dir, &contents).await;++ }+ }+ Ok(true)+}++struct TestPlan {+ rng: StdRng,+ replay: bool,+ stored_operations: Vec<(StoredOperation, Arc<AtomicBool>)>,+ max_operations: usize,+ operation_ix: usize,+ users: Vec<UserTestPlan>,+ allow_server_restarts: bool,+ allow_client_reconnection: bool,+ allow_client_disconnection: bool,+}++struct UserTestPlan {+ user_id: UserId,+ username: String,+ next_root_id: usize,+ operation_ix: usize,+ online: bool,+}++#[derive(Clone, Debug, Serialize, Deserialize)]+#[serde(untagged)]+enum StoredOperation {+ Server(Operation),+ Client {+ user_id: UserId,+ operation: ClientOperation,+ },+}++#[derive(Clone, Debug, Serialize, Deserialize)]+enum Operation {+ AddConnection {+ user_id: UserId,+ },+ RemoveConnection {+ user_id: UserId,+ },+ BounceConnection {+ user_id: UserId,+ },+ RestartServer,+ MutateClients {+ user_ids: Vec<UserId>,+ quiesce: bool,+ },+}++#[derive(Clone, Debug, Serialize, Deserialize)]+enum ClientOperation {+ AcceptIncomingCall,+ RejectIncomingCall,+ LeaveCall,+ InviteContactToCall {+ user_id: UserId,+ },+ OpenLocalProject {+ first_root_name: String,+ },+ OpenRemoteProject {+ host_id: UserId,+ first_root_name: String,+ },+ AddWorktreeToProject {+ project_root_name: String,+ new_root_path: PathBuf,+ },+ CloseRemoteProject {+ project_root_name: String,+ },+ OpenBuffer {+ project_root_name: String,+ is_local: bool,+ full_path: PathBuf,+ },+ SearchProject {+ project_root_name: String,+ is_local: bool,+ query: String,+ detach: bool,+ },+ EditBuffer {+ project_root_name: String,+ is_local: bool,+ full_path: PathBuf,+ edits: Vec<(Range<usize>, Arc<str>)>,+ },+ CloseBuffer {+ project_root_name: String,+ is_local: bool,+ full_path: PathBuf,+ },+ SaveBuffer {+ project_root_name: String,+ is_local: bool,+ full_path: PathBuf,+ detach: bool,+ },+ RequestLspDataInBuffer {+ project_root_name: String,+ is_local: bool,+ full_path: PathBuf,+ offset: usize,+ kind: LspRequestKind,+ detach: bool,+ },+ CreateWorktreeEntry {+ project_root_name: String,+ is_local: bool,+ full_path: PathBuf,+ is_dir: bool,+ },+ CreateFsEntry {+ path: PathBuf,+ is_dir: bool,+ },++ WriteGitIndex {++ repo_path: PathBuf,++ contents: Vec<(PathBuf, String)>,++ },+}++#[derive(Clone, Debug, Serialize, Deserialize)]+enum LspRequestKind {+ Rename,+ Completion,+ CodeAction,+ Definition,+ Highlights,+}++impl TestPlan {+ fn new(mut rng: StdRng, users: Vec<UserTestPlan>, max_operations: usize) -> Self {+ Self {+ replay: false,+ allow_server_restarts: rng.gen_bool(0.7),+ allow_client_reconnection: rng.gen_bool(0.7),+ allow_client_disconnection: rng.gen_bool(0.1),+ stored_operations: Vec::new(),+ operation_ix: 0,+ max_operations,+ users,+ rng,+ }+ }++ fn load(&mut self, path: &Path) {+ let json = std::fs::read_to_string(path).unwrap();+ self.replay = true;+ let stored_operations: Vec<StoredOperation> = serde_json::from_str(&json).unwrap();+ self.stored_operations = stored_operations+ .into_iter()+ .map(|operation| (operation, Arc::new(AtomicBool::new(false))))+ .collect()+ }++ fn save(&mut self, path: &Path) {+ // Format each operation as one line+ let mut json = Vec::new();+ json.push(b'[');+ for (operation, skipped) in &self.stored_operations {+ if skipped.load(SeqCst) {+ continue;+ }+ if json.len() > 1 {+ json.push(b',');+ }+ json.extend_from_slice(b"\n ");+ serde_json::to_writer(&mut json, operation).unwrap();+ }+ json.extend_from_slice(b"\n]\n");+ std::fs::write(path, &json).unwrap();+ }++ fn next_server_operation(+ &mut self,+ clients: &[(Rc<TestClient>, TestAppContext)],+ ) -> Option<(Operation, Arc<AtomicBool>)> {+ if self.replay {+ while let Some(stored_operation) = self.stored_operations.get(self.operation_ix) {+ self.operation_ix += 1;+ if let (StoredOperation::Server(operation), skipped) = stored_operation {+ return Some((operation.clone(), skipped.clone()));}- });+ }+ None+ } else {+ let operation = self.generate_server_operation(clients)?;+ let skipped = Arc::new(AtomicBool::new(false));+ self.stored_operations+ .push((StoredOperation::Server(operation.clone()), skipped.clone()));+ Some((operation, skipped))+ }+ }++ fn next_client_operation(+ &mut self,+ client: &TestClient,+ cx: &TestAppContext,+ ) -> Option<(ClientOperation, Arc<AtomicBool>)> {+ let current_user_id = client.current_user_id(cx);+ let user_ix = self+ .users+ .iter()+ .position(|user| user.user_id == current_user_id)+ .unwrap();+ let user_plan = &mut self.users[user_ix];++ if self.replay {+ while let Some(stored_operation) = self.stored_operations.get(user_plan.operation_ix) {+ user_plan.operation_ix += 1;+ if let (StoredOperation::Client { user_id, operation }, skipped) = stored_operation+ {+ if user_id == ¤t_user_id {+ return Some((operation.clone(), skipped.clone()));+ }+ }+ }+ None+ } else {+ let operation = self.generate_client_operation(current_user_id, client, cx)?;+ let skipped = Arc::new(AtomicBool::new(false));+ self.stored_operations.push((+ StoredOperation::Client {+ user_id: current_user_id,+ operation: operation.clone(),+ },+ skipped.clone(),+ ));+ Some((operation, skipped))+ }+ }++ fn generate_server_operation(+ &mut self,+ clients: &[(Rc<TestClient>, TestAppContext)],+ ) -> Option<Operation> {+ if self.operation_ix == self.max_operations {+ return None;+ }++ Some(loop {+ break match self.rng.gen_range(0..100) {+ 0..=29 if clients.len() < self.users.len() => {+ let user = self+ .users+ .iter()+ .filter(|u| !u.online)+ .choose(&mut self.rng)+ .unwrap();+ self.operation_ix += 1;+ Operation::AddConnection {+ user_id: user.user_id,+ }+ }+ 30..=34 if clients.len() > 1 && self.allow_client_disconnection => {+ let (client, cx) = &clients[self.rng.gen_range(0..clients.len())];+ let user_id = client.current_user_id(cx);+ self.operation_ix += 1;+ Operation::RemoveConnection { user_id }+ }+ 35..=39 if clients.len() > 1 && self.allow_client_reconnection => {+ let (client, cx) = &clients[self.rng.gen_range(0..clients.len())];+ let user_id = client.current_user_id(cx);+ self.operation_ix += 1;+ Operation::BounceConnection { user_id }+ }+ 40..=44 if self.allow_server_restarts && clients.len() > 1 => {+ self.operation_ix += 1;+ Operation::RestartServer+ }+ _ if !clients.is_empty() => {+ let count = self+ .rng+ .gen_range(1..10)+ .min(self.max_operations - self.operation_ix);+ let user_ids = (0..count)+ .map(|_| {+ let ix = self.rng.gen_range(0..clients.len());+ let (client, cx) = &clients[ix];+ client.current_user_id(cx)+ })+ .collect();+ Operation::MutateClients {+ user_ids,+ quiesce: self.rng.gen_bool(0.7),+ }+ }+ _ => continue,+ };+ })+ }++ fn generate_client_operation(+ &mut self,+ user_id: UserId,+ client: &TestClient,+ cx: &TestAppContext,+ ) -> Option<ClientOperation> {+ if self.operation_ix == self.max_operations {+ return None;}+++ let executor = cx.background();+ self.operation_ix += 1;+ let call = cx.read(ActiveCall::global);+ Some(loop {+ match self.rng.gen_range(0..100_u32) {+ // Mutate the call+ 0..=29 => {+ // Respond to an incoming call+ if call.read_with(cx, |call, _| call.incoming().borrow().is_some()) {+ break if self.rng.gen_bool(0.7) {+ ClientOperation::AcceptIncomingCall+ } else {+ ClientOperation::RejectIncomingCall+ };+ }++ match self.rng.gen_range(0..100_u32) {+ // Invite a contact to the current call+ 0..=70 => {+ let available_contacts =+ client.user_store.read_with(cx, |user_store, _| {+ user_store+ .contacts()+ .iter()+ .filter(|contact| contact.online && !contact.busy)+ .cloned()+ .collect::<Vec<_>>()+ });+ if !available_contacts.is_empty() {+ let contact = available_contacts.choose(&mut self.rng).unwrap();+ break ClientOperation::InviteContactToCall {+ user_id: UserId(contact.user.id as i32),+ };+ }+ }++ // Leave the current call+ 71.. => {+ if self.allow_client_disconnection+ && call.read_with(cx, |call, _| call.room().is_some())+ {+ break ClientOperation::LeaveCall;+ }+ }+ }+ }++ // Mutate projects+ 30..=59 => match self.rng.gen_range(0..100_u32) {+ // Open a new project+ 0..=70 => {+ // Open a remote project+ if let Some(room) = call.read_with(cx, |call, _| call.room().cloned()) {+ let existing_remote_project_ids = cx.read(|cx| {+ client+ .remote_projects()+ .iter()+ .map(|p| p.read(cx).remote_id().unwrap())+ .collect::<Vec<_>>()+ });+ let new_remote_projects = room.read_with(cx, |room, _| {+ room.remote_participants()+ .values()+ .flat_map(|participant| {+ participant.projects.iter().filter_map(|project| {+ if existing_remote_project_ids.contains(&project.id) {+ None+ } else {+ Some((+ UserId::from_proto(participant.user.id),+ project.worktree_root_names[0].clone(),+ ))+ }+ })+ })+ .collect::<Vec<_>>()+ });+ if !new_remote_projects.is_empty() {+ let (host_id, first_root_name) =+ new_remote_projects.choose(&mut self.rng).unwrap().clone();+ break ClientOperation::OpenRemoteProject {+ host_id,+ first_root_name,+ };+ }+ }+ // Open a local project+ else {+ let first_root_name = self.next_root_dir_name(user_id);+ break ClientOperation::OpenLocalProject { first_root_name };+ }+ }++ // Close a remote project+ 71..=80 => {+ if !client.remote_projects().is_empty() {+ let project = client+ .remote_projects()+ .choose(&mut self.rng)+ .unwrap()+ .clone();+ let first_root_name = root_name_for_project(&project, cx);+ break ClientOperation::CloseRemoteProject {+ project_root_name: first_root_name,+ };+ }+ }++ // Mutate project worktrees+ 81.. => match self.rng.gen_range(0..100_u32) {+ // Add a worktree to a local project+ 0..=50 => {+ let Some(project) = client+ .local_projects()+ .choose(&mut self.rng)+ .cloned() else { continue };+ let project_root_name = root_name_for_project(&project, cx);- let mut paths = cx.background().block(client.fs.paths());++ let mut paths = executor.block(client.fs.paths());+ paths.remove(0);+ let new_root_path = if paths.is_empty() || self.rng.gen() {+ Path::new("/").join(&self.next_root_dir_name(user_id))+ } else {+ paths.choose(&mut self.rng).unwrap().clone()+ };+ break ClientOperation::AddWorktreeToProject {+ project_root_name,+ new_root_path,+ };+ }++ // Add an entry to a worktree+ _ => {+ let Some(project) = choose_random_project(client, &mut self.rng) else { continue };+ let project_root_name = root_name_for_project(&project, cx);+ let is_local = project.read_with(cx, |project, _| project.is_local());+ let worktree = project.read_with(cx, |project, cx| {+ project+ .worktrees(cx)+ .filter(|worktree| {+ let worktree = worktree.read(cx);+ worktree.is_visible()+ && worktree.entries(false).any(|e| e.is_file())+ && worktree.root_entry().map_or(false, |e| e.is_dir())+ })+ .choose(&mut self.rng)+ });+ let Some(worktree) = worktree else { continue };+ let is_dir = self.rng.gen::<bool>();+ let mut full_path =+ worktree.read_with(cx, |w, _| PathBuf::from(w.root_name()));+ full_path.push(gen_file_name(&mut self.rng));+ if !is_dir {+ full_path.set_extension("rs");+ }+ break ClientOperation::CreateWorktreeEntry {+ project_root_name,+ is_local,+ full_path,+ is_dir,+ };+ }+ },+ },++ // Query and mutate buffers- 60..=95 => {++ 60..=90 => {+ let Some(project) = choose_random_project(client, &mut self.rng) else { continue };+ let project_root_name = root_name_for_project(&project, cx);+ let is_local = project.read_with(cx, |project, _| project.is_local());++ match self.rng.gen_range(0..100_u32) {+ // Manipulate an existing buffer+ 0..=70 => {+ let Some(buffer) = client+ .buffers_for_project(&project)+ .iter()+ .choose(&mut self.rng)+ .cloned() else { continue };++ let full_path = buffer+ .read_with(cx, |buffer, cx| buffer.file().unwrap().full_path(cx));++ match self.rng.gen_range(0..100_u32) {+ // Close the buffer+ 0..=15 => {+ break ClientOperation::CloseBuffer {+ project_root_name,+ is_local,+ full_path,+ };+ }+ // Save the buffer+ 16..=29 if buffer.read_with(cx, |b, _| b.is_dirty()) => {+ let detach = self.rng.gen_bool(0.3);+ break ClientOperation::SaveBuffer {+ project_root_name,+ is_local,+ full_path,+ detach,+ };+ }+ // Edit the buffer+ 30..=69 => {+ let edits = buffer.read_with(cx, |buffer, _| {+ buffer.get_random_edits(&mut self.rng, 3)+ });+ break ClientOperation::EditBuffer {+ project_root_name,+ is_local,+ full_path,+ edits,+ };+ }+ // Make an LSP request+ _ => {+ let offset = buffer.read_with(cx, |buffer, _| {+ buffer.clip_offset(+ self.rng.gen_range(0..=buffer.len()),+ language::Bias::Left,+ )+ });+ let detach = self.rng.gen();+ break ClientOperation::RequestLspDataInBuffer {+ project_root_name,+ full_path,+ offset,+ is_local,+ kind: match self.rng.gen_range(0..5_u32) {+ 0 => LspRequestKind::Rename,+ 1 => LspRequestKind::Highlights,+ 2 => LspRequestKind::Definition,+ 3 => LspRequestKind::CodeAction,+ 4.. => LspRequestKind::Completion,+ },+ detach,+ };+ }+ }+ }++ 71..=80 => {+ let query = self.rng.gen_range('a'..='z').to_string();+ let detach = self.rng.gen_bool(0.3);+ break ClientOperation::SearchProject {+ project_root_name,+ is_local,+ query,+ detach,+ };+ }++ // Open a buffer+ 81.. => {+ let worktree = project.read_with(cx, |project, cx| {+ project+ .worktrees(cx)+ .filter(|worktree| {+ let worktree = worktree.read(cx);+ worktree.is_visible()+ && worktree.entries(false).any(|e| e.is_file())+ })+ .choose(&mut self.rng)+ });+ let Some(worktree) = worktree else { continue };+ let full_path = worktree.read_with(cx, |worktree, _| {+ let entry = worktree+ .entries(false)+ .filter(|e| e.is_file())+ .choose(&mut self.rng)+ .unwrap();+ if entry.path.as_ref() == Path::new("") {+ Path::new(worktree.root_name()).into()+ } else {+ Path::new(worktree.root_name()).join(&entry.path)+ }+ });+ break ClientOperation::OpenBuffer {+ project_root_name,+ is_local,+ full_path,+ };+ }+ }+ }+++ // Update a git index++ 91..=95 => {++ let repo_path = executor++ .block(client.fs.directories())++ .choose(&mut self.rng)++ .unwrap()++ .clone();++++ let mut file_paths = executor++ .block(client.fs.files())++ .into_iter()++ .filter(|path| path.starts_with(&repo_path))++ .collect::<Vec<_>>();++ let count = self.rng.gen_range(0..=file_paths.len());++ file_paths.shuffle(&mut self.rng);++ file_paths.truncate(count);++++ let mut contents = Vec::new();++ for abs_child_file_path in &file_paths {++ let child_file_path = abs_child_file_path++ .strip_prefix(&repo_path)++ .unwrap()++ .to_path_buf();++ let new_base = Alphanumeric.sample_string(&mut self.rng, 16);++ contents.push((child_file_path, new_base));++ }++++ break ClientOperation::WriteGitIndex {++ repo_path,++ contents,++ };++ }+++ // Create a file or directory+ 96.. => {+ let is_dir = self.rng.gen::<bool>();+ let mut path = cx+ .background()+ .block(client.fs.directories())+ .choose(&mut self.rng)+ .unwrap()+ .clone();+ path.push(gen_file_name(&mut self.rng));+ if !is_dir {+ path.set_extension("rs");+ }+ break ClientOperation::CreateFsEntry { path, is_dir };+ }+ }+ })}- Ok(())+ fn next_root_dir_name(&mut self, user_id: UserId) -> String {+ let user_ix = self+ .users+ .iter()+ .position(|user| user.user_id == user_id)+ .unwrap();+ let root_id = util::post_inc(&mut self.users[user_ix].next_root_id);+ format!("dir-{user_id}-{root_id}")+ }++ fn user(&mut self, user_id: UserId) -> &mut UserTestPlan {+ let ix = self+ .users+ .iter()+ .position(|user| user.user_id == user_id)+ .unwrap();+ &mut self.users[ix]+ }}-fn choose_random_project(- client: &mut TestClient,- rng: &Mutex<StdRng>,+async fn simulate_client(+ client: Rc<TestClient>,+ mut operation_rx: futures::channel::mpsc::UnboundedReceiver<()>,+ plan: Arc<Mutex<TestPlan>>,+ mut cx: TestAppContext,+) {+ // Setup language server+ let mut language = Language::new(+ LanguageConfig {+ name: "Rust".into(),+ path_suffixes: vec!["rs".to_string()],+ ..Default::default()+ },+ None,+ );+ let _fake_language_servers = language+ .set_fake_lsp_adapter(Arc::new(FakeLspAdapter {+ name: "the-fake-language-server",+ capabilities: lsp::LanguageServer::full_capabilities(),+ initializer: Some(Box::new({+ let plan = plan.clone();+ let fs = client.fs.clone();+ move |fake_server: &mut FakeLanguageServer| {+ fake_server.handle_request::<lsp::request::Completion, _, _>(+ |_, _| async move {+ Ok(Some(lsp::CompletionResponse::Array(vec![+ lsp::CompletionItem {+ text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {+ range: lsp::Range::new(+ lsp::Position::new(0, 0),+ lsp::Position::new(0, 0),+ ),+ new_text: "the-new-text".to_string(),+ })),+ ..Default::default()+ },+ ])))+ },+ );++ fake_server.handle_request::<lsp::request::CodeActionRequest, _, _>(+ |_, _| async move {+ Ok(Some(vec![lsp::CodeActionOrCommand::CodeAction(+ lsp::CodeAction {+ title: "the-code-action".to_string(),+ ..Default::default()+ },+ )]))+ },+ );++ fake_server.handle_request::<lsp::request::PrepareRenameRequest, _, _>(+ |params, _| async move {+ Ok(Some(lsp::PrepareRenameResponse::Range(lsp::Range::new(+ params.position,+ params.position,+ ))))+ },+ );++ fake_server.handle_request::<lsp::request::GotoDefinition, _, _>({+ let fs = fs.clone();+ let plan = plan.clone();+ move |_, _| {+ let fs = fs.clone();+ let plan = plan.clone();+ async move {+ let files = fs.files().await;+ let count = plan.lock().rng.gen_range::<usize, _>(1..3);+ let files = (0..count)+ .map(|_| files.choose(&mut plan.lock().rng).unwrap())+ .collect::<Vec<_>>();+ log::info!("LSP: Returning definitions in files {:?}", &files);+ Ok(Some(lsp::GotoDefinitionResponse::Array(+ files+ .into_iter()+ .map(|file| lsp::Location {+ uri: lsp::Url::from_file_path(file).unwrap(),+ range: Default::default(),+ })+ .collect(),+ )))+ }+ }+ });++ fake_server.handle_request::<lsp::request::DocumentHighlightRequest, _, _>({+ let plan = plan.clone();+ move |_, _| {+ let mut highlights = Vec::new();+ let highlight_count = plan.lock().rng.gen_range(1..=5);+ for _ in 0..highlight_count {+ let start_row = plan.lock().rng.gen_range(0..100);+ let start_column = plan.lock().rng.gen_range(0..100);+ let start = PointUtf16::new(start_row, start_column);+ let end_row = plan.lock().rng.gen_range(0..100);+ let end_column = plan.lock().rng.gen_range(0..100);+ let end = PointUtf16::new(end_row, end_column);+ let range = if start > end { end..start } else { start..end };+ highlights.push(lsp::DocumentHighlight {+ range: range_to_lsp(range.clone()),+ kind: Some(lsp::DocumentHighlightKind::READ),+ });+ }+ highlights.sort_unstable_by_key(|highlight| {+ (highlight.range.start, highlight.range.end)+ });+ async move { Ok(Some(highlights)) }+ }+ });+ }+ })),+ ..Default::default()+ }))+ .await;+ client.language_registry.add(Arc::new(language));++ while operation_rx.next().await.is_some() {+ let Some((operation, skipped)) = plan.lock().next_client_operation(&client, &cx) else { break };+ match apply_client_operation(&client, operation, &mut cx).await {+ Err(error) => {+ log::error!("{} error: {}", client.username, error);+ }+ Ok(applied) => {+ if !applied {+ skipped.store(true, SeqCst);+ }+ }+ }+ cx.background().simulate_random_delay().await;+ }+ log::info!("{}: done", client.username);+}++fn buffer_for_full_path(+ buffers: &HashSet<ModelHandle<language::Buffer>>,+ full_path: &PathBuf,+ cx: &TestAppContext,+) -> Option<ModelHandle<language::Buffer>> {+ buffers+ .iter()+ .find(|buffer| {+ buffer.read_with(cx, |buffer, cx| {+ buffer.file().unwrap().full_path(cx) == *full_path+ })+ })+ .cloned()+}++fn project_for_root_name(+ client: &TestClient,+ root_name: &str,+ cx: &TestAppContext,) -> Option<ModelHandle<Project>> {+ if let Some(ix) = project_ix_for_root_name(&*client.local_projects(), root_name, cx) {+ return Some(client.local_projects()[ix].clone());+ }+ if let Some(ix) = project_ix_for_root_name(&*client.remote_projects(), root_name, cx) {+ return Some(client.remote_projects()[ix].clone());+ }+ None+}++fn project_ix_for_root_name(+ projects: &[ModelHandle<Project>],+ root_name: &str,+ cx: &TestAppContext,+) -> Option<usize> {+ projects.iter().position(|project| {+ project.read_with(cx, |project, cx| {+ let worktree = project.visible_worktrees(cx).next().unwrap();+ worktree.read(cx).root_name() == root_name+ })+ })+}++fn root_name_for_project(project: &ModelHandle<Project>, cx: &TestAppContext) -> String {+ project.read_with(cx, |project, cx| {+ project+ .visible_worktrees(cx)+ .next()+ .unwrap()+ .read(cx)+ .root_name()+ .to_string()+ })+}++fn project_path_for_full_path(+ project: &ModelHandle<Project>,+ full_path: &Path,+ cx: &TestAppContext,+) -> Option<ProjectPath> {+ let mut components = full_path.components();+ let root_name = components.next().unwrap().as_os_str().to_str().unwrap();+ let path = components.as_path().into();+ let worktree_id = project.read_with(cx, |project, cx| {+ project.worktrees(cx).find_map(|worktree| {+ let worktree = worktree.read(cx);+ if worktree.root_name() == root_name {+ Some(worktree.id())+ } else {+ None+ }+ })+ })?;+ Some(ProjectPath { worktree_id, path })+}++async fn ensure_project_shared(+ project: &ModelHandle<Project>,+ client: &TestClient,+ cx: &mut TestAppContext,+) {+ let first_root_name = root_name_for_project(project, cx);+ let active_call = cx.read(ActiveCall::global);+ if active_call.read_with(cx, |call, _| call.room().is_some())+ && project.read_with(cx, |project, _| project.is_local() && !project.is_shared())+ {+ match active_call+ .update(cx, |call, cx| call.share_project(project.clone(), cx))+ .await+ {+ Ok(project_id) => {+ log::info!(+ "{}: shared project {} with id {}",+ client.username,+ first_root_name,+ project_id+ );+ }+ Err(error) => {+ log::error!(+ "{}: error sharing project {}: {:?}",+ client.username,+ first_root_name,+ error+ );+ }+ }+ }+}++fn choose_random_project(client: &TestClient, rng: &mut StdRng) -> Option<ModelHandle<Project>> {client- .local_projects+ .local_projects().iter()- .chain(&client.remote_projects)- .choose(&mut *rng.lock())+ .chain(client.remote_projects().iter())+ .choose(rng).cloned()}