terminal_tool.rs

  1use crate::schema::json_schema_for;
  2use anyhow::{Context as _, Result, anyhow};
  3use assistant_tool::{ActionLog, Tool, ToolCard, ToolResult, ToolUseStatus};
  4use futures::{FutureExt as _, future::Shared};
  5use gpui::{
  6    AnyWindowHandle, App, AppContext, Empty, Entity, EntityId, Task, TextStyleRefinement,
  7    WeakEntity, Window,
  8};
  9use language::LineEnding;
 10use language_model::{LanguageModel, LanguageModelRequest, LanguageModelToolSchemaFormat};
 11use markdown::{Markdown, MarkdownElement, MarkdownStyle};
 12use portable_pty::{CommandBuilder, PtySize, native_pty_system};
 13use project::{Project, terminals::TerminalKind};
 14use schemars::JsonSchema;
 15use serde::{Deserialize, Serialize};
 16use settings::Settings;
 17use std::{
 18    env,
 19    path::{Path, PathBuf},
 20    process::ExitStatus,
 21    sync::Arc,
 22    time::{Duration, Instant},
 23};
 24use terminal_view::TerminalView;
 25use theme::ThemeSettings;
 26use ui::{Disclosure, Tooltip, prelude::*};
 27use util::{
 28    get_system_shell, markdown::MarkdownInlineCode, size::format_file_size,
 29    time::duration_alt_display,
 30};
 31use workspace::Workspace;
 32
 33const COMMAND_OUTPUT_LIMIT: usize = 16 * 1024;
 34
 35#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
 36pub struct TerminalToolInput {
 37    /// The one-liner command to execute.
 38    command: String,
 39    /// Working directory for the command. This must be one of the root directories of the project.
 40    cd: String,
 41}
 42
 43pub struct TerminalTool {
 44    determine_shell: Shared<Task<String>>,
 45}
 46
 47impl TerminalTool {
 48    pub const NAME: &str = "terminal";
 49
 50    pub(crate) fn new(cx: &mut App) -> Self {
 51        let determine_shell = cx.background_spawn(async move {
 52            if cfg!(windows) {
 53                return get_system_shell();
 54            }
 55
 56            if which::which("bash").is_ok() {
 57                log::info!("agent selected bash for terminal tool");
 58                "bash".into()
 59            } else {
 60                let shell = get_system_shell();
 61                log::info!("agent selected {shell} for terminal tool");
 62                shell
 63            }
 64        });
 65        Self {
 66            determine_shell: determine_shell.shared(),
 67        }
 68    }
 69}
 70
 71impl Tool for TerminalTool {
 72    fn name(&self) -> String {
 73        Self::NAME.to_string()
 74    }
 75
 76    fn needs_confirmation(&self, _: &serde_json::Value, _: &App) -> bool {
 77        true
 78    }
 79
 80    fn description(&self) -> String {
 81        include_str!("./terminal_tool/description.md").to_string()
 82    }
 83
 84    fn icon(&self) -> IconName {
 85        IconName::Terminal
 86    }
 87
 88    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
 89        json_schema_for::<TerminalToolInput>(format)
 90    }
 91
 92    fn ui_text(&self, input: &serde_json::Value) -> String {
 93        match serde_json::from_value::<TerminalToolInput>(input.clone()) {
 94            Ok(input) => {
 95                let mut lines = input.command.lines();
 96                let first_line = lines.next().unwrap_or_default();
 97                let remaining_line_count = lines.count();
 98                match remaining_line_count {
 99                    0 => MarkdownInlineCode(&first_line).to_string(),
100                    1 => MarkdownInlineCode(&format!(
101                        "{} - {} more line",
102                        first_line, remaining_line_count
103                    ))
104                    .to_string(),
105                    n => MarkdownInlineCode(&format!("{} - {} more lines", first_line, n))
106                        .to_string(),
107                }
108            }
109            Err(_) => "Run terminal command".to_string(),
110        }
111    }
112
113    fn run(
114        self: Arc<Self>,
115        input: serde_json::Value,
116        _request: Arc<LanguageModelRequest>,
117        project: Entity<Project>,
118        _action_log: Entity<ActionLog>,
119        _model: Arc<dyn LanguageModel>,
120        window: Option<AnyWindowHandle>,
121        cx: &mut App,
122    ) -> ToolResult {
123        let input: TerminalToolInput = match serde_json::from_value(input) {
124            Ok(input) => input,
125            Err(err) => return Task::ready(Err(anyhow!(err))).into(),
126        };
127
128        let working_dir = match working_dir(&input, &project, cx) {
129            Ok(dir) => dir,
130            Err(err) => return Task::ready(Err(err)).into(),
131        };
132        let program = self.determine_shell.clone();
133        let command = if cfg!(windows) {
134            format!("$null | & {{{}}}", input.command.replace("\"", "'"))
135        } else if let Some(cwd) = working_dir
136            .as_ref()
137            .and_then(|cwd| cwd.as_os_str().to_str())
138        {
139            // Make sure once we're *inside* the shell, we cd into `cwd`
140            format!("(cd {cwd}; {}) </dev/null", input.command)
141        } else {
142            format!("({}) </dev/null", input.command)
143        };
144        let args = vec!["-c".into(), command];
145
146        let cwd = working_dir.clone();
147        let env = match &working_dir {
148            Some(dir) => project.update(cx, |project, cx| {
149                project.directory_environment(dir.as_path().into(), cx)
150            }),
151            None => Task::ready(None).shared(),
152        };
153
154        let env = cx.spawn(async move |_| {
155            let mut env = env.await.unwrap_or_default();
156            if cfg!(unix) {
157                env.insert("PAGER".into(), "cat".into());
158            }
159            env
160        });
161
162        let Some(window) = window else {
163            // Headless setup, a test or eval. Our terminal subsystem requires a workspace,
164            // so bypass it and provide a convincing imitation using a pty.
165            let task = cx.background_spawn(async move {
166                let env = env.await;
167                let pty_system = native_pty_system();
168                let program = program.await;
169                let mut cmd = CommandBuilder::new(program);
170                cmd.args(args);
171                for (k, v) in env {
172                    cmd.env(k, v);
173                }
174                if let Some(cwd) = cwd {
175                    cmd.cwd(cwd);
176                }
177                let pair = pty_system.openpty(PtySize {
178                    rows: 24,
179                    cols: 80,
180                    ..Default::default()
181                })?;
182                let mut child = pair.slave.spawn_command(cmd)?;
183                let mut reader = pair.master.try_clone_reader()?;
184                drop(pair);
185                let mut content = Vec::new();
186                reader.read_to_end(&mut content)?;
187                let mut content = String::from_utf8(content)?;
188                // Massage the pty output a bit to try to match what the terminal codepath gives us
189                LineEnding::normalize(&mut content);
190                content = content
191                    .chars()
192                    .filter(|c| c.is_ascii_whitespace() || !c.is_ascii_control())
193                    .collect();
194                let content = content.trim_start().trim_start_matches("^D");
195                let exit_status = child.wait()?;
196                let (processed_content, _) =
197                    process_content(content, &input.command, Some(exit_status));
198                Ok(processed_content.into())
199            });
200            return ToolResult {
201                output: task,
202                card: None,
203            };
204        };
205
206        let terminal = cx.spawn({
207            let project = project.downgrade();
208            async move |cx| {
209                let program = program.await;
210                let env = env.await;
211                let terminal = project
212                    .update(cx, |project, cx| {
213                        project.create_terminal(
214                            TerminalKind::Task(task::SpawnInTerminal {
215                                command: program,
216                                args,
217                                cwd,
218                                env,
219                                ..Default::default()
220                            }),
221                            window,
222                            cx,
223                        )
224                    })?
225                    .await;
226                terminal
227            }
228        });
229
230        let command_markdown = cx.new(|cx| {
231            Markdown::new(
232                format!("```bash\n{}\n```", input.command).into(),
233                None,
234                None,
235                cx,
236            )
237        });
238
239        let card = cx.new(|cx| {
240            TerminalToolCard::new(
241                command_markdown.clone(),
242                working_dir.clone(),
243                cx.entity_id(),
244            )
245        });
246
247        let output = cx.spawn({
248            let card = card.clone();
249            async move |cx| {
250                let terminal = terminal.await?;
251                let workspace = window
252                    .downcast::<Workspace>()
253                    .and_then(|handle| handle.entity(cx).ok())
254                    .context("no workspace entity in root of window")?;
255
256                let terminal_view = window.update(cx, |_, window, cx| {
257                    cx.new(|cx| {
258                        TerminalView::new(
259                            terminal.clone(),
260                            workspace.downgrade(),
261                            None,
262                            project.downgrade(),
263                            true,
264                            window,
265                            cx,
266                        )
267                    })
268                })?;
269
270                let _ = card.update(cx, |card, _| {
271                    card.terminal = Some(terminal_view.clone());
272                    card.start_instant = Instant::now();
273                });
274
275                let exit_status = terminal
276                    .update(cx, |terminal, cx| terminal.wait_for_completed_task(cx))?
277                    .await;
278                let (content, content_line_count) = terminal.read_with(cx, |terminal, _| {
279                    (terminal.get_content(), terminal.total_lines())
280                })?;
281
282                let previous_len = content.len();
283                let (processed_content, finished_with_empty_output) = process_content(
284                    &content,
285                    &input.command,
286                    exit_status.map(portable_pty::ExitStatus::from),
287                );
288
289                let _ = card.update(cx, |card, _| {
290                    card.command_finished = true;
291                    card.exit_status = exit_status;
292                    card.was_content_truncated = processed_content.len() < previous_len;
293                    card.original_content_len = previous_len;
294                    card.content_line_count = content_line_count;
295                    card.finished_with_empty_output = finished_with_empty_output;
296                    card.elapsed_time = Some(card.start_instant.elapsed());
297                });
298
299                Ok(processed_content.into())
300            }
301        });
302
303        ToolResult {
304            output,
305            card: Some(card.into()),
306        }
307    }
308}
309
310fn process_content(
311    content: &str,
312    command: &str,
313    exit_status: Option<portable_pty::ExitStatus>,
314) -> (String, bool) {
315    let should_truncate = content.len() > COMMAND_OUTPUT_LIMIT;
316
317    let content = if should_truncate {
318        let mut end_ix = COMMAND_OUTPUT_LIMIT.min(content.len());
319        while !content.is_char_boundary(end_ix) {
320            end_ix -= 1;
321        }
322        // Don't truncate mid-line, clear the remainder of the last line
323        end_ix = content[..end_ix].rfind('\n').unwrap_or(end_ix);
324        &content[..end_ix]
325    } else {
326        content
327    };
328    let content = content.trim();
329    let is_empty = content.is_empty();
330    let content = format!("```\n{content}\n```");
331    let content = if should_truncate {
332        format!(
333            "Command output too long. The first {} bytes:\n\n{content}",
334            content.len(),
335        )
336    } else {
337        content
338    };
339
340    let content = match exit_status {
341        Some(exit_status) if exit_status.success() => {
342            if is_empty {
343                "Command executed successfully.".to_string()
344            } else {
345                content.to_string()
346            }
347        }
348        Some(exit_status) => {
349            if is_empty {
350                format!(
351                    "Command \"{command}\" failed with exit code {}.",
352                    exit_status.exit_code()
353                )
354            } else {
355                format!(
356                    "Command \"{command}\" failed with exit code {}.\n\n{content}",
357                    exit_status.exit_code()
358                )
359            }
360        }
361        None => {
362            format!(
363                "Command failed or was interrupted.\nPartial output captured:\n\n{}",
364                content,
365            )
366        }
367    };
368    (content, is_empty)
369}
370
371fn working_dir(
372    input: &TerminalToolInput,
373    project: &Entity<Project>,
374    cx: &mut App,
375) -> Result<Option<PathBuf>> {
376    let project = project.read(cx);
377    let cd = &input.cd;
378
379    if cd == "." || cd == "" {
380        // Accept "." or "" as meaning "the one worktree" if we only have one worktree.
381        let mut worktrees = project.worktrees(cx);
382
383        match worktrees.next() {
384            Some(worktree) => {
385                anyhow::ensure!(
386                    worktrees.next().is_none(),
387                    "'.' is ambiguous in multi-root workspaces. Please specify a root directory explicitly.",
388                );
389                Ok(Some(worktree.read(cx).abs_path().to_path_buf()))
390            }
391            None => Ok(None),
392        }
393    } else {
394        let input_path = Path::new(cd);
395
396        if input_path.is_absolute() {
397            // Absolute paths are allowed, but only if they're in one of the project's worktrees.
398            if project
399                .worktrees(cx)
400                .any(|worktree| input_path.starts_with(&worktree.read(cx).abs_path()))
401            {
402                return Ok(Some(input_path.into()));
403            }
404        } else {
405            if let Some(worktree) = project.worktree_for_root_name(cd, cx) {
406                return Ok(Some(worktree.read(cx).abs_path().to_path_buf()));
407            }
408        }
409
410        anyhow::bail!("`cd` directory {cd:?} was not in any of the project's worktrees.");
411    }
412}
413
414struct TerminalToolCard {
415    input_command: Entity<Markdown>,
416    working_dir: Option<PathBuf>,
417    entity_id: EntityId,
418    exit_status: Option<ExitStatus>,
419    terminal: Option<Entity<TerminalView>>,
420    command_finished: bool,
421    was_content_truncated: bool,
422    finished_with_empty_output: bool,
423    content_line_count: usize,
424    original_content_len: usize,
425    preview_expanded: bool,
426    start_instant: Instant,
427    elapsed_time: Option<Duration>,
428}
429
430impl TerminalToolCard {
431    pub fn new(
432        input_command: Entity<Markdown>,
433        working_dir: Option<PathBuf>,
434        entity_id: EntityId,
435    ) -> Self {
436        Self {
437            input_command,
438            working_dir,
439            entity_id,
440            exit_status: None,
441            terminal: None,
442            command_finished: false,
443            was_content_truncated: false,
444            finished_with_empty_output: false,
445            original_content_len: 0,
446            content_line_count: 0,
447            preview_expanded: true,
448            start_instant: Instant::now(),
449            elapsed_time: None,
450        }
451    }
452}
453
454impl ToolCard for TerminalToolCard {
455    fn render(
456        &mut self,
457        status: &ToolUseStatus,
458        window: &mut Window,
459        _workspace: WeakEntity<Workspace>,
460        cx: &mut Context<Self>,
461    ) -> impl IntoElement {
462        let Some(terminal) = self.terminal.as_ref() else {
463            return Empty.into_any();
464        };
465
466        let tool_failed = matches!(status, ToolUseStatus::Error(_));
467
468        let command_failed =
469            self.command_finished && self.exit_status.is_none_or(|code| !code.success());
470
471        if (tool_failed || command_failed) && self.elapsed_time.is_none() {
472            self.elapsed_time = Some(self.start_instant.elapsed());
473        }
474        let time_elapsed = self
475            .elapsed_time
476            .unwrap_or_else(|| self.start_instant.elapsed());
477        let should_hide_terminal = tool_failed || self.finished_with_empty_output;
478
479        let header_bg = cx
480            .theme()
481            .colors()
482            .element_background
483            .blend(cx.theme().colors().editor_foreground.opacity(0.025));
484
485        let border_color = cx.theme().colors().border.opacity(0.6);
486
487        let path = self
488            .working_dir
489            .as_ref()
490            .cloned()
491            .or_else(|| env::current_dir().ok())
492            .map(|path| format!("{}", path.display()))
493            .unwrap_or_else(|| "current directory".to_string());
494
495        let header = h_flex()
496            .flex_none()
497            .gap_1()
498            .justify_between()
499            .rounded_t_md()
500            .child(
501                div()
502                    .id(("command-target-path", self.entity_id))
503                    .w_full()
504                    .max_w_full()
505                    .overflow_x_scroll()
506                    .child(
507                        Label::new(path)
508                            .buffer_font(cx)
509                            .size(LabelSize::XSmall)
510                            .color(Color::Muted),
511                    ),
512            )
513            .when(self.was_content_truncated, |header| {
514                let tooltip = if self.content_line_count + 10 > terminal::MAX_SCROLL_HISTORY_LINES {
515                    "Output exceeded terminal max lines and was \
516                        truncated, the model received the first 16 KB."
517                        .to_string()
518                } else {
519                    format!(
520                        "Output is {} long, to avoid unexpected token usage, \
521                            only 16 KB was sent back to the model.",
522                        format_file_size(self.original_content_len as u64, true),
523                    )
524                };
525                header.child(
526                    h_flex()
527                        .id(("terminal-tool-truncated-label", self.entity_id))
528                        .tooltip(Tooltip::text(tooltip))
529                        .gap_1()
530                        .child(
531                            Icon::new(IconName::Info)
532                                .size(IconSize::XSmall)
533                                .color(Color::Ignored),
534                        )
535                        .child(
536                            Label::new("Truncated")
537                                .color(Color::Muted)
538                                .size(LabelSize::Small),
539                        ),
540                )
541            })
542            .when(time_elapsed > Duration::from_secs(10), |header| {
543                header.child(
544                    Label::new(format!("({})", duration_alt_display(time_elapsed)))
545                        .buffer_font(cx)
546                        .color(Color::Muted)
547                        .size(LabelSize::Small),
548                )
549            })
550            .when(tool_failed || command_failed, |header| {
551                header.child(
552                    div()
553                        .id(("terminal-tool-error-code-indicator", self.entity_id))
554                        .child(
555                            Icon::new(IconName::Close)
556                                .size(IconSize::Small)
557                                .color(Color::Error),
558                        )
559                        .when(command_failed && self.exit_status.is_some(), |this| {
560                            this.tooltip(Tooltip::text(format!(
561                                "Exited with code {}",
562                                self.exit_status
563                                    .and_then(|status| status.code())
564                                    .unwrap_or(-1),
565                            )))
566                        })
567                        .when(
568                            !command_failed && tool_failed && status.error().is_some(),
569                            |this| {
570                                this.tooltip(Tooltip::text(format!(
571                                    "Error: {}",
572                                    status.error().unwrap(),
573                                )))
574                            },
575                        ),
576                )
577            })
578            .when(!should_hide_terminal, |header| {
579                header.child(
580                    Disclosure::new(
581                        ("terminal-tool-disclosure", self.entity_id),
582                        self.preview_expanded,
583                    )
584                    .opened_icon(IconName::ChevronUp)
585                    .closed_icon(IconName::ChevronDown)
586                    .on_click(cx.listener(
587                        move |this, _event, _window, _cx| {
588                            this.preview_expanded = !this.preview_expanded;
589                        },
590                    )),
591                )
592            });
593
594        v_flex()
595            .mb_2()
596            .border_1()
597            .when(tool_failed || command_failed, |card| card.border_dashed())
598            .border_color(border_color)
599            .rounded_lg()
600            .overflow_hidden()
601            .child(
602                v_flex()
603                    .p_2()
604                    .gap_0p5()
605                    .bg(header_bg)
606                    .text_xs()
607                    .child(header)
608                    .child(
609                        MarkdownElement::new(
610                            self.input_command.clone(),
611                            markdown_style(window, cx),
612                        )
613                        .code_block_renderer(
614                            markdown::CodeBlockRenderer::Default {
615                                copy_button: false,
616                                copy_button_on_hover: true,
617                                border: false,
618                            },
619                        ),
620                    ),
621            )
622            .when(self.preview_expanded && !should_hide_terminal, |this| {
623                this.child(
624                    div()
625                        .pt_2()
626                        .min_h_72()
627                        .border_t_1()
628                        .border_color(border_color)
629                        .bg(cx.theme().colors().editor_background)
630                        .rounded_b_md()
631                        .text_ui_sm(cx)
632                        .child(terminal.clone()),
633                )
634            })
635            .into_any()
636    }
637}
638
639fn markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
640    let theme_settings = ThemeSettings::get_global(cx);
641    let buffer_font_size = TextSize::Default.rems(cx);
642    let mut text_style = window.text_style();
643
644    text_style.refine(&TextStyleRefinement {
645        font_family: Some(theme_settings.buffer_font.family.clone()),
646        font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
647        font_features: Some(theme_settings.buffer_font.features.clone()),
648        font_size: Some(buffer_font_size.into()),
649        color: Some(cx.theme().colors().text),
650        ..Default::default()
651    });
652
653    MarkdownStyle {
654        base_text_style: text_style.clone(),
655        selection_background_color: cx.theme().players().local().selection,
656        ..Default::default()
657    }
658}
659
660#[cfg(test)]
661mod tests {
662    use editor::EditorSettings;
663    use fs::RealFs;
664    use gpui::{BackgroundExecutor, TestAppContext};
665    use language_model::fake_provider::FakeLanguageModel;
666    use pretty_assertions::assert_eq;
667    use serde_json::json;
668    use settings::{Settings, SettingsStore};
669    use terminal::terminal_settings::TerminalSettings;
670    use theme::ThemeSettings;
671    use util::{ResultExt as _, test::TempTree};
672
673    use super::*;
674
675    fn init_test(executor: &BackgroundExecutor, cx: &mut TestAppContext) {
676        zlog::init_test();
677
678        executor.allow_parking();
679        cx.update(|cx| {
680            let settings_store = SettingsStore::test(cx);
681            cx.set_global(settings_store);
682            language::init(cx);
683            Project::init_settings(cx);
684            workspace::init_settings(cx);
685            ThemeSettings::register(cx);
686            TerminalSettings::register(cx);
687            EditorSettings::register(cx);
688        });
689    }
690
691    #[gpui::test]
692    async fn test_interactive_command(executor: BackgroundExecutor, cx: &mut TestAppContext) {
693        if cfg!(windows) {
694            return;
695        }
696
697        init_test(&executor, cx);
698
699        let fs = Arc::new(RealFs::new(None, executor));
700        let tree = TempTree::new(json!({
701            "project": {},
702        }));
703        let project: Entity<Project> =
704            Project::test(fs, [tree.path().join("project").as_path()], cx).await;
705        let action_log = cx.update(|cx| cx.new(|_| ActionLog::new(project.clone())));
706        let model = Arc::new(FakeLanguageModel::default());
707
708        let input = TerminalToolInput {
709            command: "cat".to_owned(),
710            cd: tree
711                .path()
712                .join("project")
713                .as_path()
714                .to_string_lossy()
715                .to_string(),
716        };
717        let result = cx.update(|cx| {
718            TerminalTool::run(
719                Arc::new(TerminalTool::new(cx)),
720                serde_json::to_value(input).unwrap(),
721                Arc::default(),
722                project.clone(),
723                action_log.clone(),
724                model,
725                None,
726                cx,
727            )
728        });
729
730        let output = result.output.await.log_err().unwrap().content;
731        assert_eq!(output.as_str().unwrap(), "Command executed successfully.");
732    }
733
734    #[gpui::test]
735    async fn test_working_directory(executor: BackgroundExecutor, cx: &mut TestAppContext) {
736        if cfg!(windows) {
737            return;
738        }
739
740        init_test(&executor, cx);
741
742        let fs = Arc::new(RealFs::new(None, executor));
743        let tree = TempTree::new(json!({
744            "project": {},
745            "other-project": {},
746        }));
747        let project: Entity<Project> =
748            Project::test(fs, [tree.path().join("project").as_path()], cx).await;
749        let action_log = cx.update(|cx| cx.new(|_| ActionLog::new(project.clone())));
750        let model = Arc::new(FakeLanguageModel::default());
751
752        let check = |input, expected, cx: &mut App| {
753            let headless_result = TerminalTool::run(
754                Arc::new(TerminalTool::new(cx)),
755                serde_json::to_value(input).unwrap(),
756                Arc::default(),
757                project.clone(),
758                action_log.clone(),
759                model.clone(),
760                None,
761                cx,
762            );
763            cx.spawn(async move |_| {
764                let output = headless_result.output.await.map(|output| output.content);
765                assert_eq!(
766                    output
767                        .ok()
768                        .and_then(|content| content.as_str().map(ToString::to_string)),
769                    expected
770                );
771            })
772        };
773
774        cx.update(|cx| {
775            check(
776                TerminalToolInput {
777                    command: "pwd".into(),
778                    cd: ".".into(),
779                },
780                Some(format!(
781                    "```\n{}\n```",
782                    tree.path().join("project").display()
783                )),
784                cx,
785            )
786        })
787        .await;
788
789        cx.update(|cx| {
790            check(
791                TerminalToolInput {
792                    command: "pwd".into(),
793                    cd: "other-project".into(),
794                },
795                None, // other-project is a dir, but *not* a worktree (yet)
796                cx,
797            )
798        })
799        .await;
800
801        // Absolute path above the worktree root
802        cx.update(|cx| {
803            check(
804                TerminalToolInput {
805                    command: "pwd".into(),
806                    cd: tree.path().to_string_lossy().into(),
807                },
808                None,
809                cx,
810            )
811        })
812        .await;
813
814        project
815            .update(cx, |project, cx| {
816                project.create_worktree(tree.path().join("other-project"), true, cx)
817            })
818            .await
819            .unwrap();
820
821        cx.update(|cx| {
822            check(
823                TerminalToolInput {
824                    command: "pwd".into(),
825                    cd: "other-project".into(),
826                },
827                Some(format!(
828                    "```\n{}\n```",
829                    tree.path().join("other-project").display()
830                )),
831                cx,
832            )
833        })
834        .await;
835
836        cx.update(|cx| {
837            check(
838                TerminalToolInput {
839                    command: "pwd".into(),
840                    cd: ".".into(),
841                },
842                None,
843                cx,
844            )
845        })
846        .await;
847    }
848}