1use anyhow::{anyhow, Result};
2use fs::Fs;
3use gpui::{AppContext, AsyncAppContext, Context, Model, ModelContext};
4use http_client::HttpClient;
5use language::{proto::serialize_operation, Buffer, BufferEvent, LanguageRegistry};
6use node_runtime::NodeRuntime;
7use project::{
8 buffer_store::{BufferStore, BufferStoreEvent},
9 project_settings::SettingsObserver,
10 search::SearchQuery,
11 task_store::TaskStore,
12 worktree_store::WorktreeStore,
13 LspStore, LspStoreEvent, PrettierStore, ProjectPath, WorktreeId,
14};
15use remote::ssh_session::ChannelClient;
16use rpc::{
17 proto::{self, SSH_PEER_ID, SSH_PROJECT_ID},
18 AnyProtoClient, TypedEnvelope,
19};
20
21use settings::initial_server_settings_content;
22use smol::stream::StreamExt;
23use std::{
24 path::{Path, PathBuf},
25 sync::{atomic::AtomicUsize, Arc},
26};
27use util::ResultExt;
28use worktree::Worktree;
29
30pub struct HeadlessProject {
31 pub fs: Arc<dyn Fs>,
32 pub session: AnyProtoClient,
33 pub worktree_store: Model<WorktreeStore>,
34 pub buffer_store: Model<BufferStore>,
35 pub lsp_store: Model<LspStore>,
36 pub task_store: Model<TaskStore>,
37 pub settings_observer: Model<SettingsObserver>,
38 pub next_entry_id: Arc<AtomicUsize>,
39 pub languages: Arc<LanguageRegistry>,
40}
41
42pub struct HeadlessAppState {
43 pub session: Arc<ChannelClient>,
44 pub fs: Arc<dyn Fs>,
45 pub http_client: Arc<dyn HttpClient>,
46 pub node_runtime: NodeRuntime,
47 pub languages: Arc<LanguageRegistry>,
48}
49
50impl HeadlessProject {
51 pub fn init(cx: &mut AppContext) {
52 settings::init(cx);
53 language::init(cx);
54 project::Project::init_settings(cx);
55 }
56
57 pub fn new(
58 HeadlessAppState {
59 session,
60 fs,
61 http_client,
62 node_runtime,
63 languages,
64 }: HeadlessAppState,
65 cx: &mut ModelContext<Self>,
66 ) -> Self {
67 languages::init(languages.clone(), node_runtime.clone(), cx);
68
69 let worktree_store = cx.new_model(|cx| {
70 let mut store = WorktreeStore::local(true, fs.clone());
71 store.shared(SSH_PROJECT_ID, session.clone().into(), cx);
72 store
73 });
74 let buffer_store = cx.new_model(|cx| {
75 let mut buffer_store = BufferStore::local(worktree_store.clone(), cx);
76 buffer_store.shared(SSH_PROJECT_ID, session.clone().into(), cx);
77 buffer_store
78 });
79 let prettier_store = cx.new_model(|cx| {
80 PrettierStore::new(
81 node_runtime,
82 fs.clone(),
83 languages.clone(),
84 worktree_store.clone(),
85 cx,
86 )
87 });
88
89 let environment = project::ProjectEnvironment::new(&worktree_store, None, cx);
90 let task_store = cx.new_model(|cx| {
91 let mut task_store = TaskStore::local(
92 fs.clone(),
93 buffer_store.downgrade(),
94 worktree_store.clone(),
95 environment.clone(),
96 cx,
97 );
98 task_store.shared(SSH_PROJECT_ID, session.clone().into(), cx);
99 task_store
100 });
101 let settings_observer = cx.new_model(|cx| {
102 let mut observer = SettingsObserver::new_local(
103 fs.clone(),
104 worktree_store.clone(),
105 task_store.clone(),
106 cx,
107 );
108 observer.shared(SSH_PROJECT_ID, session.clone().into(), cx);
109 observer
110 });
111 let lsp_store = cx.new_model(|cx| {
112 let mut lsp_store = LspStore::new_local(
113 buffer_store.clone(),
114 worktree_store.clone(),
115 prettier_store.clone(),
116 environment,
117 languages.clone(),
118 http_client,
119 fs.clone(),
120 cx,
121 );
122 lsp_store.shared(SSH_PROJECT_ID, session.clone().into(), cx);
123 lsp_store
124 });
125
126 cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
127
128 cx.subscribe(
129 &buffer_store,
130 |_this, _buffer_store, event, cx| match event {
131 BufferStoreEvent::BufferAdded(buffer) => {
132 cx.subscribe(buffer, Self::on_buffer_event).detach();
133 }
134 _ => {}
135 },
136 )
137 .detach();
138
139 let client: AnyProtoClient = session.clone().into();
140
141 session.subscribe_to_entity(SSH_PROJECT_ID, &worktree_store);
142 session.subscribe_to_entity(SSH_PROJECT_ID, &buffer_store);
143 session.subscribe_to_entity(SSH_PROJECT_ID, &cx.handle());
144 session.subscribe_to_entity(SSH_PROJECT_ID, &lsp_store);
145 session.subscribe_to_entity(SSH_PROJECT_ID, &task_store);
146 session.subscribe_to_entity(SSH_PROJECT_ID, &settings_observer);
147
148 client.add_request_handler(cx.weak_model(), Self::handle_list_remote_directory);
149 client.add_request_handler(cx.weak_model(), Self::handle_check_file_exists);
150 client.add_request_handler(cx.weak_model(), Self::handle_shutdown_remote_server);
151 client.add_request_handler(cx.weak_model(), Self::handle_ping);
152
153 client.add_model_request_handler(Self::handle_add_worktree);
154 client.add_request_handler(cx.weak_model(), Self::handle_remove_worktree);
155
156 client.add_model_request_handler(Self::handle_open_buffer_by_path);
157 client.add_model_request_handler(Self::handle_find_search_candidates);
158 client.add_model_request_handler(Self::handle_open_server_settings);
159
160 client.add_model_request_handler(BufferStore::handle_update_buffer);
161 client.add_model_message_handler(BufferStore::handle_close_buffer);
162
163 BufferStore::init(&client);
164 WorktreeStore::init(&client);
165 SettingsObserver::init(&client);
166 LspStore::init(&client);
167 TaskStore::init(Some(&client));
168
169 HeadlessProject {
170 session: client,
171 settings_observer,
172 fs,
173 worktree_store,
174 buffer_store,
175 lsp_store,
176 task_store,
177 next_entry_id: Default::default(),
178 languages,
179 }
180 }
181
182 fn on_buffer_event(
183 &mut self,
184 buffer: Model<Buffer>,
185 event: &BufferEvent,
186 cx: &mut ModelContext<Self>,
187 ) {
188 match event {
189 BufferEvent::Operation {
190 operation,
191 is_local: true,
192 } => cx
193 .background_executor()
194 .spawn(self.session.request(proto::UpdateBuffer {
195 project_id: SSH_PROJECT_ID,
196 buffer_id: buffer.read(cx).remote_id().to_proto(),
197 operations: vec![serialize_operation(operation)],
198 }))
199 .detach(),
200 _ => {}
201 }
202 }
203
204 fn on_lsp_store_event(
205 &mut self,
206 _lsp_store: Model<LspStore>,
207 event: &LspStoreEvent,
208 _cx: &mut ModelContext<Self>,
209 ) {
210 match event {
211 LspStoreEvent::LanguageServerUpdate {
212 language_server_id,
213 message,
214 } => {
215 self.session
216 .send(proto::UpdateLanguageServer {
217 project_id: SSH_PROJECT_ID,
218 language_server_id: language_server_id.to_proto(),
219 variant: Some(message.clone()),
220 })
221 .log_err();
222 }
223 LspStoreEvent::Notification(message) => {
224 self.session
225 .send(proto::Toast {
226 project_id: SSH_PROJECT_ID,
227 notification_id: "lsp".to_string(),
228 message: message.clone(),
229 })
230 .log_err();
231 }
232 LspStoreEvent::LanguageServerLog(language_server_id, log_type, message) => {
233 self.session
234 .send(proto::LanguageServerLog {
235 project_id: SSH_PROJECT_ID,
236 language_server_id: language_server_id.to_proto(),
237 message: message.clone(),
238 log_type: Some(log_type.to_proto()),
239 })
240 .log_err();
241 }
242 _ => {}
243 }
244 }
245
246 pub async fn handle_add_worktree(
247 this: Model<Self>,
248 message: TypedEnvelope<proto::AddWorktree>,
249 mut cx: AsyncAppContext,
250 ) -> Result<proto::AddWorktreeResponse> {
251 use client::ErrorCodeExt;
252 let path = shellexpand::tilde(&message.payload.path).to_string();
253
254 let fs = this.read_with(&mut cx, |this, _| this.fs.clone())?;
255 let path = PathBuf::from(path);
256
257 let canonicalized = match fs.canonicalize(&path).await {
258 Ok(path) => path,
259 Err(e) => {
260 let mut parent = path
261 .parent()
262 .ok_or(e)
263 .map_err(|_| anyhow!("{:?} does not exist", path))?;
264 if parent == Path::new("") {
265 parent = util::paths::home_dir();
266 }
267 let parent = fs.canonicalize(parent).await.map_err(|_| {
268 anyhow!(proto::ErrorCode::DevServerProjectPathDoesNotExist
269 .with_tag("path", &path.to_string_lossy().as_ref()))
270 })?;
271 parent.join(path.file_name().unwrap())
272 }
273 };
274
275 let worktree = this
276 .update(&mut cx.clone(), |this, _| {
277 Worktree::local(
278 Arc::from(canonicalized),
279 message.payload.visible,
280 this.fs.clone(),
281 this.next_entry_id.clone(),
282 &mut cx,
283 )
284 })?
285 .await?;
286
287 let response = this.update(&mut cx, |_, cx| {
288 worktree.update(cx, |worktree, _| proto::AddWorktreeResponse {
289 worktree_id: worktree.id().to_proto(),
290 })
291 })?;
292
293 // We spawn this asynchronously, so that we can send the response back
294 // *before* `worktree_store.add()` can send out UpdateProject requests
295 // to the client about the new worktree.
296 //
297 // That lets the client manage the reference/handles of the newly-added
298 // worktree, before getting interrupted by an UpdateProject request.
299 //
300 // This fixes the problem of the client sending the AddWorktree request,
301 // headless project sending out a project update, client receiving it
302 // and immediately dropping the reference of the new client, causing it
303 // to be dropped on the headless project, and the client only then
304 // receiving a response to AddWorktree.
305 cx.spawn(|mut cx| async move {
306 this.update(&mut cx, |this, cx| {
307 this.worktree_store.update(cx, |worktree_store, cx| {
308 worktree_store.add(&worktree, cx);
309 });
310 })
311 .log_err();
312 })
313 .detach();
314
315 Ok(response)
316 }
317
318 pub async fn handle_remove_worktree(
319 this: Model<Self>,
320 envelope: TypedEnvelope<proto::RemoveWorktree>,
321 mut cx: AsyncAppContext,
322 ) -> Result<proto::Ack> {
323 let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
324 this.update(&mut cx, |this, cx| {
325 this.worktree_store.update(cx, |worktree_store, cx| {
326 worktree_store.remove_worktree(worktree_id, cx);
327 });
328 })?;
329 Ok(proto::Ack {})
330 }
331
332 pub async fn handle_open_buffer_by_path(
333 this: Model<Self>,
334 message: TypedEnvelope<proto::OpenBufferByPath>,
335 mut cx: AsyncAppContext,
336 ) -> Result<proto::OpenBufferResponse> {
337 let worktree_id = WorktreeId::from_proto(message.payload.worktree_id);
338 let (buffer_store, buffer) = this.update(&mut cx, |this, cx| {
339 let buffer_store = this.buffer_store.clone();
340 let buffer = this.buffer_store.update(cx, |buffer_store, cx| {
341 buffer_store.open_buffer(
342 ProjectPath {
343 worktree_id,
344 path: PathBuf::from(message.payload.path).into(),
345 },
346 cx,
347 )
348 });
349 anyhow::Ok((buffer_store, buffer))
350 })??;
351
352 let buffer = buffer.await?;
353 let buffer_id = buffer.read_with(&cx, |b, _| b.remote_id())?;
354 buffer_store.update(&mut cx, |buffer_store, cx| {
355 buffer_store
356 .create_buffer_for_peer(&buffer, SSH_PEER_ID, cx)
357 .detach_and_log_err(cx);
358 })?;
359
360 Ok(proto::OpenBufferResponse {
361 buffer_id: buffer_id.to_proto(),
362 })
363 }
364
365 pub async fn handle_open_server_settings(
366 this: Model<Self>,
367 _: TypedEnvelope<proto::OpenServerSettings>,
368 mut cx: AsyncAppContext,
369 ) -> Result<proto::OpenBufferResponse> {
370 let settings_path = paths::settings_file();
371 let (worktree, path) = this
372 .update(&mut cx, |this, cx| {
373 this.worktree_store.update(cx, |worktree_store, cx| {
374 worktree_store.find_or_create_worktree(settings_path, false, cx)
375 })
376 })?
377 .await?;
378
379 let (buffer, buffer_store) = this.update(&mut cx, |this, cx| {
380 let buffer = this.buffer_store.update(cx, |buffer_store, cx| {
381 buffer_store.open_buffer(
382 ProjectPath {
383 worktree_id: worktree.read(cx).id(),
384 path: path.into(),
385 },
386 cx,
387 )
388 });
389
390 (buffer, this.buffer_store.clone())
391 })?;
392
393 let buffer = buffer.await?;
394
395 let buffer_id = cx.update(|cx| {
396 if buffer.read(cx).is_empty() {
397 buffer.update(cx, |buffer, cx| {
398 buffer.edit([(0..0, initial_server_settings_content())], None, cx)
399 });
400 }
401
402 let buffer_id = buffer.read_with(cx, |b, _| b.remote_id());
403
404 buffer_store.update(cx, |buffer_store, cx| {
405 buffer_store
406 .create_buffer_for_peer(&buffer, SSH_PEER_ID, cx)
407 .detach_and_log_err(cx);
408 });
409
410 buffer_id
411 })?;
412
413 Ok(proto::OpenBufferResponse {
414 buffer_id: buffer_id.to_proto(),
415 })
416 }
417
418 pub async fn handle_find_search_candidates(
419 this: Model<Self>,
420 envelope: TypedEnvelope<proto::FindSearchCandidates>,
421 mut cx: AsyncAppContext,
422 ) -> Result<proto::FindSearchCandidatesResponse> {
423 let message = envelope.payload;
424 let query = SearchQuery::from_proto(
425 message
426 .query
427 .ok_or_else(|| anyhow!("missing query field"))?,
428 )?;
429 let mut results = this.update(&mut cx, |this, cx| {
430 this.buffer_store.update(cx, |buffer_store, cx| {
431 buffer_store.find_search_candidates(&query, message.limit as _, this.fs.clone(), cx)
432 })
433 })?;
434
435 let mut response = proto::FindSearchCandidatesResponse {
436 buffer_ids: Vec::new(),
437 };
438
439 let buffer_store = this.read_with(&cx, |this, _| this.buffer_store.clone())?;
440
441 while let Some(buffer) = results.next().await {
442 let buffer_id = buffer.update(&mut cx, |this, _| this.remote_id())?;
443 response.buffer_ids.push(buffer_id.to_proto());
444 buffer_store
445 .update(&mut cx, |buffer_store, cx| {
446 buffer_store.create_buffer_for_peer(&buffer, SSH_PEER_ID, cx)
447 })?
448 .await?;
449 }
450
451 Ok(response)
452 }
453
454 pub async fn handle_list_remote_directory(
455 this: Model<Self>,
456 envelope: TypedEnvelope<proto::ListRemoteDirectory>,
457 cx: AsyncAppContext,
458 ) -> Result<proto::ListRemoteDirectoryResponse> {
459 let expanded = shellexpand::tilde(&envelope.payload.path).to_string();
460 let fs = cx.read_model(&this, |this, _| this.fs.clone())?;
461
462 let mut entries = Vec::new();
463 let mut response = fs.read_dir(Path::new(&expanded)).await?;
464 while let Some(path) = response.next().await {
465 if let Some(file_name) = path?.file_name() {
466 entries.push(file_name.to_string_lossy().to_string());
467 }
468 }
469 Ok(proto::ListRemoteDirectoryResponse { entries })
470 }
471
472 pub async fn handle_check_file_exists(
473 this: Model<Self>,
474 envelope: TypedEnvelope<proto::CheckFileExists>,
475 cx: AsyncAppContext,
476 ) -> Result<proto::CheckFileExistsResponse> {
477 let fs = cx.read_model(&this, |this, _| this.fs.clone())?;
478 let expanded = shellexpand::tilde(&envelope.payload.path).to_string();
479
480 let exists = fs.is_file(&PathBuf::from(expanded.clone())).await;
481
482 Ok(proto::CheckFileExistsResponse {
483 exists,
484 path: expanded,
485 })
486 }
487
488 pub async fn handle_shutdown_remote_server(
489 _this: Model<Self>,
490 _envelope: TypedEnvelope<proto::ShutdownRemoteServer>,
491 cx: AsyncAppContext,
492 ) -> Result<proto::Ack> {
493 cx.spawn(|cx| async move {
494 cx.update(|cx| {
495 // TODO: This is a hack, because in a headless project, shutdown isn't executed
496 // when calling quit, but it should be.
497 cx.shutdown();
498 cx.quit();
499 })
500 })
501 .detach();
502
503 Ok(proto::Ack {})
504 }
505
506 pub async fn handle_ping(
507 _this: Model<Self>,
508 _envelope: TypedEnvelope<proto::Ping>,
509 _cx: AsyncAppContext,
510 ) -> Result<proto::Ack> {
511 log::debug!("Received ping from client");
512 Ok(proto::Ack {})
513 }
514}